summaryrefslogtreecommitdiff
path: root/modules
diff options
context:
space:
mode:
Diffstat (limited to 'modules')
-rw-r--r--modules/SCsub49
-rw-r--r--modules/arkit/SCsub3
-rw-r--r--modules/arkit/arkit.gdip18
-rw-r--r--modules/arkit/arkit_interface.h51
-rw-r--r--modules/arkit/arkit_interface.mm385
-rw-r--r--modules/arkit/arkit_module.cpp (renamed from modules/arkit/register_types.cpp)8
-rw-r--r--modules/arkit/arkit_module.h37
-rw-r--r--modules/arkit/arkit_session_delegate.h10
-rw-r--r--modules/arkit/arkit_session_delegate.mm4
-rw-r--r--modules/assimp/SCsub94
-rw-r--r--modules/assimp/editor_scene_importer_assimp.cpp1509
-rw-r--r--modules/assimp/editor_scene_importer_assimp.h149
-rwxr-xr-xmodules/assimp/godot_update_assimp.sh262
-rw-r--r--modules/assimp/import_state.h130
-rw-r--r--modules/assimp/import_utils.h451
-rw-r--r--modules/basis_universal/SCsub17
-rw-r--r--modules/basis_universal/register_types.cpp14
-rw-r--r--modules/basis_universal/register_types.h4
-rw-r--r--modules/basis_universal/texture_basisu.cpp18
-rw-r--r--modules/basis_universal/texture_basisu.h11
-rw-r--r--modules/bmp/image_loader_bmp.cpp66
-rw-r--r--modules/bmp/image_loader_bmp.h4
-rw-r--r--modules/bmp/register_types.cpp4
-rw-r--r--modules/bmp/register_types.h4
-rw-r--r--modules/bullet/SCsub18
-rw-r--r--modules/bullet/area_bullet.cpp38
-rw-r--r--modules/bullet/area_bullet.h40
-rw-r--r--modules/bullet/btRayShape.cpp12
-rw-r--r--modules/bullet/btRayShape.h5
-rw-r--r--modules/bullet/bullet_physics_server.cpp120
-rw-r--r--modules/bullet/bullet_physics_server.h389
-rw-r--r--modules/bullet/bullet_types_converter.cpp63
-rw-r--r--modules/bullet/bullet_types_converter.h4
-rw-r--r--modules/bullet/bullet_utilities.h4
-rw-r--r--modules/bullet/collision_object_bullet.cpp47
-rw-r--r--modules/bullet/collision_object_bullet.h46
-rw-r--r--modules/bullet/cone_twist_joint_bullet.cpp6
-rw-r--r--modules/bullet/cone_twist_joint_bullet.h4
-rw-r--r--modules/bullet/constraint_bullet.cpp9
-rw-r--r--modules/bullet/constraint_bullet.h11
-rw-r--r--modules/bullet/generic_6dof_joint_bullet.cpp13
-rw-r--r--modules/bullet/generic_6dof_joint_bullet.h7
-rw-r--r--modules/bullet/godot_collision_configuration.cpp26
-rw-r--r--modules/bullet/godot_collision_configuration.h4
-rw-r--r--modules/bullet/godot_collision_dispatcher.cpp4
-rw-r--r--modules/bullet/godot_collision_dispatcher.h6
-rw-r--r--modules/bullet/godot_motion_state.h5
-rw-r--r--modules/bullet/godot_ray_world_algorithm.cpp16
-rw-r--r--modules/bullet/godot_ray_world_algorithm.h12
-rw-r--r--modules/bullet/godot_result_callbacks.cpp71
-rw-r--r--modules/bullet/godot_result_callbacks.h43
-rw-r--r--modules/bullet/hinge_joint_bullet.cpp12
-rw-r--r--modules/bullet/hinge_joint_bullet.h4
-rw-r--r--modules/bullet/joint_bullet.cpp4
-rw-r--r--modules/bullet/joint_bullet.h5
-rw-r--r--modules/bullet/pin_joint_bullet.cpp5
-rw-r--r--modules/bullet/pin_joint_bullet.h4
-rw-r--r--modules/bullet/register_types.cpp8
-rw-r--r--modules/bullet/register_types.h4
-rw-r--r--modules/bullet/rid_bullet.h6
-rw-r--r--modules/bullet/rigid_body_bullet.cpp166
-rw-r--r--modules/bullet/rigid_body_bullet.h123
-rw-r--r--modules/bullet/shape_bullet.cpp45
-rw-r--r--modules/bullet/shape_bullet.h25
-rw-r--r--modules/bullet/shape_owner_bullet.cpp4
-rw-r--r--modules/bullet/shape_owner_bullet.h4
-rw-r--r--modules/bullet/slider_joint_bullet.cpp164
-rw-r--r--modules/bullet/slider_joint_bullet.h4
-rw-r--r--modules/bullet/soft_body_bullet.cpp46
-rw-r--r--modules/bullet/soft_body_bullet.h27
-rw-r--r--modules/bullet/space_bullet.cpp179
-rw-r--r--modules/bullet/space_bullet.h92
-rw-r--r--modules/camera/SCsub9
-rw-r--r--modules/camera/camera_osx.h4
-rw-r--r--modules/camera/camera_osx.mm10
-rw-r--r--modules/camera/camera_win.cpp20
-rw-r--r--modules/camera/camera_win.h6
-rw-r--r--modules/camera/config.py2
-rw-r--r--modules/camera/register_types.cpp10
-rw-r--r--modules/camera/register_types.h9
-rw-r--r--modules/camera_iphone/SCsub15
-rw-r--r--modules/camera_iphone/camera.gdip18
-rw-r--r--modules/camera_iphone/camera_ios.h (renamed from modules/camera/camera_ios.h)4
-rw-r--r--modules/camera_iphone/camera_ios.mm (renamed from modules/camera/camera_ios.mm)121
-rw-r--r--modules/camera_iphone/camera_module.cpp40
-rw-r--r--modules/camera_iphone/camera_module.h32
-rw-r--r--modules/camera_iphone/config.py6
-rw-r--r--modules/csg/csg.cpp316
-rw-r--r--modules/csg/csg.h18
-rw-r--r--modules/csg/csg_gizmos.cpp123
-rw-r--r--modules/csg/csg_gizmos.h25
-rw-r--r--modules/csg/csg_shape.cpp348
-rw-r--r--modules/csg/csg_shape.h47
-rw-r--r--modules/csg/doc_classes/CSGBox3D.xml10
-rw-r--r--modules/csg/doc_classes/CSGShape3D.xml4
-rw-r--r--modules/csg/icons/CSGBox3D.svg7
-rw-r--r--modules/csg/icons/CSGCapsule3D.svg7
-rw-r--r--modules/csg/icons/CSGCombiner3D.svg9
-rw-r--r--modules/csg/icons/CSGCylinder3D.svg7
-rw-r--r--modules/csg/icons/CSGMesh3D.svg7
-rw-r--r--modules/csg/icons/CSGPolygon3D.svg7
-rw-r--r--modules/csg/icons/CSGSphere3D.svg7
-rw-r--r--modules/csg/icons/CSGTorus3D.svg7
-rw-r--r--modules/csg/register_types.cpp5
-rw-r--r--modules/csg/register_types.h4
-rw-r--r--modules/cvtt/SCsub15
-rw-r--r--modules/cvtt/image_compress_cvtt.cpp27
-rw-r--r--modules/cvtt/image_compress_cvtt.h6
-rw-r--r--modules/cvtt/register_types.cpp5
-rw-r--r--modules/cvtt/register_types.h12
-rw-r--r--modules/dds/register_types.cpp6
-rw-r--r--modules/dds/register_types.h4
-rw-r--r--modules/dds/texture_loader_dds.cpp94
-rw-r--r--modules/dds/texture_loader_dds.h4
-rw-r--r--modules/denoise/SCsub129
-rw-r--r--modules/denoise/config.py12
-rw-r--r--modules/denoise/denoise_wrapper.cpp64
-rw-r--r--modules/denoise/denoise_wrapper.h38
-rw-r--r--modules/denoise/lightmap_denoiser.cpp62
-rw-r--r--modules/denoise/lightmap_denoiser.h (renamed from modules/mono/glue/string_name_glue.h)38
-rw-r--r--modules/denoise/register_types.cpp40
-rw-r--r--modules/denoise/register_types.h37
-rw-r--r--modules/denoise/resource_to_cpp.py68
-rw-r--r--modules/enet/SCsub16
-rw-r--r--modules/enet/doc_classes/NetworkedMultiplayerENet.xml10
-rw-r--r--modules/enet/networked_multiplayer_enet.cpp111
-rw-r--r--modules/enet/networked_multiplayer_enet.h34
-rw-r--r--modules/enet/register_types.cpp11
-rw-r--r--modules/enet/register_types.h4
-rw-r--r--modules/etc/SCsub15
-rw-r--r--modules/etc/image_compress_etc.cpp (renamed from modules/etc/image_etc.cpp)37
-rw-r--r--modules/etc/image_compress_etc.h (renamed from modules/etc/image_etc.h)12
-rw-r--r--modules/etc/register_types.cpp8
-rw-r--r--modules/etc/register_types.h4
-rw-r--r--modules/etc/texture_loader_pkm.cpp23
-rw-r--r--modules/etc/texture_loader_pkm.h4
-rw-r--r--modules/fbx/README.md196
-rw-r--r--modules/fbx/SCsub15
-rw-r--r--modules/fbx/config.py16
-rw-r--r--modules/fbx/data/fbx_anim_container.h46
-rw-r--r--modules/fbx/data/fbx_bone.cpp56
-rw-r--r--modules/fbx/data/fbx_bone.h (renamed from modules/mono/glue/base_object_glue.h)77
-rw-r--r--modules/fbx/data/fbx_material.cpp464
-rw-r--r--modules/fbx/data/fbx_material.h286
-rw-r--r--modules/fbx/data/fbx_mesh_data.cpp1447
-rw-r--r--modules/fbx/data/fbx_mesh_data.h184
-rw-r--r--modules/fbx/data/fbx_node.h63
-rw-r--r--modules/fbx/data/fbx_skeleton.cpp123
-rw-r--r--modules/fbx/data/fbx_skeleton.h53
-rw-r--r--modules/fbx/data/import_state.h113
-rw-r--r--modules/fbx/data/model_abstraction.h (renamed from modules/mono/glue/rid_glue.h)39
-rw-r--r--modules/fbx/data/pivot_transform.cpp294
-rw-r--r--modules/fbx/data/pivot_transform.h115
-rw-r--r--modules/fbx/doc_classes/EditorSceneImporterFBX.xml36
-rw-r--r--modules/fbx/editor_scene_importer_fbx.cpp1427
-rw-r--r--modules/fbx/editor_scene_importer_fbx.h135
-rw-r--r--modules/fbx/fbx_parser/ByteSwapper.h282
-rw-r--r--modules/fbx/fbx_parser/CREDITS183
-rw-r--r--modules/fbx/fbx_parser/FBXAnimation.cpp290
-rw-r--r--modules/fbx/fbx_parser/FBXBinaryTokenizer.cpp467
-rw-r--r--modules/fbx/fbx_parser/FBXCommon.h110
-rw-r--r--modules/fbx/fbx_parser/FBXDeformer.cpp279
-rw-r--r--modules/fbx/fbx_parser/FBXDocument.cpp713
-rw-r--r--modules/fbx/fbx_parser/FBXDocument.h1319
-rw-r--r--modules/fbx/fbx_parser/FBXDocumentUtil.cpp172
-rw-r--r--modules/fbx/fbx_parser/FBXDocumentUtil.h141
-rw-r--r--modules/fbx/fbx_parser/FBXImportSettings.h173
-rw-r--r--modules/fbx/fbx_parser/FBXMaterial.cpp407
-rw-r--r--modules/fbx/fbx_parser/FBXMeshGeometry.cpp485
-rw-r--r--modules/fbx/fbx_parser/FBXMeshGeometry.h263
-rw-r--r--modules/fbx/fbx_parser/FBXModel.cpp176
-rw-r--r--modules/fbx/fbx_parser/FBXNodeAttribute.cpp183
-rw-r--r--modules/fbx/fbx_parser/FBXParseTools.h111
-rw-r--r--modules/fbx/fbx_parser/FBXParser.cpp1295
-rw-r--r--modules/fbx/fbx_parser/FBXParser.h263
-rw-r--r--modules/fbx/fbx_parser/FBXPose.cpp104
-rw-r--r--modules/fbx/fbx_parser/FBXProperties.cpp237
-rw-r--r--modules/fbx/fbx_parser/FBXProperties.h221
-rw-r--r--modules/fbx/fbx_parser/FBXTokenizer.cpp251
-rw-r--r--modules/fbx/fbx_parser/FBXTokenizer.h203
-rw-r--r--modules/fbx/fbx_parser/FBXUtil.cpp220
-rw-r--r--modules/fbx/fbx_parser/FBXUtil.h122
-rw-r--r--modules/fbx/fbx_parser/LICENSE39
-rw-r--r--modules/fbx/register_types.cpp (renamed from modules/assimp/register_types.cpp)19
-rw-r--r--modules/fbx/register_types.h (renamed from modules/assimp/register_types.h)14
-rw-r--r--modules/fbx/tools/import_utils.cpp151
-rw-r--r--modules/fbx/tools/import_utils.h400
-rw-r--r--modules/fbx/tools/validation_tools.cpp48
-rw-r--r--modules/fbx/tools/validation_tools.h92
-rw-r--r--modules/freetype/SCsub14
-rw-r--r--modules/freetype/register_types.cpp4
-rw-r--r--modules/freetype/register_types.h4
-rw-r--r--modules/freetype/uwpdef.h4
-rw-r--r--modules/gamecenter/SCsub15
-rw-r--r--modules/gamecenter/config.py6
-rw-r--r--modules/gamecenter/game_center.h71
-rw-r--r--modules/gamecenter/game_center.mm380
-rw-r--r--modules/gamecenter/game_center_delegate.h35
-rw-r--r--modules/gamecenter/game_center_delegate.mm45
-rw-r--r--modules/gamecenter/game_center_module.cpp48
-rw-r--r--modules/gamecenter/game_center_module.h32
-rw-r--r--modules/gamecenter/gamecenter.gdip17
-rw-r--r--modules/gdnative/SCsub6
-rw-r--r--modules/gdnative/android/android_gdn.cpp4
-rw-r--r--modules/gdnative/config.py3
-rw-r--r--modules/gdnative/doc_classes/@NativeScript.xml13
-rw-r--r--modules/gdnative/doc_classes/GDNativeLibrary.xml4
-rw-r--r--modules/gdnative/gdnative.cpp53
-rw-r--r--modules/gdnative/gdnative.h6
-rw-r--r--modules/gdnative/gdnative/aabb.cpp15
-rw-r--r--modules/gdnative/gdnative/array.cpp60
-rw-r--r--modules/gdnative/gdnative/basis.cpp8
-rw-r--r--modules/gdnative/gdnative/callable.cpp252
-rw-r--r--modules/gdnative/gdnative/color.cpp19
-rw-r--r--modules/gdnative/gdnative/dictionary.cpp16
-rw-r--r--modules/gdnative/gdnative/gdnative.cpp36
-rw-r--r--modules/gdnative/gdnative/node_path.cpp10
-rw-r--r--modules/gdnative/gdnative/packed_arrays.cpp1141
-rw-r--r--modules/gdnative/gdnative/plane.cpp16
-rw-r--r--modules/gdnative/gdnative/pool_arrays.cpp666
-rw-r--r--modules/gdnative/gdnative/quat.cpp9
-rw-r--r--modules/gdnative/gdnative/rect2.cpp170
-rw-r--r--modules/gdnative/gdnative/rid.cpp12
-rw-r--r--modules/gdnative/gdnative/string.cpp687
-rw-r--r--modules/gdnative/gdnative/string_name.cpp10
-rw-r--r--modules/gdnative/gdnative/transform.cpp8
-rw-r--r--modules/gdnative/gdnative/transform2d.cpp8
-rw-r--r--modules/gdnative/gdnative/variant.cpp145
-rw-r--r--modules/gdnative/gdnative/vector2.cpp162
-rw-r--r--modules/gdnative/gdnative/vector3.cpp155
-rw-r--r--modules/gdnative/gdnative_api.json6682
-rw-r--r--modules/gdnative/gdnative_builders.py16
-rw-r--r--modules/gdnative/gdnative_library_editor_plugin.cpp86
-rw-r--r--modules/gdnative/gdnative_library_editor_plugin.h16
-rw-r--r--modules/gdnative/gdnative_library_singleton_editor.cpp22
-rw-r--r--modules/gdnative/gdnative_library_singleton_editor.h4
-rw-r--r--modules/gdnative/icons/GDNativeLibrary.svg6
-rw-r--r--modules/gdnative/icons/NativeScript.svg6
-rw-r--r--modules/gdnative/include/android/godot_android.h4
-rw-r--r--modules/gdnative/include/gdnative/aabb.h6
-rw-r--r--modules/gdnative/include/gdnative/array.h15
-rw-r--r--modules/gdnative/include/gdnative/basis.h4
-rw-r--r--modules/gdnative/include/gdnative/callable.h126
-rw-r--r--modules/gdnative/include/gdnative/color.h6
-rw-r--r--modules/gdnative/include/gdnative/dictionary.h6
-rw-r--r--modules/gdnative/include/gdnative/gdnative.h22
-rw-r--r--modules/gdnative/include/gdnative/node_path.h4
-rw-r--r--modules/gdnative/include/gdnative/packed_arrays.h530
-rw-r--r--modules/gdnative/include/gdnative/plane.h6
-rw-r--r--modules/gdnative/include/gdnative/pool_arrays.h340
-rw-r--r--modules/gdnative/include/gdnative/quat.h4
-rw-r--r--modules/gdnative/include/gdnative/rect2.h62
-rw-r--r--modules/gdnative/include/gdnative/rid.h6
-rw-r--r--modules/gdnative/include/gdnative/string.h179
-rw-r--r--modules/gdnative/include/gdnative/string_name.h4
-rw-r--r--modules/gdnative/include/gdnative/transform.h4
-rw-r--r--modules/gdnative/include/gdnative/transform2d.h4
-rw-r--r--modules/gdnative/include/gdnative/variant.h46
-rw-r--r--modules/gdnative/include/gdnative/vector2.h61
-rw-r--r--modules/gdnative/include/gdnative/vector3.h57
-rw-r--r--modules/gdnative/include/nativescript/godot_nativescript.h86
-rw-r--r--modules/gdnative/include/net/godot_net.h5
-rw-r--r--modules/gdnative/include/net/godot_webrtc.h4
-rw-r--r--modules/gdnative/include/pluginscript/godot_pluginscript.h6
-rw-r--r--modules/gdnative/include/text/godot_text.h231
-rw-r--r--modules/gdnative/include/videodecoder/godot_videodecoder.h6
-rw-r--r--modules/gdnative/include/xr/godot_xr.h4
-rw-r--r--modules/gdnative/nativescript/api_generator.cpp38
-rw-r--r--modules/gdnative/nativescript/api_generator.h6
-rw-r--r--modules/gdnative/nativescript/godot_nativescript.cpp46
-rw-r--r--modules/gdnative/nativescript/nativescript.cpp249
-rw-r--r--modules/gdnative/nativescript/nativescript.h136
-rw-r--r--modules/gdnative/nativescript/register_types.cpp5
-rw-r--r--modules/gdnative/nativescript/register_types.h4
-rw-r--r--modules/gdnative/net/multiplayer_peer_gdnative.cpp5
-rw-r--r--modules/gdnative/net/multiplayer_peer_gdnative.h32
-rw-r--r--modules/gdnative/net/packet_peer_gdnative.cpp5
-rw-r--r--modules/gdnative/net/packet_peer_gdnative.h12
-rw-r--r--modules/gdnative/net/register_types.cpp4
-rw-r--r--modules/gdnative/net/register_types.h4
-rw-r--r--modules/gdnative/net/stream_peer_gdnative.cpp4
-rw-r--r--modules/gdnative/net/stream_peer_gdnative.h15
-rw-r--r--modules/gdnative/net/webrtc_gdnative.cpp6
-rw-r--r--modules/gdnative/pluginscript/pluginscript_instance.cpp6
-rw-r--r--modules/gdnative/pluginscript/pluginscript_instance.h12
-rw-r--r--modules/gdnative/pluginscript/pluginscript_language.cpp36
-rw-r--r--modules/gdnative/pluginscript/pluginscript_language.h17
-rw-r--r--modules/gdnative/pluginscript/pluginscript_loader.cpp15
-rw-r--r--modules/gdnative/pluginscript/pluginscript_loader.h8
-rw-r--r--modules/gdnative/pluginscript/pluginscript_script.cpp48
-rw-r--r--modules/gdnative/pluginscript/pluginscript_script.h101
-rw-r--r--modules/gdnative/pluginscript/register_types.cpp6
-rw-r--r--modules/gdnative/pluginscript/register_types.h4
-rw-r--r--modules/gdnative/register_types.cpp126
-rw-r--r--modules/gdnative/register_types.h4
-rw-r--r--modules/gdnative/tests/test_string.h1979
-rw-r--r--modules/gdnative/text/SCsub6
-rw-r--r--modules/gdnative/text/config.py (renamed from modules/gdnative/xr/config.py)0
-rw-r--r--modules/gdnative/text/register_types.cpp36
-rw-r--r--modules/gdnative/text/register_types.h37
-rw-r--r--modules/gdnative/text/text_server_gdnative.cpp853
-rw-r--r--modules/gdnative/text/text_server_gdnative.h187
-rw-r--r--modules/gdnative/videodecoder/register_types.cpp8
-rw-r--r--modules/gdnative/videodecoder/register_types.h4
-rw-r--r--modules/gdnative/videodecoder/video_stream_gdnative.cpp54
-rw-r--r--modules/gdnative/videodecoder/video_stream_gdnative.h87
-rw-r--r--modules/gdnative/xr/register_types.cpp4
-rw-r--r--modules/gdnative/xr/register_types.h4
-rw-r--r--modules/gdnative/xr/xr_interface_gdnative.cpp20
-rw-r--r--modules/gdnative/xr/xr_interface_gdnative.h36
-rw-r--r--modules/gdnavigation/SCsub31
-rw-r--r--modules/gdnavigation/gd_navigation_server.cpp14
-rw-r--r--modules/gdnavigation/gd_navigation_server.h10
-rw-r--r--modules/gdnavigation/nav_map.cpp65
-rw-r--r--modules/gdnavigation/nav_map.h23
-rw-r--r--modules/gdnavigation/nav_region.cpp17
-rw-r--r--modules/gdnavigation/nav_region.h10
-rw-r--r--modules/gdnavigation/nav_rid.h6
-rw-r--r--modules/gdnavigation/nav_utils.h50
-rw-r--r--modules/gdnavigation/navigation_mesh_editor_plugin.cpp26
-rw-r--r--modules/gdnavigation/navigation_mesh_editor_plugin.h19
-rw-r--r--modules/gdnavigation/navigation_mesh_generator.cpp77
-rw-r--r--modules/gdnavigation/navigation_mesh_generator.h4
-rw-r--r--modules/gdnavigation/register_types.cpp6
-rw-r--r--modules/gdnavigation/register_types.h4
-rw-r--r--modules/gdnavigation/rvo_agent.cpp7
-rw-r--r--modules/gdnavigation/rvo_agent.h9
-rw-r--r--modules/gdscript/SCsub4
-rw-r--r--modules/gdscript/config.py1
-rw-r--r--modules/gdscript/doc_classes/@GDScript.xml1228
-rw-r--r--modules/gdscript/doc_classes/GDScript.xml2
-rw-r--r--modules/gdscript/doc_classes/GDScriptFunctionState.xml44
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.cpp400
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.h33
-rw-r--r--modules/gdscript/editor/gdscript_translation_parser_plugin.cpp351
-rw-r--r--modules/gdscript/editor/gdscript_translation_parser_plugin.h73
-rw-r--r--modules/gdscript/gdscript.cpp1179
-rw-r--r--modules/gdscript/gdscript.h208
-rw-r--r--modules/gdscript/gdscript_analyzer.cpp3446
-rw-r--r--modules/gdscript/gdscript_analyzer.h126
-rw-r--r--modules/gdscript/gdscript_byte_codegen.cpp1282
-rw-r--r--modules/gdscript/gdscript_byte_codegen.h474
-rw-r--r--modules/gdscript/gdscript_cache.cpp255
-rw-r--r--modules/gdscript/gdscript_cache.h97
-rw-r--r--modules/gdscript/gdscript_codegen.h167
-rw-r--r--modules/gdscript/gdscript_compiler.cpp3279
-rw-r--r--modules/gdscript/gdscript_compiler.h161
-rw-r--r--modules/gdscript/gdscript_disassembler.cpp842
-rw-r--r--modules/gdscript/gdscript_editor.cpp3649
-rw-r--r--modules/gdscript/gdscript_function.cpp1725
-rw-r--r--modules/gdscript/gdscript_function.h272
-rw-r--r--modules/gdscript/gdscript_functions.cpp2065
-rw-r--r--modules/gdscript/gdscript_functions.h137
-rw-r--r--modules/gdscript/gdscript_parser.cpp11328
-rw-r--r--modules/gdscript/gdscript_parser.h1716
-rw-r--r--modules/gdscript/gdscript_tokenizer.cpp2589
-rw-r--r--modules/gdscript/gdscript_tokenizer.h459
-rw-r--r--modules/gdscript/gdscript_utility_functions.cpp718
-rw-r--r--modules/gdscript/gdscript_utility_functions.h58
-rw-r--r--modules/gdscript/gdscript_vm.cpp2918
-rw-r--r--modules/gdscript/gdscript_warning.cpp210
-rw-r--r--modules/gdscript/gdscript_warning.h87
-rw-r--r--modules/gdscript/icons/GDScript.svg6
-rw-r--r--modules/gdscript/language_server/gdscript_extend_parser.cpp648
-rw-r--r--modules/gdscript/language_server/gdscript_extend_parser.h7
-rw-r--r--modules/gdscript/language_server/gdscript_language_protocol.cpp43
-rw-r--r--modules/gdscript/language_server/gdscript_language_protocol.h10
-rw-r--r--modules/gdscript/language_server/gdscript_language_server.cpp6
-rw-r--r--modules/gdscript/language_server/gdscript_language_server.h4
-rw-r--r--modules/gdscript/language_server/gdscript_text_document.cpp30
-rw-r--r--modules/gdscript/language_server/gdscript_text_document.h6
-rw-r--r--modules/gdscript/language_server/gdscript_workspace.cpp77
-rw-r--r--modules/gdscript/language_server/gdscript_workspace.h6
-rw-r--r--modules/gdscript/language_server/lsp.hpp76
-rw-r--r--modules/gdscript/register_types.cpp143
-rw-r--r--modules/gdscript/register_types.h4
-rw-r--r--modules/gdscript/tests/test_gdscript.cpp306
-rw-r--r--modules/gdscript/tests/test_gdscript.h46
-rw-r--r--modules/glslang/SCsub24
-rw-r--r--modules/glslang/register_types.cpp119
-rw-r--r--modules/glslang/register_types.h4
-rw-r--r--modules/gltf/SCsub10
-rw-r--r--modules/gltf/config.py6
-rw-r--r--modules/gltf/editor_scene_exporter_gltf_plugin.cpp90
-rw-r--r--modules/gltf/editor_scene_exporter_gltf_plugin.h (renamed from modules/mono/glue/string_glue.h)44
-rw-r--r--modules/gltf/editor_scene_importer_gltf.cpp180
-rw-r--r--modules/gltf/editor_scene_importer_gltf.h96
-rw-r--r--modules/gltf/gltf_accessor.cpp189
-rw-r--r--modules/gltf/gltf_accessor.h104
-rw-r--r--modules/gltf/gltf_animation.cpp53
-rw-r--r--modules/gltf/gltf_animation.h74
-rw-r--r--modules/gltf/gltf_buffer_view.cpp90
-rw-r--r--modules/gltf/gltf_buffer_view.h68
-rw-r--r--modules/gltf/gltf_camera.cpp47
-rw-r--r--modules/gltf/gltf_camera.h58
-rw-r--r--modules/gltf/gltf_document.cpp6540
-rw-r--r--modules/gltf/gltf_document.h428
-rw-r--r--modules/gltf/gltf_light.cpp101
-rw-r--r--modules/gltf/gltf_light.h72
-rw-r--r--modules/gltf/gltf_mesh.cpp58
-rw-r--r--modules/gltf/gltf_mesh.h55
-rw-r--r--modules/gltf/gltf_node.cpp189
-rw-r--r--modules/gltf/gltf_node.h105
-rw-r--r--modules/gltf/gltf_skeleton.cpp95
-rw-r--r--modules/gltf/gltf_skeleton.h101
-rw-r--r--modules/gltf/gltf_skin.cpp155
-rw-r--r--modules/gltf/gltf_skin.h109
-rw-r--r--modules/gltf/gltf_spec_gloss.cpp90
-rw-r--r--modules/gltf/gltf_spec_gloss.h67
-rw-r--r--modules/gltf/gltf_state.cpp296
-rw-r--r--modules/gltf/gltf_state.h180
-rw-r--r--modules/gltf/gltf_texture.cpp46
-rw-r--r--modules/gltf/gltf_texture.h51
-rw-r--r--modules/gltf/register_types.cpp88
-rw-r--r--modules/gltf/register_types.h (renamed from modules/arkit/register_types.h)8
-rw-r--r--modules/gridmap/doc_classes/GridMap.xml44
-rw-r--r--modules/gridmap/grid_map.cpp248
-rw-r--r--modules/gridmap/grid_map.h32
-rw-r--r--modules/gridmap/grid_map_editor_plugin.cpp303
-rw-r--r--modules/gridmap/grid_map_editor_plugin.h34
-rw-r--r--modules/gridmap/icons/GridMap.svg6
-rw-r--r--modules/gridmap/register_types.cpp7
-rw-r--r--modules/gridmap/register_types.h4
-rw-r--r--modules/hdr/image_loader_hdr.cpp19
-rw-r--r--modules/hdr/image_loader_hdr.h5
-rw-r--r--modules/hdr/register_types.cpp6
-rw-r--r--modules/hdr/register_types.h4
-rw-r--r--modules/icloud/SCsub15
-rw-r--r--modules/icloud/config.py6
-rw-r--r--modules/icloud/icloud.gdip17
-rw-r--r--modules/icloud/icloud.h60
-rw-r--r--modules/icloud/icloud.mm345
-rw-r--r--modules/icloud/icloud_module.cpp48
-rw-r--r--modules/icloud/icloud_module.h32
-rw-r--r--modules/inappstore/SCsub15
-rw-r--r--modules/inappstore/config.py6
-rw-r--r--modules/inappstore/in_app_store.h (renamed from modules/mono/glue/nodepath_glue.h)65
-rw-r--r--modules/inappstore/in_app_store.mm411
-rw-r--r--modules/inappstore/in_app_store_module.cpp48
-rw-r--r--modules/inappstore/in_app_store_module.h32
-rw-r--r--modules/inappstore/inappstore.gdip17
-rw-r--r--modules/jpg/SCsub17
-rw-r--r--modules/jpg/image_loader_jpegd.cpp24
-rw-r--r--modules/jpg/image_loader_jpegd.h5
-rw-r--r--modules/jpg/register_types.cpp6
-rw-r--r--modules/jpg/register_types.h4
-rw-r--r--modules/jsonrpc/jsonrpc.cpp15
-rw-r--r--modules/jsonrpc/jsonrpc.h8
-rw-r--r--modules/jsonrpc/register_types.cpp6
-rw-r--r--modules/jsonrpc/register_types.h4
-rw-r--r--modules/lightmapper_rd/SCsub12
-rw-r--r--modules/lightmapper_rd/config.py (renamed from modules/assimp/config.py)2
-rw-r--r--modules/lightmapper_rd/lightmapper_rd.cpp1751
-rw-r--r--modules/lightmapper_rd/lightmapper_rd.h258
-rw-r--r--modules/lightmapper_rd/lm_blendseams.glsl108
-rw-r--r--modules/lightmapper_rd/lm_common_inc.glsl92
-rw-r--r--modules/lightmapper_rd/lm_compute.glsl653
-rw-r--r--modules/lightmapper_rd/lm_raster.glsl157
-rw-r--r--modules/lightmapper_rd/register_types.cpp63
-rw-r--r--modules/lightmapper_rd/register_types.h37
-rwxr-xr-xmodules/mbedtls/SCsub25
-rw-r--r--modules/mbedtls/crypto_mbedtls.cpp243
-rw-r--r--modules/mbedtls/crypto_mbedtls.h44
-rw-r--r--modules/mbedtls/dtls_server_mbedtls.cpp6
-rw-r--r--modules/mbedtls/dtls_server_mbedtls.h5
-rw-r--r--[-rwxr-xr-x]modules/mbedtls/packet_peer_mbed_dtls.cpp37
-rwxr-xr-xmodules/mbedtls/packet_peer_mbed_dtls.h4
-rw-r--r--[-rwxr-xr-x]modules/mbedtls/register_types.cpp10
-rwxr-xr-xmodules/mbedtls/register_types.h4
-rw-r--r--modules/mbedtls/ssl_context_mbedtls.cpp23
-rw-r--r--modules/mbedtls/ssl_context_mbedtls.h8
-rw-r--r--[-rwxr-xr-x]modules/mbedtls/stream_peer_mbedtls.cpp38
-rwxr-xr-xmodules/mbedtls/stream_peer_mbedtls.h4
-rw-r--r--modules/mbedtls/tests/test_crypto_mbedtls.cpp (renamed from modules/mono/editor/csharp_project.cpp)67
-rw-r--r--modules/mbedtls/tests/test_crypto_mbedtls.h61
-rw-r--r--modules/meshoptimizer/SCsub45
-rw-r--r--modules/meshoptimizer/config.py7
-rw-r--r--modules/meshoptimizer/register_types.cpp47
-rw-r--r--modules/meshoptimizer/register_types.h37
-rw-r--r--modules/minimp3/SCsub17
-rw-r--r--modules/minimp3/audio_stream_mp3.cpp231
-rw-r--r--modules/minimp3/audio_stream_mp3.h110
-rw-r--r--modules/minimp3/config.py16
-rw-r--r--modules/minimp3/doc_classes/AudioStreamMP3.xml26
-rw-r--r--modules/minimp3/register_types.cpp52
-rw-r--r--modules/minimp3/register_types.h37
-rw-r--r--modules/minimp3/resource_importer_mp3.cpp104
-rw-r--r--modules/minimp3/resource_importer_mp3.h58
-rw-r--r--modules/mobile_vr/mobile_vr_interface.cpp34
-rw-r--r--modules/mobile_vr/mobile_vr_interface.h28
-rw-r--r--modules/mobile_vr/register_types.cpp12
-rw-r--r--modules/mobile_vr/register_types.h4
-rw-r--r--modules/modules_builders.py11
-rw-r--r--modules/mono/SCsub7
-rw-r--r--modules/mono/build_scripts/godot_net_sdk_build.py45
-rw-r--r--modules/mono/build_scripts/godot_tools_build.py8
-rw-r--r--modules/mono/build_scripts/make_android_mono_config.py5
-rw-r--r--modules/mono/build_scripts/mono_configure.py28
-rw-r--r--modules/mono/build_scripts/mono_reg_utils.py10
-rw-r--r--modules/mono/build_scripts/solution_builder.py151
-rw-r--r--modules/mono/class_db_api_json.cpp30
-rw-r--r--modules/mono/class_db_api_json.h12
-rw-r--r--modules/mono/config.py20
-rw-r--r--modules/mono/csharp_script.cpp957
-rw-r--r--modules/mono/csharp_script.h298
-rw-r--r--modules/mono/doc_classes/@C#.xml13
-rw-r--r--modules/mono/doc_classes/CSharpScript.xml5
-rw-r--r--modules/mono/doc_classes/GodotSharp.xml17
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln16
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj50
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.nuspec22
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk_PackageVersion.txt1
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props112
-rw-r--r--modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets17
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs89
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj58
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs35
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/FileUtils.cs5
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj39
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs26
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs44
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs33
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs94
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs219
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs207
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs24
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs24
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj53
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs21
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs46
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs88
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs35
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/ForwarderMessageHandler.cs57
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj17
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs218
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs351
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientHandshake.cs44
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs52
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotIdeMetadata.cs (renamed from modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs)6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotTools.IdeMessaging.csproj24
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IHandshake.cs8
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ILogger.cs (renamed from modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs)2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IMessageHandler.cs9
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Message.cs52
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/MessageDecoder.cs100
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Peer.cs298
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Requests/Requests.cs129
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ResponseAwaiter.cs23
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/NotifyAwaiter.cs (renamed from modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs)4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/SemaphoreExtensions.cs32
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj12
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/Program.cs270
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs3
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj69
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs56
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe0
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs121
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs160
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs320
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs27
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets36
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj6
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.sln14
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs343
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs (renamed from modules/mono/editor/GodotTools/GodotTools/BuildInfo.cs)16
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs303
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs417
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildResult.cs8
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs99
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs10
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs185
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs112
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs296
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/BuildManager.cs273
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/BuildTab.cs267
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs116
-rwxr-xr-xmodules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs10
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs84
-rwxr-xr-xmodules/mono/editor/GodotTools/GodotTools/Export/XcodeHelper.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs257
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj130
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs163
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs212
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/MessagingServer.cs390
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs20
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs18
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs7
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs10
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/PlaySettings.cs19
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs26
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs48
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs61
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/packages.config5
-rw-r--r--modules/mono/editor/bindings_generator.cpp651
-rw-r--r--modules/mono/editor/bindings_generator.h254
-rw-r--r--modules/mono/editor/code_completion.cpp261
-rw-r--r--modules/mono/editor/code_completion.h56
-rw-r--r--modules/mono/editor/editor_internal_calls.cpp154
-rw-r--r--modules/mono/editor/editor_internal_calls.h4
-rw-r--r--modules/mono/editor/godotsharp_export.cpp99
-rw-r--r--modules/mono/editor/godotsharp_export.h11
-rw-r--r--modules/mono/editor/script_class_parser.cpp100
-rw-r--r--modules/mono/editor/script_class_parser.h22
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs234
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs47
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs294
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs622
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs4
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs17
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs29
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs331
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs49
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs13
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs148
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs242
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs196
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs174
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs207
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs144
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs183
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs337
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs159
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs374
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs143
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj35
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Properties/AssemblyInfo.cs24
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj47
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharpEditor/Properties/AssemblyInfo.cs25
-rw-r--r--modules/mono/glue/arguments_vector.h9
-rw-r--r--modules/mono/glue/base_object_glue.cpp45
-rw-r--r--modules/mono/glue/collections_glue.cpp137
-rw-r--r--modules/mono/glue/collections_glue.h124
-rw-r--r--modules/mono/glue/gd_glue.cpp87
-rw-r--r--modules/mono/glue/glue_header.h39
-rw-r--r--modules/mono/glue/nodepath_glue.cpp37
-rw-r--r--modules/mono/glue/rid_glue.cpp21
-rw-r--r--modules/mono/glue/scene_tree_glue.cpp86
-rw-r--r--modules/mono/glue/string_glue.cpp26
-rw-r--r--modules/mono/glue/string_name_glue.cpp21
-rw-r--r--modules/mono/godotsharp_defs.h4
-rw-r--r--modules/mono/godotsharp_dirs.cpp12
-rw-r--r--modules/mono/godotsharp_dirs.h7
-rw-r--r--modules/mono/icons/CSharpScript.svg6
-rw-r--r--modules/mono/managed_callable.cpp11
-rw-r--r--modules/mono/managed_callable.h8
-rw-r--r--modules/mono/mono_gc_handle.cpp6
-rw-r--r--modules/mono/mono_gc_handle.h17
-rw-r--r--modules/mono/mono_gd/android_mono_config.h6
-rw-r--r--modules/mono/mono_gd/gd_mono.cpp261
-rw-r--r--modules/mono/mono_gd/gd_mono.h56
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.cpp185
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.h27
-rw-r--r--modules/mono/mono_gd/gd_mono_cache.cpp11
-rw-r--r--modules/mono/mono_gd/gd_mono_cache.h6
-rw-r--r--modules/mono/mono_gd/gd_mono_class.cpp114
-rw-r--r--modules/mono/mono_gd/gd_mono_class.h26
-rw-r--r--modules/mono/mono_gd/gd_mono_field.cpp342
-rw-r--r--modules/mono/mono_gd/gd_mono_field.h5
-rw-r--r--modules/mono/mono_gd/gd_mono_header.h6
-rw-r--r--modules/mono/mono_gd/gd_mono_internals.cpp15
-rw-r--r--modules/mono/mono_gd/gd_mono_internals.h7
-rw-r--r--modules/mono/mono_gd/gd_mono_log.cpp55
-rw-r--r--modules/mono/mono_gd/gd_mono_log.h5
-rw-r--r--modules/mono/mono_gd/gd_mono_marshal.cpp1251
-rw-r--r--modules/mono/mono_gd/gd_mono_marshal.h77
-rw-r--r--modules/mono/mono_gd/gd_mono_method.cpp48
-rw-r--r--modules/mono/mono_gd/gd_mono_method.h16
-rw-r--r--modules/mono/mono_gd/gd_mono_method_thunk.h32
-rw-r--r--modules/mono/mono_gd/gd_mono_property.cpp27
-rw-r--r--modules/mono/mono_gd/gd_mono_property.h5
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.cpp62
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.h57
-rw-r--r--modules/mono/mono_gd/gd_mono_wasm_m2n.cpp (renamed from modules/mono/glue/gd_glue.h)83
-rw-r--r--modules/mono/mono_gd/gd_mono_wasm_m2n.h263
-rw-r--r--modules/mono/mono_gd/i_mono_class_member.h4
-rw-r--r--modules/mono/mono_gd/managed_type.cpp4
-rw-r--r--modules/mono/mono_gd/managed_type.h13
-rw-r--r--[-rwxr-xr-x]modules/mono/mono_gd/support/android_support.cpp13
-rwxr-xr-xmodules/mono/mono_gd/support/android_support.h7
-rwxr-xr-xmodules/mono/mono_gd/support/ios_support.h7
-rw-r--r--[-rwxr-xr-x]modules/mono/mono_gd/support/ios_support.mm8
-rw-r--r--modules/mono/register_types.cpp12
-rw-r--r--modules/mono/register_types.h9
-rw-r--r--modules/mono/signal_awaiter_utils.cpp39
-rw-r--r--modules/mono/signal_awaiter_utils.h6
-rw-r--r--modules/mono/utils/macros.h9
-rw-r--r--modules/mono/utils/mono_reg_utils.cpp23
-rw-r--r--modules/mono/utils/mono_reg_utils.h7
-rw-r--r--modules/mono/utils/osx_utils.cpp30
-rw-r--r--modules/mono/utils/osx_utils.h6
-rw-r--r--modules/mono/utils/path_utils.cpp79
-rw-r--r--modules/mono/utils/path_utils.h11
-rw-r--r--modules/mono/utils/string_utils.cpp23
-rw-r--r--modules/mono/utils/string_utils.h8
-rw-r--r--modules/ogg/SCsub16
-rw-r--r--modules/ogg/register_types.cpp4
-rw-r--r--modules/ogg/register_types.h4
-rw-r--r--modules/opensimplex/SCsub17
-rw-r--r--modules/opensimplex/doc_classes/NoiseTexture.xml4
-rw-r--r--modules/opensimplex/doc_classes/OpenSimplexNoise.xml20
-rw-r--r--modules/opensimplex/icons/NoiseTexture.svg4
-rw-r--r--modules/opensimplex/noise_texture.cpp66
-rw-r--r--modules/opensimplex/noise_texture.h26
-rw-r--r--modules/opensimplex/open_simplex_noise.cpp70
-rw-r--r--modules/opensimplex/open_simplex_noise.h42
-rw-r--r--modules/opensimplex/register_types.cpp5
-rw-r--r--modules/opensimplex/register_types.h4
-rw-r--r--modules/opus/SCsub22
-rw-r--r--modules/opus/config.py2
-rw-r--r--modules/opus/register_types.cpp4
-rw-r--r--modules/opus/register_types.h4
-rw-r--r--modules/pvr/SCsub15
-rw-r--r--modules/pvr/image_compress_pvrtc.cpp84
-rw-r--r--modules/pvr/image_compress_pvrtc.h36
-rw-r--r--modules/pvr/register_types.cpp9
-rw-r--r--modules/pvr/register_types.h4
-rw-r--r--modules/pvr/texture_loader_pvr.cpp152
-rw-r--r--modules/pvr/texture_loader_pvr.h4
-rw-r--r--modules/regex/SCsub20
-rw-r--r--modules/regex/doc_classes/RegEx.xml16
-rw-r--r--modules/regex/doc_classes/RegExMatch.xml2
-rw-r--r--modules/regex/regex.cpp316
-rw-r--r--modules/regex/regex.h19
-rw-r--r--modules/regex/register_types.cpp7
-rw-r--r--modules/regex/register_types.h4
-rw-r--r--modules/regex/tests/test_regex.h164
-rw-r--r--modules/register_module_types.h4
-rw-r--r--modules/squish/SCsub16
-rw-r--r--modules/squish/image_compress_squish.cpp21
-rw-r--r--modules/squish/image_compress_squish.h6
-rw-r--r--modules/squish/register_types.cpp5
-rw-r--r--modules/squish/register_types.h4
-rw-r--r--modules/stb_vorbis/SCsub17
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.cpp42
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.h28
-rw-r--r--modules/stb_vorbis/register_types.cpp7
-rw-r--r--modules/stb_vorbis/register_types.h4
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.cpp14
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.h24
-rw-r--r--modules/svg/SCsub17
-rw-r--r--modules/svg/image_loader_svg.cpp12
-rw-r--r--modules/svg/image_loader_svg.h7
-rw-r--r--modules/svg/register_types.cpp6
-rw-r--r--modules/svg/register_types.h4
-rw-r--r--modules/text_server_adv/SCsub501
-rw-r--r--modules/text_server_adv/bitmap_font_adv.cpp580
-rw-r--r--modules/text_server_adv/bitmap_font_adv.h118
-rw-r--r--modules/text_server_adv/config.py6
-rw-r--r--modules/text_server_adv/dynamic_font_adv.cpp1003
-rw-r--r--modules/text_server_adv/dynamic_font_adv.h191
-rw-r--r--modules/text_server_adv/font_adv.h94
-rw-r--r--modules/text_server_adv/icu_data/icudata_stub.cpp63
-rw-r--r--modules/text_server_adv/register_types.cpp43
-rw-r--r--modules/text_server_adv/register_types.h40
-rw-r--r--modules/text_server_adv/script_iterator.cpp110
-rw-r--r--modules/text_server_adv/script_iterator.h61
-rw-r--r--modules/text_server_adv/text_server_adv.cpp2571
-rw-r--r--modules/text_server_adv/text_server_adv.h248
-rw-r--r--modules/text_server_fb/SCsub13
-rw-r--r--modules/text_server_fb/bitmap_font_fb.cpp356
-rw-r--r--modules/text_server_fb/bitmap_font_fb.h107
-rw-r--r--modules/text_server_fb/config.py11
-rw-r--r--modules/text_server_fb/dynamic_font_fb.cpp685
-rw-r--r--modules/text_server_fb/dynamic_font_fb.h169
-rw-r--r--modules/text_server_fb/font_fb.h80
-rw-r--r--modules/text_server_fb/register_types.cpp43
-rw-r--r--modules/text_server_fb/register_types.h (renamed from modules/mono/editor/csharp_project.h)22
-rw-r--r--modules/text_server_fb/text_server_fb.cpp1383
-rw-r--r--modules/text_server_fb/text_server_fb.h193
-rw-r--r--modules/tga/image_loader_tga.cpp35
-rw-r--r--modules/tga/image_loader_tga.h4
-rw-r--r--modules/tga/register_types.cpp6
-rw-r--r--modules/tga/register_types.h4
-rw-r--r--modules/theora/SCsub16
-rw-r--r--modules/theora/config.py2
-rw-r--r--modules/theora/doc_classes/VideoStreamTheora.xml5
-rw-r--r--modules/theora/register_types.cpp6
-rw-r--r--modules/theora/register_types.h4
-rw-r--r--modules/theora/video_stream_theora.cpp91
-rw-r--r--modules/theora/video_stream_theora.h46
-rw-r--r--modules/tinyexr/SCsub17
-rw-r--r--modules/tinyexr/image_loader_tinyexr.cpp172
-rw-r--r--modules/tinyexr/image_loader_tinyexr.h5
-rw-r--r--modules/tinyexr/image_saver_tinyexr.cpp25
-rw-r--r--modules/tinyexr/image_saver_tinyexr.h4
-rw-r--r--modules/tinyexr/register_types.cpp6
-rw-r--r--modules/tinyexr/register_types.h4
-rw-r--r--modules/upnp/SCsub15
-rw-r--r--modules/upnp/register_types.cpp7
-rw-r--r--modules/upnp/register_types.h4
-rw-r--r--modules/upnp/upnp.cpp8
-rw-r--r--modules/upnp/upnp.h8
-rw-r--r--modules/upnp/upnp_device.cpp6
-rw-r--r--modules/upnp/upnp_device.h8
-rw-r--r--modules/vhacd/SCsub17
-rw-r--r--modules/vhacd/register_types.cpp5
-rw-r--r--modules/vhacd/register_types.h4
-rw-r--r--modules/visual_script/config.py1
-rw-r--r--modules/visual_script/doc_classes/@VisualScript.xml15
-rw-r--r--modules/visual_script/doc_classes/VisualScript.xml136
-rw-r--r--modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml42
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLists.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPropertyGet.xml2
-rw-r--r--modules/visual_script/icons/VisualScript.svg7
-rw-r--r--modules/visual_script/register_types.cpp11
-rw-r--r--modules/visual_script/register_types.h4
-rw-r--r--modules/visual_script/visual_script.cpp1454
-rw-r--r--modules/visual_script/visual_script.h231
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.cpp366
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.h33
-rw-r--r--modules/visual_script/visual_script_editor.cpp2575
-rw-r--r--modules/visual_script/visual_script_editor.h90
-rw-r--r--modules/visual_script/visual_script_expression.cpp390
-rw-r--r--modules/visual_script/visual_script_expression.h38
-rw-r--r--modules/visual_script/visual_script_flow_control.cpp193
-rw-r--r--modules/visual_script/visual_script_flow_control.h169
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp521
-rw-r--r--modules/visual_script/visual_script_func_nodes.h106
-rw-r--r--modules/visual_script/visual_script_nodes.cpp776
-rw-r--r--modules/visual_script/visual_script_nodes.h634
-rw-r--r--modules/visual_script/visual_script_property_selector.cpp115
-rw-r--r--modules/visual_script/visual_script_property_selector.h4
-rw-r--r--modules/visual_script/visual_script_yield_nodes.cpp168
-rw-r--r--modules/visual_script/visual_script_yield_nodes.h54
-rw-r--r--modules/vorbis/SCsub20
-rw-r--r--modules/vorbis/config.py2
-rw-r--r--modules/vorbis/register_types.cpp4
-rw-r--r--modules/vorbis/register_types.h4
-rw-r--r--modules/webm/SCsub15
-rw-r--r--modules/webm/config.py5
-rw-r--r--modules/webm/doc_classes/VideoStreamWebm.xml4
-rw-r--r--modules/webm/libvpx/SCsub6
-rw-r--r--modules/webm/register_types.cpp6
-rw-r--r--modules/webm/register_types.h4
-rw-r--r--modules/webm/video_stream_webm.cpp154
-rw-r--r--modules/webm/video_stream_webm.h70
-rw-r--r--modules/webp/SCsub16
-rw-r--r--modules/webp/image_loader_webp.cpp22
-rw-r--r--modules/webp/image_loader_webp.h5
-rw-r--r--modules/webp/register_types.cpp6
-rw-r--r--modules/webp/register_types.h4
-rw-r--r--modules/webrtc/SCsub6
-rw-r--r--modules/webrtc/doc_classes/WebRTCPeerConnection.xml6
-rw-r--r--modules/webrtc/library_godot_webrtc.js433
-rw-r--r--modules/webrtc/register_types.cpp6
-rw-r--r--modules/webrtc/register_types.h4
-rw-r--r--modules/webrtc/webrtc_data_channel.cpp6
-rw-r--r--modules/webrtc/webrtc_data_channel.h11
-rw-r--r--modules/webrtc/webrtc_data_channel_gdnative.cpp4
-rw-r--r--modules/webrtc/webrtc_data_channel_gdnative.h46
-rw-r--r--modules/webrtc/webrtc_data_channel_js.cpp250
-rw-r--r--modules/webrtc/webrtc_data_channel_js.h60
-rw-r--r--modules/webrtc/webrtc_multiplayer.cpp39
-rw-r--r--modules/webrtc/webrtc_multiplayer.h39
-rw-r--r--modules/webrtc/webrtc_peer_connection.cpp9
-rw-r--r--modules/webrtc/webrtc_peer_connection.h4
-rw-r--r--modules/webrtc/webrtc_peer_connection_gdnative.cpp5
-rw-r--r--modules/webrtc/webrtc_peer_connection_gdnative.h30
-rw-r--r--modules/webrtc/webrtc_peer_connection_js.cpp248
-rw-r--r--modules/webrtc/webrtc_peer_connection_js.h28
-rw-r--r--modules/websocket/SCsub40
-rw-r--r--modules/websocket/editor_debugger_server_websocket.cpp93
-rw-r--r--modules/websocket/editor_debugger_server_websocket.h62
-rw-r--r--modules/websocket/emws_client.cpp156
-rw-r--r--modules/websocket/emws_client.h17
-rw-r--r--modules/websocket/emws_peer.cpp54
-rw-r--r--modules/websocket/emws_peer.h23
-rw-r--r--modules/websocket/emws_server.cpp7
-rw-r--r--modules/websocket/emws_server.h7
-rw-r--r--modules/websocket/library_godot_websocket.js188
-rw-r--r--modules/websocket/packet_buffer.h7
-rw-r--r--modules/websocket/register_types.cpp39
-rw-r--r--modules/websocket/register_types.h4
-rw-r--r--modules/websocket/remote_debugger_peer_websocket.cpp133
-rw-r--r--modules/websocket/remote_debugger_peer_websocket.h65
-rw-r--r--modules/websocket/websocket_client.cpp20
-rw-r--r--modules/websocket/websocket_client.h13
-rw-r--r--modules/websocket/websocket_macros.h16
-rw-r--r--modules/websocket/websocket_multiplayer_peer.cpp54
-rw-r--r--modules/websocket/websocket_multiplayer_peer.h32
-rw-r--r--modules/websocket/websocket_peer.cpp4
-rw-r--r--modules/websocket/websocket_peer.h12
-rw-r--r--modules/websocket/websocket_server.cpp13
-rw-r--r--modules/websocket/websocket_server.h15
-rw-r--r--modules/websocket/wsl_client.cpp48
-rw-r--r--modules/websocket/wsl_client.h7
-rw-r--r--modules/websocket/wsl_peer.cpp36
-rw-r--r--modules/websocket/wsl_peer.h9
-rw-r--r--modules/websocket/wsl_server.cpp60
-rw-r--r--modules/websocket/wsl_server.h6
-rw-r--r--modules/webxr/SCsub11
-rw-r--r--modules/webxr/config.py14
-rw-r--r--modules/webxr/doc_classes/WebXRInterface.xml253
-rw-r--r--modules/webxr/godot_webxr.h84
-rw-r--r--modules/webxr/native/library_godot_webxr.js651
-rw-r--r--modules/webxr/native/webxr.externs.js499
-rw-r--r--modules/webxr/register_types.cpp47
-rw-r--r--modules/webxr/register_types.h37
-rw-r--r--modules/webxr/webxr_interface.cpp71
-rw-r--r--modules/webxr/webxr_interface.h65
-rw-r--r--modules/webxr/webxr_interface_js.cpp451
-rw-r--r--modules/webxr/webxr_interface_js.h103
-rw-r--r--modules/xatlas_unwrap/SCsub16
-rw-r--r--modules/xatlas_unwrap/register_types.cpp15
-rw-r--r--modules/xatlas_unwrap/register_types.h4
908 files changed, 97553 insertions, 44890 deletions
diff --git a/modules/SCsub b/modules/SCsub
index fb46c5f877..24598f4b28 100644
--- a/modules/SCsub
+++ b/modules/SCsub
@@ -1,28 +1,63 @@
#!/usr/bin/env python
-Import("env")
-
import modules_builders
+import os
+
+Import("env")
env_modules = env.Clone()
Export("env_modules")
# Header with MODULE_*_ENABLED defines.
-env.CommandNoCache("modules_enabled.gen.h", Value(env.module_list), modules_builders.generate_modules_enabled)
+env.CommandNoCache(
+ "modules_enabled.gen.h",
+ Value(env.module_list),
+ env.Run(
+ modules_builders.generate_modules_enabled,
+ "Generating enabled modules header.",
+ # NOTE: No need to run in subprocess since this is still executed serially.
+ subprocess=False,
+ ),
+)
+
+# Header to be included in `tests/test_main.cpp` to run module-specific tests.
+if env["tests"]:
+ env.CommandNoCache(
+ "modules_tests.gen.h",
+ Value(env.module_list),
+ env.Run(
+ modules_builders.generate_modules_tests,
+ "Generating modules tests header.",
+ # NOTE: No need to run in subprocess since this is still executed serially.
+ subprocess=False,
+ ),
+ )
+ env.AlwaysBuild("modules_tests.gen.h")
vs_sources = []
# libmodule_<name>.a for each active module.
-for module in env.module_list:
+for name, path in env.module_list.items():
env.modules_sources = []
- SConscript(module + "/SCsub")
+
+ if not os.path.isabs(path):
+ SConscript(name + "/SCsub") # Built-in.
+ else:
+ SConscript(path + "/SCsub") # Custom.
# Some modules are not linked automatically but can be enabled optionally
# on iOS, so we handle those specially.
- if env["platform"] == "iphone" and module in ["arkit", "camera"]:
+ if env["platform"] == "iphone" and name in [
+ "arkit",
+ "camera",
+ "camera_iphone",
+ "gamecenter",
+ "inappstore",
+ "icloud",
+ ]:
continue
- lib = env_modules.add_library("module_%s" % module, env.modules_sources)
+ lib = env_modules.add_library("module_%s" % name, env.modules_sources)
env.Prepend(LIBS=[lib])
if env["vsproj"]:
vs_sources += env.modules_sources
diff --git a/modules/arkit/SCsub b/modules/arkit/SCsub
index 61c0a8248c..7e103d6565 100644
--- a/modules/arkit/SCsub
+++ b/modules/arkit/SCsub
@@ -5,6 +5,9 @@ Import("env_modules")
env_arkit = env_modules.Clone()
+# (iOS) Enable module support
+env_arkit.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])
+
# (iOS) Build as separate static library
modules_sources = []
env_arkit.add_source_files(modules_sources, "*.cpp")
diff --git a/modules/arkit/arkit.gdip b/modules/arkit/arkit.gdip
new file mode 100644
index 0000000000..22c0a07e26
--- /dev/null
+++ b/modules/arkit/arkit.gdip
@@ -0,0 +1,18 @@
+[config]
+name="ARKit"
+binary="arkit_lib.a"
+
+initialization="register_arkit_types"
+deinitialization="unregister_arkit_types"
+
+[dependencies]
+linked=[]
+embedded=[]
+system=["AVFoundation.framework", "ARKit.framework"]
+
+capabilities=["arkit"]
+
+files=[]
+
+[plist]
+NSCameraUsageDescription="Device camera is used for some functionality"
diff --git a/modules/arkit/arkit_interface.h b/modules/arkit/arkit_interface.h
index 1044f3cf6f..f9b7709aba 100644
--- a/modules/arkit/arkit_interface.h
+++ b/modules/arkit/arkit_interface.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -44,6 +44,15 @@
// forward declaration for some needed objects
class ARKitShader;
+#ifdef __OBJC__
+
+typedef ARAnchor GodotARAnchor;
+
+#else
+
+typedef void GodotARAnchor;
+#endif
+
class ARKitInterface : public XRInterface {
GDCLASS(ARKitInterface, XRInterface);
@@ -60,8 +69,8 @@ private:
float eye_height, z_near, z_far;
Ref<CameraFeed> feed;
- int image_width[2];
- int image_height[2];
+ size_t image_width[2];
+ size_t image_height[2];
Vector<uint8_t> img_data[2];
struct anchor_map {
@@ -84,9 +93,9 @@ 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_anchor_detection_is_enabled() const override;
+ void set_anchor_detection_is_enabled(bool p_enable) override;
+ virtual int get_camera_feed_id() override;
bool get_light_estimation_is_enabled() const;
void set_light_estimation_is_enabled(bool p_enable);
@@ -97,26 +106,26 @@ public:
/* 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 void notification(int p_what) override;
- virtual StringName get_name() const;
- virtual int get_capabilities() const;
+ virtual StringName get_name() const override;
+ virtual int get_capabilities() const override;
- virtual bool is_initialized() const;
- virtual bool initialize();
- virtual void uninitialize();
+ virtual bool is_initialized() const override;
+ virtual bool initialize() override;
+ virtual void uninitialize() override;
- virtual Size2 get_render_targetsize();
- virtual bool is_stereo();
- virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform);
- virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far);
- virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect);
+ virtual Size2 get_render_targetsize() override;
+ virtual bool is_stereo() override;
+ virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override;
+ virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override;
+ virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override;
- virtual void process();
+ virtual void process() override;
// 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);
+ void _add_or_update_anchor(GodotARAnchor *p_anchor);
+ void _remove_anchor(GodotARAnchor *p_anchor);
ARKitInterface();
~ARKitInterface();
diff --git a/modules/arkit/arkit_interface.mm b/modules/arkit/arkit_interface.mm
index 7de824815a..608afd4ff3 100644
--- a/modules/arkit/arkit_interface.mm
+++ b/modules/arkit/arkit_interface.mm
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,9 @@
#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.
+API_AVAILABLE(ios(11.0))
ARSession *ar_session;
+
ARKitSessionDelegate *ar_delegate;
NSTimeInterval last_timestamp;
@@ -55,22 +57,28 @@ void ARKitInterface::start_session() {
if (initialized) {
print_line("Starting ARKit session");
- Class ARWorldTrackingConfigurationClass = NSClassFromString(@"ARWorldTrackingConfiguration");
- ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfigurationClass new];
+ if (@available(iOS 11, *)) {
+ Class ARWorldTrackingConfigurationClass = NSClassFromString(@"ARWorldTrackingConfiguration");
+ ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfigurationClass new];
- configuration.lightEstimationEnabled = light_estimation_is_enabled;
- if (plane_detection_is_enabled) {
- configuration.planeDetection = ARPlaneDetectionVertical | ARPlaneDetectionHorizontal;
- } else {
- configuration.planeDetection = 0;
- }
+ configuration.lightEstimationEnabled = light_estimation_is_enabled;
+ if (plane_detection_is_enabled) {
+ if (@available(iOS 11.3, *)) {
+ configuration.planeDetection = ARPlaneDetectionVertical | ARPlaneDetectionHorizontal;
+ } else {
+ configuration.planeDetection = ARPlaneDetectionHorizontal;
+ }
+ } else {
+ configuration.planeDetection = 0;
+ }
- // make sure our camera is on
- if (feed.is_valid()) {
- feed->set_active(true);
- }
+ // make sure our camera is on
+ if (feed.is_valid()) {
+ feed->set_active(true);
+ }
- [ar_session runWithConfiguration:configuration];
+ [ar_session runWithConfiguration:configuration];
+ }
}
}
@@ -84,7 +92,9 @@ void ARKitInterface::stop_session() {
feed->set_active(false);
}
- [ar_session pause];
+ if (@available(iOS 11.0, *)) {
+ [ar_session pause];
+ }
}
}
@@ -92,12 +102,12 @@ 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: {
+ case DisplayServer::WINDOW_EVENT_FOCUS_IN: {
print_line("Focus in");
start_session();
}; break;
- case MainLoop::NOTIFICATION_WM_FOCUS_OUT: {
+ case DisplayServer::WINDOW_EVENT_FOCUS_OUT: {
print_line("Focus out");
stop_session();
@@ -162,37 +172,42 @@ int ARKitInterface::get_capabilities() const {
}
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);
- }
+ if (@available(iOS 11, *)) {
+ Array arr;
+ Size2 screen_size = DisplayServer::get_singleton()->screen_get_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;
+ return arr;
+ } else {
+ return Array();
+ }
}
void ARKitInterface::_bind_methods() {
@@ -221,51 +236,55 @@ bool ARKitInterface::initialize() {
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL_V(xr_server, false);
- if (!initialized) {
- print_line("initializing ARKit");
+ if (@available(iOS 11, *)) {
+ if (!initialized) {
+ print_line("initializing ARKit");
- // create our ar session and delegate
- Class ARSessionClass = NSClassFromString(@"ARSession");
- if (ARSessionClass == Nil) {
- void *arkit_handle = dlopen("/System/Library/Frameworks/ARKit.framework/ARKit", RTLD_NOW);
- if (arkit_handle) {
- ARSessionClass = NSClassFromString(@"ARSession");
- } else {
- print_line("ARKit init failed");
- return false;
+ // create our ar session and delegate
+ Class ARSessionClass = NSClassFromString(@"ARSession");
+ if (ARSessionClass == Nil) {
+ void *arkit_handle = dlopen("/System/Library/Frameworks/ARKit.framework/ARKit", RTLD_NOW);
+ if (arkit_handle) {
+ ARSessionClass = NSClassFromString(@"ARSession");
+ } else {
+ print_line("ARKit init failed");
+ return false;
+ }
}
- }
- ar_session = [ARSessionClass new];
- ar_delegate = [ARKitSessionDelegate new];
- ar_delegate.arkit_interface = this;
- ar_session.delegate = ar_delegate;
+ ar_session = [ARSessionClass new];
+ ar_delegate = [ARKitSessionDelegate new];
+ ar_delegate.arkit_interface = this;
+ ar_session.delegate = ar_delegate;
- // reset our transform
- transform = Transform();
+ // reset our transform
+ transform = Transform();
- // make this our primary interface
- xr_server->set_primary_interface(this);
+ // make this our primary interface
+ xr_server->set_primary_interface(this);
- // make sure we have our feed setup
- if (feed.is_null()) {
- feed.instance();
- feed->set_name("ARKit");
+ // 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);
+ CameraServer *cs = CameraServer::get_singleton();
+ if (cs != NULL) {
+ cs->add_feed(feed);
+ }
}
- }
- feed->set_active(true);
+ feed->set_active(true);
- // yeah!
- initialized = true;
+ // yeah!
+ initialized = true;
- // Start our session...
- start_session();
- }
+ // Start our session...
+ start_session();
+ }
- return true;
+ return true;
+ } else {
+ return false;
+ }
}
void ARKitInterface::uninitialize() {
@@ -286,25 +305,26 @@ void ARKitInterface::uninitialize() {
remove_all_anchors();
- [ar_session release];
- [ar_delegate release];
- ar_session = NULL;
- ar_delegate = NULL;
+ if (@available(iOS 11.0, *)) {
+ ar_session = nil;
+ }
+
+ ar_delegate = nil;
initialized = false;
session_was_started = false;
}
}
Size2 ARKitInterface::get_render_targetsize() {
- _THREAD_SAFE_METHOD_
+ // _THREAD_SAFE_METHOD_
- Size2 target_size = OS::get_singleton()->get_window_size();
+ Size2 target_size = DisplayServer::get_singleton()->screen_get_size();
return target_size;
}
Transform ARKitInterface::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) {
- _THREAD_SAFE_METHOD_
+ // _THREAD_SAFE_METHOD_
Transform transform_for_eye;
@@ -336,7 +356,7 @@ CameraMatrix ARKitInterface::get_projection_for_eye(XRInterface::Eyes p_eye, rea
}
void ARKitInterface::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) {
- _THREAD_SAFE_METHOD_
+ // _THREAD_SAFE_METHOD_
// We must have a valid render target
ERR_FAIL_COND(!p_render_target.is_valid());
@@ -345,15 +365,15 @@ void ARKitInterface::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target
ERR_FAIL_COND(p_screen_rect == Rect2());
// get the size of our screen
- Rect2 screen_rect = p_screen_rect;
+ // 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);
+ // VSG::rasterizer->set_current_render_target(RID());
+ // VSG::rasterizer->blit_render_target_to_screen(p_render_target, screen_rect, 0);
}
XRPositionalTracker *ARKitInterface::get_anchor_for_uuid(const unsigned char *p_uuid) {
@@ -378,14 +398,14 @@ XRPositionalTracker *ARKitInterface::get_anchor_for_uuid(const unsigned char *p_
}
XRPositionalTracker *new_tracker = memnew(XRPositionalTracker);
- new_tracker->set_type(XRServer::TRACKER_ANCHOR);
+ new_tracker->set_tracker_type(XRServer::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);
+ new_tracker->set_tracker_name(name);
// add our tracker
XRServer::get_singleton()->add_tracker(new_tracker);
@@ -432,7 +452,7 @@ void ARKitInterface::remove_all_anchors() {
}
void ARKitInterface::process() {
- _THREAD_SAFE_METHOD_
+ // _THREAD_SAFE_METHOD_
if (@available(iOS 11.0, *)) {
if (initialized) {
@@ -443,8 +463,16 @@ void ARKitInterface::process() {
last_timestamp = current_frame.timestamp;
// get some info about our screen and orientation
- Size2 screen_size = OS::get_singleton()->get_window_size();
- UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
+ Size2 screen_size = DisplayServer::get_singleton()->screen_get_size();
+ UIInterfaceOrientation orientation = UIInterfaceOrientationUnknown;
+
+ if (@available(iOS 13, *)) {
+ orientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
+#if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
+ } else {
+ orientation = [[UIApplication sharedApplication] statusBarOrientation];
+#endif
+ }
// Grab our camera image for our backbuffer
CVPixelBufferRef pixelBuffer = current_frame.capturedImage;
@@ -475,27 +503,27 @@ void ARKitInterface::process() {
{
// do Y
- int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
- int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
- int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
+ size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
+ size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
+ size_t 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);
+ printf("- Camera Y plane size: %lu, %lu - %lu\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);
}
- uint8_t *w = img_data[0].write();
+ uint8_t *w = img_data[0].ptrw();
if (new_width == bytes_per_row) {
- memcpy(w.ptr(), dataY, new_width * new_height);
+ memcpy(w, 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);
+ size_t offset_a = 0;
+ size_t offset_b = extraLeft + (extraTop * bytes_per_row);
+ for (size_t r = 0; r < new_height; r++) {
+ memcpy(w + offset_a, dataY + offset_b, new_width);
offset_a += new_width;
offset_b += bytes_per_row;
}
@@ -507,26 +535,26 @@ void ARKitInterface::process() {
{
// do CbCr
- int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
- int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
- int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
+ size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
+ size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
+ size_t 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);
+ printf("- Camera CbCr plane size: %lu, %lu - %lu\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);
}
- uint8_t *w = img_data[1].write();
+ uint8_t *w = img_data[1].ptrw();
if ((2 * new_width) == bytes_per_row) {
- memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height);
+ memcpy(w, 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);
+ size_t offset_a = 0;
+ size_t offset_b = extraLeft + (extraTop * bytes_per_row);
+ for (size_t r = 0; r < new_height; r++) {
+ memcpy(w + offset_a, dataCbCr + offset_b, 2 * new_width);
offset_a += 2 * new_width;
offset_b += bytes_per_row;
}
@@ -657,70 +685,79 @@ void ARKitInterface::process() {
}
}
-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];
+void ARKitInterface::_add_or_update_anchor(GodotARAnchor *p_anchor) {
+ // _THREAD_SAFE_METHOD_
- XRPositionalTracker *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);
+ if (@available(iOS 11.0, *)) {
+ ARAnchor *anchor = (ARAnchor *)p_anchor;
+
+ unsigned char uuid[16];
+ [anchor.identifier getUUIDBytes:uuid];
+
+ XRPositionalTracker *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 (@available(iOS 11.3, *)) {
+ 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->set_uv(Vector2(textcoord[0], textcoord[1]));
+ surftool->set_color(Color(0.8, 0.8, 0.8));
+ surftool->add_vertex(Vector3(vrtx[0], vrtx[1], vrtx[2]));
+ }
- 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);
+ }
+ } else {
+ Ref<Mesh> nomesh;
+ tracker->set_mesh(nomesh);
}
- 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 XRAnchor 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]));
}
-
- // Note, this also contains a scale factor which gives us an idea of the size of the anchor
- // We may extract that in our XRAnchor 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_
+void ARKitInterface::_remove_anchor(GodotARAnchor *p_anchor) {
+ // _THREAD_SAFE_METHOD_
- ARAnchor *anchor = (ARAnchor *)p_anchor;
+ if (@available(iOS 11.0, *)) {
+ ARAnchor *anchor = (ARAnchor *)p_anchor;
- unsigned char uuid[16];
- [anchor.identifier getUUIDBytes:uuid];
+ unsigned char uuid[16];
+ [anchor.identifier getUUIDBytes:uuid];
- remove_anchor_for_uuid(uuid);
+ remove_anchor_for_uuid(uuid);
+ }
}
ARKitInterface::ARKitInterface() {
@@ -728,7 +765,9 @@ ARKitInterface::ARKitInterface() {
session_was_started = false;
plane_detection_is_enabled = false;
light_estimation_is_enabled = false;
- ar_session = NULL;
+ if (@available(iOS 11.0, *)) {
+ ar_session = nil;
+ }
z_near = 0.01;
z_far = 1000.0;
projection.set_perspective(60.0, 1.0, z_near, z_far, false);
diff --git a/modules/arkit/register_types.cpp b/modules/arkit/arkit_module.cpp
index 91069ab364..be3c5e29ca 100644
--- a/modules/arkit/register_types.cpp
+++ b/modules/arkit/arkit_module.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* register_types.cpp */
+/* arkit_module.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "register_types.h"
+#include "arkit_module.h"
#include "arkit_interface.h"
diff --git a/modules/arkit/arkit_module.h b/modules/arkit/arkit_module.h
new file mode 100644
index 0000000000..ca48371152
--- /dev/null
+++ b/modules/arkit/arkit_module.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* arkit_module.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_REGISTER_TYPES_H
+#define ARKIT_REGISTER_TYPES_H
+
+void register_arkit_types();
+void unregister_arkit_types();
+
+#endif // ARKIT_REGISTER_TYPES_H
diff --git a/modules/arkit/arkit_session_delegate.h b/modules/arkit/arkit_session_delegate.h
index 158b80a60a..f227d50b35 100644
--- a/modules/arkit/arkit_session_delegate.h
+++ b/modules/arkit/arkit_session_delegate.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,9 +42,9 @@ class ARKitInterface;
@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;
+- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor *> *)anchors API_AVAILABLE(ios(11.0));
+- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor *> *)anchors API_AVAILABLE(ios(11.0));
+- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor *> *)anchors API_AVAILABLE(ios(11.0));
@end
#endif /* !ARKIT_SESSION_DELEGATE_H */
diff --git a/modules/arkit/arkit_session_delegate.mm b/modules/arkit/arkit_session_delegate.mm
index f44f46b7b7..97af5bf42c 100644
--- a/modules/arkit/arkit_session_delegate.mm
+++ b/modules/arkit/arkit_session_delegate.mm
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/assimp/SCsub b/modules/assimp/SCsub
deleted file mode 100644
index f1d0c742b4..0000000000
--- a/modules/assimp/SCsub
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/env python
-
-Import("env")
-Import("env_modules")
-
-env_assimp = env_modules.Clone()
-
-# Force bundled version for now, there's no released version of Assimp with
-# support for ArmaturePopulate which we use from their master branch.
-if True: # env['builtin_assimp']:
- thirdparty_dir = "#thirdparty/assimp"
-
- env_assimp.Prepend(CPPPATH=["#thirdparty/assimp"])
- env_assimp.Prepend(CPPPATH=["#thirdparty/assimp/code"])
- env_assimp.Prepend(CPPPATH=["#thirdparty/assimp/include"])
-
- # 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_SINGLETHREADED"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_BOOST_WORKAROUND"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_OWN_ZLIB"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_EXPORT"])
-
- # Importers we don't need
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_3D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_3DS_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_3MF_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_AC_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_AMF_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_ASE_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_ASSBIN_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_B3D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_BLEND_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_BVH_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_C4D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_COB_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_COLLADA_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_CSM_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_DXF_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_GLTF2_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_GLTF_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_HMP_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_IFC_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_IRR_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_IRRMESH_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_LWO_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_LWS_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_M3D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_MD2_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_MD5_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_MDC_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_MDL_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_MMD_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_MS3D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_NDO_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_NFF_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_OBJ_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_OFF_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_PLY_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_Q3BSP_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_Q3D_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_SMD_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_STEP_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_STL_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_TERRAGEN_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_X3D_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_XGL_IMPORTER"])
- env_assimp.Append(CPPDEFINES=["ASSIMP_BUILD_NO_X_IMPORTER"])
-
- if env["platform"] == "windows":
- env_assimp.Append(CPPDEFINES=["PLATFORM_WINDOWS"])
- env_assimp.Append(CPPDEFINES=[("PLATFORM", "WINDOWS")])
- elif env["platform"] == "linuxbsd":
- env_assimp.Append(CPPDEFINES=["PLATFORM_LINUX"])
- env_assimp.Append(CPPDEFINES=[("PLATFORM", "LINUX")])
- elif env["platform"] == "osx":
- env_assimp.Append(CPPDEFINES=["PLATFORM_DARWIN"])
- env_assimp.Append(CPPDEFINES=[("PLATFORM", "DARWIN")])
-
- env_thirdparty = env_assimp.Clone()
- env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, Glob("#thirdparty/assimp/code/CApi/*.cpp"))
- env_thirdparty.add_source_files(env.modules_sources, Glob("#thirdparty/assimp/code/Common/*.cpp"))
- env_thirdparty.add_source_files(env.modules_sources, Glob("#thirdparty/assimp/code/PostProcessing/*.cpp"))
- env_thirdparty.add_source_files(env.modules_sources, Glob("#thirdparty/assimp/code/Material/*.cpp"))
- env_thirdparty.add_source_files(env.modules_sources, Glob("#thirdparty/assimp/code/FBX/*.cpp"))
-
-# Godot's own source files
-env_assimp.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/assimp/editor_scene_importer_assimp.cpp b/modules/assimp/editor_scene_importer_assimp.cpp
deleted file mode 100644
index cc74674eff..0000000000
--- a/modules/assimp/editor_scene_importer_assimp.cpp
+++ /dev/null
@@ -1,1509 +0,0 @@
-/*************************************************************************/
-/* editor_scene_importer_assimp.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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_scene_importer_assimp.h"
-#include "core/io/image_loader.h"
-#include "editor/import/resource_importer_scene.h"
-#include "import_utils.h"
-#include "scene/3d/camera_3d.h"
-#include "scene/3d/light_3d.h"
-#include "scene/3d/mesh_instance_3d.h"
-#include "scene/main/node.h"
-#include "scene/resources/material.h"
-#include "scene/resources/surface_tool.h"
-
-#include <assimp/matrix4x4.h>
-#include <assimp/postprocess.h>
-#include <assimp/scene.h>
-#include <assimp/Importer.hpp>
-#include <assimp/LogStream.hpp>
-#include <string>
-
-// move into assimp
-aiBone *get_bone_by_name(const aiScene *scene, aiString bone_name) {
- for (unsigned int mesh_id = 0; mesh_id < scene->mNumMeshes; ++mesh_id) {
- aiMesh *mesh = scene->mMeshes[mesh_id];
-
- // iterate over all the bones on the mesh for this node only!
- for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
-
- aiBone *bone = mesh->mBones[boneIndex];
- if (bone->mName == bone_name) {
- printf("matched bone by name: %s\n", bone->mName.C_Str());
- return bone;
- }
- }
- }
-
- return nullptr;
-}
-
-void EditorSceneImporterAssimp::get_extensions(List<String> *r_extensions) const {
-
- const String import_setting_string = "filesystem/import/open_asset_import/";
-
- Map<String, ImportFormat> import_format;
- {
- Vector<String> exts;
- exts.push_back("fbx");
- ImportFormat import = { exts, true };
- import_format.insert("fbx", import);
- }
- for (Map<String, ImportFormat>::Element *E = import_format.front(); E; E = E->next()) {
- _register_project_setting_import(E->key(), import_setting_string, E->get().extensions, r_extensions,
- E->get().is_default);
- }
-}
-
-void EditorSceneImporterAssimp::_register_project_setting_import(const String generic, const String import_setting_string,
- const Vector<String> &exts, List<String> *r_extensions,
- const bool p_enabled) const {
- const String use_generic = "use_" + generic;
- _GLOBAL_DEF(import_setting_string + use_generic, p_enabled, true);
- if (ProjectSettings::get_singleton()->get(import_setting_string + use_generic)) {
- for (int32_t i = 0; i < exts.size(); i++) {
- r_extensions->push_back(exts[i]);
- }
- }
-}
-
-uint32_t EditorSceneImporterAssimp::get_import_flags() const {
- return IMPORT_SCENE;
-}
-
-void EditorSceneImporterAssimp::_bind_methods() {
-}
-
-Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps,
- List<String> *r_missing_deps, Error *r_err) {
- Assimp::Importer importer;
- std::wstring w_path = ProjectSettings::get_singleton()->globalize_path(p_path).c_str();
- std::string s_path(w_path.begin(), w_path.end());
- importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
- // Cannot remove pivot points because the static mesh will be in the wrong place
- importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
- int32_t max_bone_weights = 4;
- //if (p_flags & IMPORT_ANIMATION_EIGHT_WEIGHTS) {
- // const int eight_bones = 8;
- // importer.SetPropertyBool(AI_CONFIG_PP_LBW_MAX_WEIGHTS, eight_bones);
- // max_bone_weights = eight_bones;
- //}
-
- importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
-
- //importer.SetPropertyFloat(AI_CONFIG_PP_DB_THRESHOLD, 1.0f);
- int32_t post_process_Steps = aiProcess_CalcTangentSpace |
- aiProcess_GlobalScale |
- // imports models and listens to their file scale for CM to M conversions
- //aiProcess_FlipUVs |
- aiProcess_FlipWindingOrder |
- // very important for culling so that it is done in the correct order.
- //aiProcess_DropNormals |
- //aiProcess_GenSmoothNormals |
- //aiProcess_JoinIdenticalVertices |
- aiProcess_ImproveCacheLocality |
- //aiProcess_RemoveRedundantMaterials | // Causes a crash
- //aiProcess_SplitLargeMeshes |
- aiProcess_Triangulate |
- aiProcess_GenUVCoords |
- //aiProcess_FindDegenerates |
- //aiProcess_SortByPType |
- // aiProcess_FindInvalidData |
- aiProcess_TransformUVCoords |
- aiProcess_FindInstances |
- //aiProcess_FixInfacingNormals |
- //aiProcess_ValidateDataStructure |
- aiProcess_OptimizeMeshes |
- aiProcess_PopulateArmatureData |
- //aiProcess_OptimizeGraph |
- //aiProcess_Debone |
- // aiProcess_EmbedTextures |
- //aiProcess_SplitByBoneCount |
- 0;
- aiScene *scene = (aiScene *)importer.ReadFile(s_path.c_str(), post_process_Steps);
-
- ERR_FAIL_COND_V_MSG(scene == nullptr, nullptr, String("Open Asset Import failed to open: ") + String(importer.GetErrorString()));
-
- return _generate_scene(p_path, scene, p_flags, p_bake_fps, max_bone_weights);
-}
-
-template <class T>
-struct EditorSceneImporterAssetImportInterpolate {
-
- T lerp(const T &a, const T &b, float c) const {
-
- return a + (b - a) * c;
- }
-
- T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
-
- float t2 = t * t;
- float t3 = t2 * t;
-
- return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
- }
-
- T bezier(T start, T control_1, T control_2, T end, float t) {
- /* Formula from Wikipedia article on Bezier curves. */
- real_t omt = (1.0 - t);
- real_t omt2 = omt * omt;
- real_t omt3 = omt2 * omt;
- real_t t2 = t * t;
- real_t t3 = t2 * t;
-
- return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
- }
-};
-
-//thank you for existing, partial specialization
-template <>
-struct EditorSceneImporterAssetImportInterpolate<Quat> {
-
- Quat lerp(const Quat &a, const Quat &b, float c) const {
- ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized.");
- ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized.");
-
- return a.slerp(b, c).normalized();
- }
-
- Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
- ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized.");
- ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized.");
-
- return p1.slerp(p2, c).normalized();
- }
-
- Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
- ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized.");
- ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized.");
-
- return start.slerp(end, t).normalized();
- }
-};
-
-template <class T>
-T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time,
- AssetImportAnimation::Interpolation p_interp) {
- //could use binary search, worth it?
- int idx = -1;
- for (int i = 0; i < p_times.size(); i++) {
- if (p_times[i] > p_time)
- break;
- idx++;
- }
-
- EditorSceneImporterAssetImportInterpolate<T> interp;
-
- switch (p_interp) {
- case AssetImportAnimation::INTERP_LINEAR: {
-
- if (idx == -1) {
- return p_values[0];
- } else if (idx >= p_times.size() - 1) {
- return p_values[p_times.size() - 1];
- }
-
- float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
-
- return interp.lerp(p_values[idx], p_values[idx + 1], c);
-
- } break;
- case AssetImportAnimation::INTERP_STEP: {
-
- if (idx == -1) {
- return p_values[0];
- } else if (idx >= p_times.size() - 1) {
- return p_values[p_times.size() - 1];
- }
-
- return p_values[idx];
-
- } break;
- case AssetImportAnimation::INTERP_CATMULLROMSPLINE: {
-
- if (idx == -1) {
- return p_values[1];
- } else if (idx >= p_times.size() - 1) {
- return p_values[1 + p_times.size() - 1];
- }
-
- float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
-
- return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
-
- } break;
- case AssetImportAnimation::INTERP_CUBIC_SPLINE: {
-
- if (idx == -1) {
- return p_values[1];
- } else if (idx >= p_times.size() - 1) {
- return p_values[(p_times.size() - 1) * 3 + 1];
- }
-
- float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
-
- T from = p_values[idx * 3 + 1];
- T c1 = from + p_values[idx * 3 + 2];
- T to = p_values[idx * 3 + 4];
- T c2 = to + p_values[idx * 3 + 3];
-
- return interp.bezier(from, c1, c2, to, c);
-
- } break;
- }
-
- ERR_FAIL_V(p_values[0]);
-}
-
-aiBone *EditorSceneImporterAssimp::get_bone_from_stack(ImportState &state, aiString name) {
- List<aiBone *>::Element *iter;
- aiBone *bone = nullptr;
- for (iter = state.bone_stack.front(); iter; iter = iter->next()) {
- bone = (aiBone *)iter->get();
-
- if (bone && bone->mName == name) {
- state.bone_stack.erase(bone);
- return bone;
- }
- }
-
- return nullptr;
-}
-
-Node3D *
-EditorSceneImporterAssimp::_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps,
- const int32_t p_max_bone_weights) {
- ERR_FAIL_COND_V(scene == nullptr, nullptr);
-
- ImportState state;
- state.path = p_path;
- state.assimp_scene = scene;
- state.max_bone_weights = p_max_bone_weights;
- state.animation_player = nullptr;
-
- // populate light map
- for (unsigned int l = 0; l < scene->mNumLights; l++) {
-
- aiLight *ai_light = scene->mLights[l];
- ERR_CONTINUE(ai_light == nullptr);
- state.light_cache[AssimpUtils::get_assimp_string(ai_light->mName)] = l;
- }
-
- // fill camera cache
- for (unsigned int c = 0; c < scene->mNumCameras; c++) {
- aiCamera *ai_camera = scene->mCameras[c];
- ERR_CONTINUE(ai_camera == nullptr);
- state.camera_cache[AssimpUtils::get_assimp_string(ai_camera->mName)] = c;
- }
-
- if (scene->mRootNode) {
- state.nodes.push_back(scene->mRootNode);
-
- // make flat node tree - in order to make processing deterministic
- for (unsigned int i = 0; i < scene->mRootNode->mNumChildren; i++) {
- _generate_node(state, scene->mRootNode->mChildren[i]);
- }
-
- RegenerateBoneStack(state);
-
- Node *last_valid_parent = nullptr;
-
- List<const aiNode *>::Element *iter;
- for (iter = state.nodes.front(); iter; iter = iter->next()) {
- const aiNode *element_assimp_node = iter->get();
- const aiNode *parent_assimp_node = element_assimp_node->mParent;
-
- String node_name = AssimpUtils::get_assimp_string(element_assimp_node->mName);
- //print_verbose("node: " + node_name);
-
- Node3D *spatial = nullptr;
- Transform transform = AssimpUtils::assimp_matrix_transform(element_assimp_node->mTransformation);
-
- // retrieve this node bone
- aiBone *bone = get_bone_from_stack(state, element_assimp_node->mName);
-
- if (state.light_cache.has(node_name)) {
- spatial = create_light(state, node_name, transform);
- } else if (state.camera_cache.has(node_name)) {
- spatial = create_camera(state, node_name, transform);
- } else if (state.armature_nodes.find(element_assimp_node)) {
- // create skeleton
- print_verbose("Making skeleton: " + node_name);
- Skeleton3D *skeleton = memnew(Skeleton3D);
- spatial = skeleton;
- if (!state.armature_skeletons.has(element_assimp_node)) {
- state.armature_skeletons.insert(element_assimp_node, skeleton);
- }
- } else if (bone != nullptr) {
- continue;
- } else {
- spatial = memnew(Node3D);
- }
-
- ERR_CONTINUE_MSG(spatial == nullptr, "FBX Import - are we out of ram?");
- // we on purpose set the transform and name after creating the node.
-
- spatial->set_name(node_name);
- spatial->set_global_transform(transform);
-
- // first element is root
- if (iter == state.nodes.front()) {
- state.root = spatial;
- }
-
- // flat node map parent lookup tool
- state.flat_node_map.insert(element_assimp_node, spatial);
-
- Map<const aiNode *, Node3D *>::Element *parent_lookup = state.flat_node_map.find(parent_assimp_node);
-
- // note: this always fails on the root node :) keep that in mind this is by design
- if (parent_lookup) {
- Node3D *parent_node = parent_lookup->value();
-
- ERR_FAIL_COND_V_MSG(parent_node == nullptr, state.root,
- "Parent node invalid even though lookup successful, out of ram?");
-
- if (spatial != state.root) {
- parent_node->add_child(spatial);
- spatial->set_owner(state.root);
- } else {
- // required - think about it root never has a parent yet is valid, anything else without a parent is not valid.
- }
- } else if (spatial != state.root) {
- // if the ainode is not in the tree
- // parent it to the last good parent found
- if (last_valid_parent) {
- last_valid_parent->add_child(spatial);
- spatial->set_owner(state.root);
- } else {
- // this is a serious error?
- memdelete(spatial);
- }
- }
-
- // update last valid parent
- last_valid_parent = spatial;
- }
- print_verbose("node counts: " + itos(state.nodes.size()));
-
- // make clean bone stack
- RegenerateBoneStack(state);
-
- print_verbose("generating godot bone data");
-
- print_verbose("Godot bone stack count: " + itos(state.bone_stack.size()));
-
- // This is a list of bones, duplicates are from other meshes and must be dealt with properly
- for (List<aiBone *>::Element *element = state.bone_stack.front(); element; element = element->next()) {
- aiBone *bone = element->get();
-
- ERR_CONTINUE_MSG(!bone, "invalid bone read from assimp?");
-
- // Utilities for armature lookup - for now only FBX makes these
- aiNode *armature_for_bone = bone->mArmature;
-
- // Utilities for bone node lookup - for now only FBX makes these
- aiNode *bone_node = bone->mNode;
- aiNode *parent_node = bone_node->mParent;
-
- String bone_name = AssimpUtils::get_anim_string_from_assimp(bone->mName);
- ERR_CONTINUE_MSG(armature_for_bone == nullptr, "Armature for bone invalid: " + bone_name);
- Skeleton3D *skeleton = state.armature_skeletons[armature_for_bone];
-
- state.skeleton_bone_map[bone] = skeleton;
-
- if (bone_name.empty()) {
- bone_name = "untitled_bone_name";
- WARN_PRINT("Untitled bone name detected... report with file please");
- }
-
- // todo: this is where skin support goes
- if (skeleton && skeleton->find_bone(bone_name) == -1) {
- print_verbose("[Godot Glue] Imported bone" + bone_name);
- int boneIdx = skeleton->get_bone_count();
-
- Transform pform = AssimpUtils::assimp_matrix_transform(bone->mNode->mTransformation);
- skeleton->add_bone(bone_name);
- skeleton->set_bone_rest(boneIdx, pform);
- skeleton->set_bone_pose(boneIdx, pform);
-
- if (parent_node != nullptr) {
- int parent_bone_id = skeleton->find_bone(AssimpUtils::get_anim_string_from_assimp(parent_node->mName));
- int current_bone_id = boneIdx;
- skeleton->set_bone_parent(current_bone_id, parent_bone_id);
- }
- }
- }
-
- print_verbose("generating mesh phase from skeletal mesh");
-
- List<Node3D *> cleanup_template_nodes;
-
- for (Map<const aiNode *, Node3D *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
- const aiNode *assimp_node = key_value_pair->key();
- Node3D *mesh_template = key_value_pair->value();
-
- ERR_CONTINUE(assimp_node == nullptr);
- ERR_CONTINUE(mesh_template == nullptr);
-
- Node *parent_node = mesh_template->get_parent();
-
- if (mesh_template == state.root) {
- continue;
- }
-
- if (parent_node == nullptr) {
- print_error("Found invalid parent node!");
- continue; // root node
- }
-
- String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
- Transform node_transform = AssimpUtils::assimp_matrix_transform(assimp_node->mTransformation);
-
- if (assimp_node->mNumMeshes > 0) {
- MeshInstance3D *mesh = create_mesh(state, assimp_node, node_name, parent_node, node_transform);
- if (mesh) {
-
- parent_node->remove_child(mesh_template);
-
- // re-parent children
- List<Node *> children;
- // re-parent all children to new node
- // note: since get_child_count will change during execution we must build a list first to be safe.
- for (int childId = 0; childId < mesh_template->get_child_count(); childId++) {
- // get child
- Node *child = mesh_template->get_child(childId);
- children.push_back(child);
- }
-
- for (List<Node *>::Element *element = children.front(); element; element = element->next()) {
- // reparent the children to the real mesh node.
- mesh_template->remove_child(element->get());
- mesh->add_child(element->get());
- element->get()->set_owner(state.root);
- }
-
- // update mesh in list so that each mesh node is available
- // this makes the template unavailable which is the desired behaviour
- state.flat_node_map[assimp_node] = mesh;
-
- cleanup_template_nodes.push_back(mesh_template);
-
- // clean up this list we don't need it
- children.clear();
- }
- }
- }
-
- for (List<Node3D *>::Element *element = cleanup_template_nodes.front(); element; element = element->next()) {
- if (element->get()) {
- memdelete(element->get());
- }
- }
- }
-
- if (p_flags & IMPORT_ANIMATION && scene->mNumAnimations) {
-
- state.animation_player = memnew(AnimationPlayer);
- state.root->add_child(state.animation_player);
- state.animation_player->set_owner(state.root);
-
- for (uint32_t i = 0; i < scene->mNumAnimations; i++) {
- _import_animation(state, i, p_bake_fps);
- }
- }
-
- //
- // Cleanup operations
- //
-
- state.mesh_cache.clear();
- state.material_cache.clear();
- state.light_cache.clear();
- state.camera_cache.clear();
- state.assimp_node_map.clear();
- state.path_to_image_cache.clear();
- state.nodes.clear();
- state.flat_node_map.clear();
- state.armature_skeletons.clear();
- state.bone_stack.clear();
- return state.root;
-}
-
-void EditorSceneImporterAssimp::_insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id,
- int anim_fps, Ref<Animation> animation, float ticks_per_second,
- Skeleton3D *skeleton, const NodePath &node_path,
- const String &node_name, aiBone *track_bone) {
- const aiNodeAnim *assimp_track = assimp_anim->mChannels[track_id];
- //make transform track
- int track_idx = animation->get_track_count();
- animation->add_track(Animation::TYPE_TRANSFORM);
- animation->track_set_path(track_idx, node_path);
- //first determine animation length
-
- float increment = 1.0 / float(anim_fps);
- float time = 0.0;
-
- bool last = false;
-
- Vector<Vector3> pos_values;
- Vector<float> pos_times;
- Vector<Vector3> scale_values;
- Vector<float> scale_times;
- Vector<Quat> rot_values;
- Vector<float> rot_times;
-
- for (size_t p = 0; p < assimp_track->mNumPositionKeys; p++) {
- aiVector3D pos = assimp_track->mPositionKeys[p].mValue;
- pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
- pos_times.push_back(assimp_track->mPositionKeys[p].mTime / ticks_per_second);
- }
-
- for (size_t r = 0; r < assimp_track->mNumRotationKeys; r++) {
- aiQuaternion quat = assimp_track->mRotationKeys[r].mValue;
- rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
- rot_times.push_back(assimp_track->mRotationKeys[r].mTime / ticks_per_second);
- }
-
- for (size_t sc = 0; sc < assimp_track->mNumScalingKeys; sc++) {
- aiVector3D scale = assimp_track->mScalingKeys[sc].mValue;
- scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
- scale_times.push_back(assimp_track->mScalingKeys[sc].mTime / ticks_per_second);
- }
-
- while (true) {
- Vector3 pos;
- Quat rot;
- Vector3 scale(1, 1, 1);
-
- if (pos_values.size()) {
- pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
- }
-
- if (rot_values.size()) {
- rot = _interpolate_track<Quat>(rot_times, rot_values, time,
- AssetImportAnimation::INTERP_LINEAR)
- .normalized();
- }
-
- if (scale_values.size()) {
- scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
- }
-
- if (skeleton) {
- int skeleton_bone = skeleton->find_bone(node_name);
-
- if (skeleton_bone >= 0 && track_bone) {
-
- Transform xform;
- xform.basis.set_quat_scale(rot, scale);
- xform.origin = pos;
-
- xform = skeleton->get_bone_pose(skeleton_bone).inverse() * xform;
-
- rot = xform.basis.get_rotation_quat();
- rot.normalize();
- scale = xform.basis.get_scale();
- pos = xform.origin;
- } else {
- ERR_FAIL_MSG("Skeleton bone lookup failed for skeleton: " + skeleton->get_name());
- }
- }
-
- animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
- animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
-
- if (last) { //done this way so a key is always inserted past the end (for proper interpolation)
- break;
- }
- time += increment;
- if (time >= animation->get_length()) {
- last = true;
- }
- }
-}
-
-// I really do not like this but need to figure out a better way of removing it later.
-Node *EditorSceneImporterAssimp::get_node_by_name(ImportState &state, String name) {
- for (Map<const aiNode *, Node3D *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
- const aiNode *assimp_node = key_value_pair->key();
- Node3D *node = key_value_pair->value();
-
- String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
- if (name == node_name && node) {
- return node;
- }
- }
- return nullptr;
-}
-
-/* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
-void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state) {
-
- state.bone_stack.clear();
- // build bone stack list
- for (unsigned int mesh_id = 0; mesh_id < state.assimp_scene->mNumMeshes; ++mesh_id) {
- aiMesh *mesh = state.assimp_scene->mMeshes[mesh_id];
-
- // iterate over all the bones on the mesh for this node only!
- for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
- aiBone *bone = mesh->mBones[boneIndex];
-
- // doubtful this is required right now but best to check
- if (!state.bone_stack.find(bone)) {
- //print_verbose("[assimp] bone stack added: " + String(bone->mName.C_Str()) );
- state.bone_stack.push_back(bone);
- }
- }
- }
-}
-
-/* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
-void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state, aiMesh *mesh) {
- state.bone_stack.clear();
- // iterate over all the bones on the mesh for this node only!
- for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
- aiBone *bone = mesh->mBones[boneIndex];
- if (state.bone_stack.find(bone) == nullptr) {
- state.bone_stack.push_back(bone);
- }
- }
-}
-
-// animation tracks are per bone
-
-void EditorSceneImporterAssimp::_import_animation(ImportState &state, int p_animation_index, int p_bake_fps) {
-
- ERR_FAIL_INDEX(p_animation_index, (int)state.assimp_scene->mNumAnimations);
-
- const aiAnimation *anim = state.assimp_scene->mAnimations[p_animation_index];
- String name = AssimpUtils::get_anim_string_from_assimp(anim->mName);
- if (name == String()) {
- name = "Animation " + itos(p_animation_index + 1);
- }
- print_verbose("import animation: " + name);
- float ticks_per_second = anim->mTicksPerSecond;
-
- if (state.assimp_scene->mMetaData != nullptr && Math::is_equal_approx(ticks_per_second, 0.0f)) {
- int32_t time_mode = 0;
- state.assimp_scene->mMetaData->Get("TimeMode", time_mode);
- ticks_per_second = AssimpUtils::get_fbx_fps(time_mode, state.assimp_scene);
- }
-
- //?
- //if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) {
- // ticks_per_second = 1000.0f;
- //}
-
- if (Math::is_equal_approx(ticks_per_second, 0.0f)) {
- ticks_per_second = 25.0f;
- }
-
- Ref<Animation> animation;
- animation.instance();
- animation->set_name(name);
- animation->set_length(anim->mDuration / ticks_per_second);
-
- if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
- animation->set_loop(true);
- }
-
- // generate bone stack for animation import
- RegenerateBoneStack(state);
-
- //regular tracks
- for (size_t i = 0; i < anim->mNumChannels; i++) {
- const aiNodeAnim *track = anim->mChannels[i];
- String node_name = AssimpUtils::get_assimp_string(track->mNodeName);
- print_verbose("track name import: " + node_name);
- if (track->mNumRotationKeys == 0 && track->mNumPositionKeys == 0 && track->mNumScalingKeys == 0) {
- continue; //do not bother
- }
-
- Skeleton3D *skeleton = nullptr;
- NodePath node_path;
- aiBone *bone = nullptr;
-
- // Import skeleton bone animation for this track
- // Any bone will do, no point in processing more than just what is in the skeleton
- {
- bone = get_bone_from_stack(state, track->mNodeName);
-
- if (bone) {
- // get skeleton by bone
- skeleton = state.armature_skeletons[bone->mArmature];
-
- if (skeleton) {
- String path = state.root->get_path_to(skeleton);
- path += ":" + node_name;
- node_path = path;
-
- if (node_path != NodePath()) {
- _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
- node_path, node_name, bone);
- } else {
- print_error("Failed to find valid node path for animation");
- }
- }
- }
- }
-
- // not a bone
- // note this is flaky it uses node names which is unreliable
- Node *allocated_node = get_node_by_name(state, node_name);
- // todo: implement skeleton grabbing for node based animations too :)
- // check if node exists, if it does then also apply animation track for node and bones above are all handled.
- // this is now inclusive animation handling so that
- // we import all the data and do not miss anything.
- if (allocated_node) {
- node_path = state.root->get_path_to(allocated_node);
-
- if (node_path != NodePath()) {
- _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
- node_path, node_name, nullptr);
- }
- }
- }
-
- //blend shape tracks
-
- for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) {
-
- const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i];
-
- const String prop_name = AssimpUtils::get_assimp_string(anim_mesh->mName);
- const String mesh_name = prop_name.split("*")[0];
-
- ERR_CONTINUE(prop_name.split("*").size() != 2);
-
- Node *item = get_node_by_name(state, mesh_name);
- ERR_CONTINUE_MSG(!item, "failed to look up node by name");
- const MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(item);
- ERR_CONTINUE(mesh_instance == nullptr);
-
- String base_path = state.root->get_path_to(mesh_instance);
-
- Ref<Mesh> mesh = mesh_instance->get_mesh();
- ERR_CONTINUE(mesh.is_null());
-
- //add the tracks for this mesh
- int base_track = animation->get_track_count();
- for (int j = 0; j < mesh->get_blend_shape_count(); j++) {
-
- animation->add_track(Animation::TYPE_VALUE);
- animation->track_set_path(base_track + j, base_path + ":blend_shapes/" + mesh->get_blend_shape_name(j));
- }
-
- for (size_t k = 0; k < anim_mesh->mNumKeys; k++) {
- for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) {
-
- float t = anim_mesh->mKeys[k].mTime / ticks_per_second;
- float w = anim_mesh->mKeys[k].mWeights[j];
-
- animation->track_insert_key(base_track + j, t, w);
- }
- }
- }
-
- if (animation->get_track_count()) {
- state.animation_player->add_animation(name, animation);
- }
-}
-//
-// Mesh Generation from indices ? why do we need so much mesh code
-// [debt needs looked into]
-Ref<Mesh>
-EditorSceneImporterAssimp::_generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices,
- const aiNode *assimp_node, Ref<Skin> &skin,
- Skeleton3D *&skeleton_assigned) {
-
- Ref<ArrayMesh> mesh;
- mesh.instance();
- bool has_uvs = false;
-
- Map<String, uint32_t> morph_mesh_string_lookup;
-
- for (int i = 0; i < p_surface_indices.size(); i++) {
- const unsigned int mesh_idx = p_surface_indices[0];
- const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
- for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
- String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
- if (!morph_mesh_string_lookup.has(ai_anim_mesh_name)) {
- morph_mesh_string_lookup.insert(ai_anim_mesh_name, j);
- mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
- if (ai_anim_mesh_name.empty()) {
- ai_anim_mesh_name = String("morph_") + itos(j);
- }
- mesh->add_blend_shape(ai_anim_mesh_name);
- }
- }
- }
- //
- // Process Vertex Weights
- //
- for (int i = 0; i < p_surface_indices.size(); i++) {
- const unsigned int mesh_idx = p_surface_indices[i];
- const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
-
- Map<uint32_t, Vector<BoneInfo>> vertex_weights;
-
- if (ai_mesh->mNumBones > 0) {
- for (size_t b = 0; b < ai_mesh->mNumBones; b++) {
- aiBone *bone = ai_mesh->mBones[b];
-
- if (!skeleton_assigned) {
- print_verbose("Assigned mesh skeleton during mesh creation");
- skeleton_assigned = state.skeleton_bone_map[bone];
-
- if (!skin.is_valid()) {
- print_verbose("Configured new skin");
- skin.instance();
- } else {
- print_verbose("Reusing existing skin!");
- }
- }
- // skeleton_assigned =
- String bone_name = AssimpUtils::get_assimp_string(bone->mName);
- int bone_index = skeleton_assigned->find_bone(bone_name);
- ERR_CONTINUE(bone_index == -1);
- for (size_t w = 0; w < bone->mNumWeights; w++) {
-
- aiVertexWeight ai_weights = bone->mWeights[w];
-
- BoneInfo bi;
- uint32_t vertex_index = ai_weights.mVertexId;
- bi.bone = bone_index;
- bi.weight = ai_weights.mWeight;
-
- if (!vertex_weights.has(vertex_index)) {
- vertex_weights[vertex_index] = Vector<BoneInfo>();
- }
-
- vertex_weights[vertex_index].push_back(bi);
- }
- }
- }
-
- //
- // Create mesh from data from assimp
- //
-
- Ref<SurfaceTool> st;
- st.instance();
- st->begin(Mesh::PRIMITIVE_TRIANGLES);
-
- for (size_t j = 0; j < ai_mesh->mNumVertices; j++) {
-
- // Get the texture coordinates if they exist
- if (ai_mesh->HasTextureCoords(0)) {
- has_uvs = true;
- st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y));
- }
-
- if (ai_mesh->HasTextureCoords(1)) {
- has_uvs = true;
- st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y));
- }
-
- // Assign vertex colors
- if (ai_mesh->HasVertexColors(0)) {
- Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b,
- ai_mesh->mColors[0]->a);
- st->add_color(color);
- }
-
- // Work out normal calculations? - this needs work it doesn't work properly on huestos
- if (ai_mesh->mNormals != nullptr) {
- const aiVector3D normals = ai_mesh->mNormals[j];
- const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
- st->add_normal(godot_normal);
- if (ai_mesh->HasTangentsAndBitangents()) {
- const aiVector3D tangents = ai_mesh->mTangents[j];
- const Vector3 godot_tangent = Vector3(tangents.x, tangents.y, tangents.z);
- const aiVector3D bitangent = ai_mesh->mBitangents[j];
- const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
- float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
- st->add_tangent(Plane(tangents.x, tangents.y, tangents.z, d));
- }
- }
-
- // We have vertex weights right?
- if (vertex_weights.has(j)) {
-
- Vector<BoneInfo> bone_info = vertex_weights[j];
- Vector<int> bones;
- bones.resize(bone_info.size());
- Vector<float> weights;
- weights.resize(bone_info.size());
-
- // todo? do we really need to loop over all bones? - assimp may have helper to find all influences on this vertex.
- for (int k = 0; k < bone_info.size(); k++) {
- bones.write[k] = bone_info[k].bone;
- weights.write[k] = bone_info[k].weight;
- }
-
- st->add_bones(bones);
- st->add_weights(weights);
- }
-
- // Assign vertex
- const aiVector3D pos = ai_mesh->mVertices[j];
-
- // note we must include node offset transform as this is relative to world space not local space.
- Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z);
- st->add_vertex(godot_pos);
- }
-
- // fire replacement for face handling
- for (size_t j = 0; j < ai_mesh->mNumFaces; j++) {
- const aiFace face = ai_mesh->mFaces[j];
- for (unsigned int k = 0; k < face.mNumIndices; k++) {
- st->add_index(face.mIndices[k]);
- }
- }
-
- if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) {
- st->generate_tangents();
- }
-
- aiMaterial *ai_material = state.assimp_scene->mMaterials[ai_mesh->mMaterialIndex];
- Ref<StandardMaterial3D> mat;
- mat.instance();
-
- int32_t mat_two_sided = 0;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) {
- if (mat_two_sided > 0) {
- mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
- } else {
- mat->set_cull_mode(StandardMaterial3D::CULL_BACK);
- }
- }
-
- aiString mat_name;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) {
- mat->set_name(AssimpUtils::get_assimp_string(mat_name));
- }
-
- // Culling handling for meshes
-
- // cull all back faces
- mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
-
- // Now process materials
- aiTextureType base_color = aiTextureType_BASE_COLOR;
- {
- String filename, path;
- AssimpImageData image_data;
-
- if (AssimpUtils::GetAssimpTexture(state, ai_material, base_color, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
-
- // anything transparent must be culled
- if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
- mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
- mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
- }
-
- mat->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, image_data.texture);
- }
- }
-
- aiTextureType tex_diffuse = aiTextureType_DIFFUSE;
- {
- String filename, path;
- AssimpImageData image_data;
-
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_diffuse, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
-
- // anything transparent must be culled
- if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
- mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
- mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
- }
-
- mat->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, image_data.texture);
- }
-
- aiColor4D clr_diffuse;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) {
- if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) {
- mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
- mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
- }
- mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a));
- }
- }
-
- aiTextureType tex_normal = aiTextureType_NORMALS;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
- } else {
- aiString texture_path;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, AI_PROPERTIES, texture_path)) {
- if (AssimpUtils::CreateAssimpTexture(state, texture_path, filename, path, image_data)) {
- mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
- }
- }
- }
- }
-
- aiTextureType tex_normal_camera = aiTextureType_NORMAL_CAMERA;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal_camera, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
- }
- }
-
- aiTextureType tex_emission_color = aiTextureType_EMISSION_COLOR;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emission_color, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
- }
- }
-
- aiTextureType tex_metalness = aiTextureType_METALNESS;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_metalness, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_texture(StandardMaterial3D::TEXTURE_METALLIC, image_data.texture);
- }
- }
-
- aiTextureType tex_roughness = aiTextureType_DIFFUSE_ROUGHNESS;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_roughness, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_texture(StandardMaterial3D::TEXTURE_ROUGHNESS, image_data.texture);
- }
- }
-
- aiTextureType tex_emissive = aiTextureType_EMISSIVE;
- {
- String filename = "";
- String path = "";
- Ref<Image> texture;
- AssimpImageData image_data;
-
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emissive, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_EMISSION, image_data.texture);
- } else {
- // Process emission textures
- aiString texture_emissive_path;
- if (AI_SUCCESS ==
- ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE, AI_PROPERTIES, texture_emissive_path)) {
- if (AssimpUtils::CreateAssimpTexture(state, texture_emissive_path, filename, path, image_data)) {
- mat->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_EMISSION, image_data.texture);
- }
- } else {
- float pbr_emission = 0.0f;
- if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR, AI_NULL, pbr_emission)) {
- mat->set_emission(Color(pbr_emission, pbr_emission, pbr_emission, 1.0f));
- }
- }
- }
- }
-
- aiTextureType tex_specular = aiTextureType_SPECULAR;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_specular, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_texture(StandardMaterial3D::TEXTURE_METALLIC, image_data.texture);
- }
- }
-
- aiTextureType tex_ao_map = aiTextureType_AMBIENT_OCCLUSION;
- {
- String filename, path;
- Ref<ImageTexture> texture;
- AssimpImageData image_data;
-
- // Process texture normal map
- if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_ao_map, filename, path, image_data)) {
- AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
- mat->set_feature(StandardMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
- mat->set_texture(StandardMaterial3D::TEXTURE_AMBIENT_OCCLUSION, image_data.texture);
- }
- }
-
- Array array_mesh = st->commit_to_arrays();
- Array morphs;
- morphs.resize(ai_mesh->mNumAnimMeshes);
- Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
-
- for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
-
- String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
-
- if (ai_anim_mesh_name.empty()) {
- ai_anim_mesh_name = String("morph_") + itos(j);
- }
-
- Array array_copy;
- array_copy.resize(RenderingServer::ARRAY_MAX);
-
- for (int l = 0; l < RenderingServer::ARRAY_MAX; l++) {
- array_copy[l] = array_mesh[l].duplicate(true);
- }
-
- const size_t num_vertices = ai_mesh->mAnimMeshes[j]->mNumVertices;
- array_copy[Mesh::ARRAY_INDEX] = Variant();
- if (ai_mesh->mAnimMeshes[j]->HasPositions()) {
- PackedVector3Array vertices;
- vertices.resize(num_vertices);
- for (size_t l = 0; l < num_vertices; l++) {
- const aiVector3D ai_pos = ai_mesh->mAnimMeshes[j]->mVertices[l];
- Vector3 position = Vector3(ai_pos.x, ai_pos.y, ai_pos.z);
- vertices.ptrw()[l] = position;
- }
- PackedVector3Array new_vertices = array_copy[RenderingServer::ARRAY_VERTEX].duplicate(true);
- ERR_CONTINUE(vertices.size() != new_vertices.size());
- for (int32_t l = 0; l < new_vertices.size(); l++) {
- Vector3 *w = new_vertices.ptrw();
- w[l] = vertices[l];
- }
- array_copy[RenderingServer::ARRAY_VERTEX] = new_vertices;
- }
-
- int32_t color_set = 0;
- if (ai_mesh->mAnimMeshes[j]->HasVertexColors(color_set)) {
- PackedColorArray colors;
- colors.resize(num_vertices);
- for (size_t l = 0; l < num_vertices; l++) {
- const aiColor4D ai_color = ai_mesh->mAnimMeshes[j]->mColors[color_set][l];
- Color color = Color(ai_color.r, ai_color.g, ai_color.b, ai_color.a);
- colors.ptrw()[l] = color;
- }
- PackedColorArray new_colors = array_copy[RenderingServer::ARRAY_COLOR].duplicate(true);
- ERR_CONTINUE(colors.size() != new_colors.size());
- for (int32_t l = 0; l < colors.size(); l++) {
- Color *w = new_colors.ptrw();
- w[l] = colors[l];
- }
- array_copy[RenderingServer::ARRAY_COLOR] = new_colors;
- }
-
- if (ai_mesh->mAnimMeshes[j]->HasNormals()) {
- PackedVector3Array normals;
- normals.resize(num_vertices);
- for (size_t l = 0; l < num_vertices; l++) {
- const aiVector3D ai_normal = ai_mesh->mAnimMeshes[j]->mNormals[l];
- Vector3 normal = Vector3(ai_normal.x, ai_normal.y, ai_normal.z);
- normals.ptrw()[l] = normal;
- }
- PackedVector3Array new_normals = array_copy[RenderingServer::ARRAY_NORMAL].duplicate(true);
- ERR_CONTINUE(normals.size() != new_normals.size());
- for (int l = 0; l < normals.size(); l++) {
- Vector3 *w = new_normals.ptrw();
- w[l] = normals[l];
- }
- array_copy[RenderingServer::ARRAY_NORMAL] = new_normals;
- }
-
- if (ai_mesh->mAnimMeshes[j]->HasTangentsAndBitangents()) {
- PackedColorArray tangents;
- tangents.resize(num_vertices);
- Color *w = tangents.ptrw();
- for (size_t l = 0; l < num_vertices; l++) {
- AssimpUtils::calc_tangent_from_mesh(ai_mesh, j, l, l, w);
- }
- PackedFloat32Array new_tangents = array_copy[RenderingServer::ARRAY_TANGENT].duplicate(true);
- ERR_CONTINUE(new_tangents.size() != tangents.size() * 4);
- for (int32_t l = 0; l < tangents.size(); l++) {
- new_tangents.ptrw()[l + 0] = tangents[l].r;
- new_tangents.ptrw()[l + 1] = tangents[l].g;
- new_tangents.ptrw()[l + 2] = tangents[l].b;
- new_tangents.ptrw()[l + 3] = tangents[l].a;
- }
- array_copy[RenderingServer::ARRAY_TANGENT] = new_tangents;
- }
-
- morphs[j] = array_copy;
- }
- mesh->add_surface_from_arrays(primitive, array_mesh, morphs);
- mesh->surface_set_material(i, mat);
- mesh->surface_set_name(i, AssimpUtils::get_assimp_string(ai_mesh->mName));
- }
-
- return mesh;
-}
-
-/**
- * Create a new mesh for the node supplied
- */
-MeshInstance3D *
-EditorSceneImporterAssimp::create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform) {
- /* MESH NODE */
- Ref<Mesh> mesh;
- Ref<Skin> skin;
- // see if we have mesh cache for this.
- Vector<int> surface_indices;
-
- RegenerateBoneStack(state);
-
- // Configure indices
- for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
- int mesh_index = assimp_node->mMeshes[i];
- // create list of mesh indexes
- surface_indices.push_back(mesh_index);
- }
-
- //surface_indices.sort();
- String mesh_key;
- for (int i = 0; i < surface_indices.size(); i++) {
- if (i > 0) {
- mesh_key += ":";
- }
- mesh_key += itos(surface_indices[i]);
- }
-
- Skeleton3D *skeleton = nullptr;
- aiNode *armature = nullptr;
-
- if (!state.mesh_cache.has(mesh_key)) {
- mesh = _generate_mesh_from_surface_indices(state, surface_indices, assimp_node, skin, skeleton);
- state.mesh_cache[mesh_key] = mesh;
- }
-
- MeshInstance3D *mesh_node = memnew(MeshInstance3D);
- mesh = state.mesh_cache[mesh_key];
- mesh_node->set_mesh(mesh);
-
- // if we have a valid skeleton set it up
- if (skin.is_valid()) {
- for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
- unsigned int mesh_index = assimp_node->mMeshes[i];
- const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_index];
-
- // please remember bone id relative to the skin is NOT the mesh relative index.
- // it is the index relative to the skeleton that is why
- // we have state.bone_id_map, it allows for duplicate bone id's too :)
- // hope this makes sense
-
- int bind_count = 0;
- for (unsigned int boneId = 0; boneId < ai_mesh->mNumBones; ++boneId) {
- aiBone *iterBone = ai_mesh->mBones[boneId];
-
- // used to reparent mesh to the correct armature later on if assigned.
- if (!armature) {
- print_verbose("Configured mesh armature, will reparent later to armature");
- armature = iterBone->mArmature;
- }
-
- if (skeleton) {
- int id = skeleton->find_bone(AssimpUtils::get_assimp_string(iterBone->mName));
- if (id != -1) {
- print_verbose("Set bind bone: mesh: " + itos(mesh_index) + " bone index: " + itos(id));
- Transform t = AssimpUtils::assimp_matrix_transform(iterBone->mOffsetMatrix);
-
- skin->add_bind(bind_count, t);
- skin->set_bind_bone(bind_count, id);
- bind_count++;
- }
- }
- }
- }
-
- print_verbose("Finished configuring bind pose for skin mesh");
- }
-
- // this code parents all meshes with bones to the armature they are for
- // GLTF2 specification relies on this and we are enforcing it for FBX.
- if (armature && state.flat_node_map[armature]) {
- Node *armature_parent = state.flat_node_map[armature];
- print_verbose("Parented mesh " + node_name + " to armature " + armature_parent->get_name());
- // static mesh handling
- armature_parent->add_child(mesh_node);
- // transform must be identity
- mesh_node->set_global_transform(Transform());
- mesh_node->set_name(node_name);
- mesh_node->set_owner(state.root);
- } else {
- // static mesh handling
- active_node->add_child(mesh_node);
- mesh_node->set_global_transform(node_transform);
- mesh_node->set_name(node_name);
- mesh_node->set_owner(state.root);
- }
-
- if (skeleton) {
- print_verbose("Attempted to set skeleton path!");
- mesh_node->set_skeleton_path(mesh_node->get_path_to(skeleton));
- mesh_node->set_skin(skin);
- }
-
- return mesh_node;
-}
-
-/**
- * Create a light for the scene
- * Automatically caches lights for lookup later
- */
-Node3D *EditorSceneImporterAssimp::create_light(
- ImportState &state,
- const String &node_name,
- Transform &look_at_transform) {
- Light3D *light = nullptr;
- aiLight *assimp_light = state.assimp_scene->mLights[state.light_cache[node_name]];
- ERR_FAIL_COND_V(!assimp_light, nullptr);
-
- if (assimp_light->mType == aiLightSource_DIRECTIONAL) {
- light = memnew(DirectionalLight3D);
- } else if (assimp_light->mType == aiLightSource_POINT) {
- light = memnew(OmniLight3D);
- } else if (assimp_light->mType == aiLightSource_SPOT) {
- light = memnew(SpotLight3D);
- }
- ERR_FAIL_COND_V(light == nullptr, nullptr);
-
- if (assimp_light->mType != aiLightSource_POINT) {
- Vector3 pos = Vector3(
- assimp_light->mPosition.x,
- assimp_light->mPosition.y,
- assimp_light->mPosition.z);
- Vector3 look_at = Vector3(
- assimp_light->mDirection.y,
- assimp_light->mDirection.x,
- assimp_light->mDirection.z)
- .normalized();
- Vector3 up = Vector3(
- assimp_light->mUp.x,
- assimp_light->mUp.y,
- assimp_light->mUp.z);
-
- look_at_transform.set_look_at(pos, look_at, up);
- }
- // properties for light variables should be put here.
- // not really hugely important yet but we will need them in the future
-
- light->set_color(
- Color(assimp_light->mColorDiffuse.r, assimp_light->mColorDiffuse.g, assimp_light->mColorDiffuse.b));
-
- return light;
-}
-
-/**
- * Create camera for the scene
- */
-Node3D *EditorSceneImporterAssimp::create_camera(
- ImportState &state,
- const String &node_name,
- Transform &look_at_transform) {
- aiCamera *camera = state.assimp_scene->mCameras[state.camera_cache[node_name]];
- ERR_FAIL_COND_V(!camera, nullptr);
-
- Camera3D *camera_node = memnew(Camera3D);
- ERR_FAIL_COND_V(!camera_node, nullptr);
- float near = camera->mClipPlaneNear;
- if (Math::is_equal_approx(near, 0.0f)) {
- near = 0.1f;
- }
- camera_node->set_perspective(Math::rad2deg(camera->mHorizontalFOV) * 2.0f, near, camera->mClipPlaneFar);
- Vector3 pos = Vector3(camera->mPosition.x, camera->mPosition.y, camera->mPosition.z);
- Vector3 look_at = Vector3(camera->mLookAt.y, camera->mLookAt.x, camera->mLookAt.z).normalized();
- Vector3 up = Vector3(camera->mUp.x, camera->mUp.y, camera->mUp.z);
-
- look_at_transform.set_look_at(pos + look_at_transform.origin, look_at, up);
- return camera_node;
-}
-
-/**
- * Generate node
- * Recursive call to iterate over all nodes
- */
-void EditorSceneImporterAssimp::_generate_node(
- ImportState &state,
- const aiNode *assimp_node) {
-
- ERR_FAIL_COND(assimp_node == nullptr);
- state.nodes.push_back(assimp_node);
- String parent_name = AssimpUtils::get_assimp_string(assimp_node->mParent->mName);
-
- // please note
- // duplicate bone names exist
- // this is why we only check if the bone exists
- // so everything else is useless but the name
- // please do not copy any other values from get_bone_by_name.
- aiBone *parent_bone = get_bone_by_name(state.assimp_scene, assimp_node->mParent->mName);
- aiBone *current_bone = get_bone_by_name(state.assimp_scene, assimp_node->mName);
-
- // is this an armature
- // parent null
- // and this is the first bone :)
- if (parent_bone == nullptr && current_bone) {
- state.armature_nodes.push_back(assimp_node->mParent);
- print_verbose("found valid armature: " + parent_name);
- }
-
- for (size_t i = 0; i < assimp_node->mNumChildren; i++) {
- _generate_node(state, assimp_node->mChildren[i]);
- }
-}
diff --git a/modules/assimp/editor_scene_importer_assimp.h b/modules/assimp/editor_scene_importer_assimp.h
deleted file mode 100644
index ab00a6c3aa..0000000000
--- a/modules/assimp/editor_scene_importer_assimp.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*************************************************************************/
-/* editor_scene_importer_assimp.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 EDITOR_SCENE_IMPORTER_ASSIMP_H
-#define EDITOR_SCENE_IMPORTER_ASSIMP_H
-
-#ifdef TOOLS_ENABLED
-#include "core/bind/core_bind.h"
-#include "core/io/resource_importer.h"
-#include "core/vector.h"
-#include "editor/import/resource_importer_scene.h"
-#include "editor/project_settings_editor.h"
-#include "scene/3d/mesh_instance_3d.h"
-#include "scene/3d/node_3d.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/animation/animation_player.h"
-#include "scene/resources/animation.h"
-#include "scene/resources/surface_tool.h"
-
-#include <assimp/matrix4x4.h>
-#include <assimp/scene.h>
-#include <assimp/types.h>
-#include <assimp/DefaultLogger.hpp>
-#include <assimp/LogStream.hpp>
-#include <assimp/Logger.hpp>
-#include <map>
-
-#include "import_state.h"
-#include "import_utils.h"
-
-using namespace AssimpImporter;
-
-class AssimpStream : public Assimp::LogStream {
-public:
- // Constructor
- AssimpStream() {}
-
- // Destructor
- ~AssimpStream() {}
- // Write something using your own functionality
- void write(const char *message) {
- print_verbose(String("Open Asset Import: ") + String(message).strip_edges());
- }
-};
-
-class EditorSceneImporterAssimp : public EditorSceneImporter {
-private:
- GDCLASS(EditorSceneImporterAssimp, EditorSceneImporter);
-
- struct AssetImportAnimation {
- enum Interpolation {
- INTERP_LINEAR,
- INTERP_STEP,
- INTERP_CATMULLROMSPLINE,
- INTERP_CUBIC_SPLINE
- };
- };
-
- struct BoneInfo {
- uint32_t bone;
- float weight;
- };
-
- Ref<Mesh> _generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices,
- const aiNode *assimp_node, Ref<Skin> &skin,
- Skeleton3D *&skeleton_assigned);
-
- // simple object creation functions
- Node3D *create_light(ImportState &state,
- const String &node_name,
- Transform &look_at_transform);
- Node3D *create_camera(
- ImportState &state,
- const String &node_name,
- Transform &look_at_transform);
- // non recursive - linear so must not use recursive arguments
- MeshInstance3D *create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform);
- // recursive node generator
- void _generate_node(ImportState &state, const aiNode *assimp_node);
- void _insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id,
- int anim_fps, Ref<Animation> animation, float ticks_per_second,
- Skeleton3D *skeleton, const NodePath &node_path,
- const String &node_name, aiBone *track_bone);
-
- void _import_animation(ImportState &state, int p_animation_index, int p_bake_fps);
- Node *get_node_by_name(ImportState &state, String name);
- aiBone *get_bone_from_stack(ImportState &state, aiString name);
- Node3D *_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps, const int32_t p_max_bone_weights);
-
- template <class T>
- T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, AssetImportAnimation::Interpolation p_interp);
- void _register_project_setting_import(const String generic, const String import_setting_string, const Vector<String> &exts, List<String> *r_extensions, const bool p_enabled) const;
-
- struct ImportFormat {
- Vector<String> extensions;
- bool is_default;
- };
-
-protected:
- static void _bind_methods();
-
-public:
- EditorSceneImporterAssimp() {
- Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE);
- unsigned int severity = Assimp::Logger::Info | Assimp::Logger::Err | Assimp::Logger::Warn;
- Assimp::DefaultLogger::get()->attachStream(new AssimpStream(), severity);
- }
- ~EditorSceneImporterAssimp() {
- Assimp::DefaultLogger::kill();
- }
-
- virtual void get_extensions(List<String> *r_extensions) const;
- virtual uint32_t get_import_flags() const;
- virtual Node *import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr);
- Ref<Image> load_image(ImportState &state, const aiScene *p_scene, String p_path);
-
- static void RegenerateBoneStack(ImportState &state);
-
- void RegenerateBoneStack(ImportState &state, aiMesh *mesh);
-};
-#endif
-#endif
diff --git a/modules/assimp/godot_update_assimp.sh b/modules/assimp/godot_update_assimp.sh
deleted file mode 100755
index ff8ff59e97..0000000000
--- a/modules/assimp/godot_update_assimp.sh
+++ /dev/null
@@ -1,262 +0,0 @@
-rm -rf ../../thirdparty/assimp
-cd ../../thirdparty/
-git clone https://github.com/assimp/assimp.git
-cd assimp
-rm -rf code/3DSExporter.h
-rm -rf code/3DSLoader.h
-rm -rf code/3MFXmlTags.h
-rm -rf code/ABCImporter.h
-rm -rf code/ACLoader.h
-rm -rf code/AMFImporter_Macro.hpp
-rm -rf code/ASELoader.h
-rm -rf code/assbin_chunks.h
-rm -rf code/AssbinExporter.h
-rm -rf code/AssbinLoader.h
-rm -rf code/AssimpCExport.cpp
-rm -rf code/AssxmlExporter.h
-rm -rf code/B3DImporter.h
-# rm -rf code/BaseProcess.cpp
-# rm -rf code/BaseProcess.h
-# rm -rf code/Bitmap.cpp
-rm -rf code/BlenderBMesh.cpp
-rm -rf code/BlenderBMesh.h
-rm -rf code/BlenderCustomData.cpp
-rm -rf code/BlenderCustomData.h
-rm -rf code/BlenderIntermediate.h
-rm -rf code/BlenderLoader.h
-rm -rf code/BlenderModifier.h
-rm -rf code/BlenderSceneGen.h
-rm -rf code/BlenderTessellator.h
-rm -rf code/BVHLoader.h
-rm -rf code/C4DImporter.h
-# rm -rf code/CalcTangentsProcess.h
-# rm -rf code/CInterfaceIOWrapper.cpp
-# rm -rf code/CInterfaceIOWrapper.h
-rm -rf code/COBLoader.h
-rm -rf code/COBScene.h
-rm -rf code/ColladaExporter.h
-rm -rf code/ColladaLoader.h
-# rm -rf code/ComputeUVMappingProcess.h
-# rm -rf code/ConvertToLHProcess.h
-# rm -rf code/CreateAnimMesh.cpp
-rm -rf code/CSMLoader.h
-rm -rf code/D3MFExporter.h
-rm -rf code/D3MFImporter.h
-rm -rf code/D3MFOpcPackage.h
-# rm -rf code/DeboneProcess.h
-# rm -rf code/DefaultIOStream.cpp
-# rm -rf code/DefaultIOSystem.cpp
-# rm -rf code/DefaultProgressHandler.h
-# rm -rf code/DropFaceNormalsProcess.cpp
-# rm -rf code/DropFaceNormalsProcess.h
-rm -rf code/DXFHelper.h
-rm -rf code/DXFLoader.h
-# rm -rf code/EmbedTexturesProcess.cpp
-# rm -rf code/EmbedTexturesProcess.h
-# rm -rf code/FBXCommon.h
-# rm -rf code/FBXCompileConfig.h
-# rm -rf code/FBXDeformer.cpp
-# rm -rf code/FBXDocumentUtil.cpp
-# rm -rf code/FBXDocumentUtil.h
-# rm -rf code/FBXExporter.h
-# rm -rf code/FBXExportNode.h
-# rm -rf code/FBXExportProperty.h
-# rm -rf code/FBXImporter.cpp
-# rm -rf code/FBXImporter.h
-# rm -rf code/FBXImportSettings.h
-# rm -rf code/FBXMeshGeometry.h
-# rm -rf code/FBXModel.cpp
-# rm -rf code/FBXNodeAttribute.cpp
-# rm -rf code/FBXParser.h
-# rm -rf code/FBXProperties.cpp
-# rm -rf code/FBXProperties.h
-# rm -rf code/FBXTokenizer.cpp
-# rm -rf code/FBXTokenizer.h
-# rm -rf code/FBXUtil.cpp
-# rm -rf code/FBXUtil.h
-# rm -rf code/FileLogStream.h
-# rm -rf code/FindDegenerates.h
-# rm -rf code/FindInstancesProcess.h
-# rm -rf code/FindInvalidDataProcess.h
-rm -rf code/FIReader.hpp
-# rm -rf code/FixNormalsStep.cpp
-# rm -rf code/FixNormalsStep.h
-# rm -rf code/GenFaceNormalsProcess.cpp
-# rm -rf code/GenFaceNormalsProcess.h
-# rm -rf code/GenVertexNormalsProcess.cpp
-# rm -rf code/GenVertexNormalsProcess.h
-rm -rf code/glTF2Asset.h
-rm -rf code/glTF2Asset.inl
-rm -rf code/glTF2AssetWriter.inl
-rm -rf code/glTF2Exporter.cpp
-rm -rf code/glTF2Importer.cpp
-rm -rf code/glTF2AssetWriter.h
-rm -rf code/glTFAsset.h
-rm -rf code/glTFAsset.inl
-rm -rf code/glTFAssetWriter.inl
-rm -rf code/glTFExporter.cpp
-rm -rf code/glTFImporter.cpp
-rm -rf code/glTF2Exporter.h
-rm -rf code/glTF2Importer.h
-rm -rf code/glTFAssetWriter.h
-rm -rf code/glTFExporter.h
-rm -rf code/glTFImporter.h
-rm -rf code/HalfLifeFileData.h
-rm -rf code/HMPFileData.h
-rm -rf code/HMPLoader.h
-rm -rf code/HMPLoader.cpp
-rm -rf code/IFF.h
-# rm -rf code/Importer.h
-# rm -rf code/ImproveCacheLocality.h
-rm -rf code/IRRLoader.h
-rm -rf code/IRRMeshLoader.h
-rm -rf code/IRRShared.h
-# rm -rf code/JoinVerticesProcess.h
-# rm -rf code/LimitBoneWeightsProcess.cpp
-# rm -rf code/LimitBoneWeightsProcess.h
-rm -rf code/LWSLoader.h
-rm -rf code/makefile.mingw
-# rm -rf code/MakeVerboseFormat.cpp
-# rm -rf code/MakeVerboseFormat.h
-# rm -rf code/MaterialSystem.h
-rm -rf code/MD2FileData.h
-rm -rf code/MD2Loader.h
-rm -rf code/MD2NormalTable.h
-rm -rf code/MD3FileData.h
-rm -rf code/MD3Loader.h
-rm -rf code/MD4FileData.h
-rm -rf code/MD5Loader.h
-rm -rf code/MD5Parser.cpp
-rm -rf code/MDCFileData.h
-rm -rf code/MDCLoader.h
-rm -rf code/MDLDefaultColorMap.h
-# rm -rf code/MMDCpp14.h
-# rm -rf code/MMDImporter.h
-rm -rf code/MS3DLoader.h
-rm -rf code/NDOLoader.h
-rm -rf code/NFFLoader.h
-rm -rf code/ObjExporter.h
-rm -rf code/ObjFileImporter.h
-rm -rf code/ObjFileMtlImporter.h
-rm -rf code/ObjFileParser.h
-rm -rf code/ObjTools.h
-rm -rf code/ObjExporter.cpp
-rm -rf code/ObjFileImporter.cpp
-rm -rf code/ObjFileMtlImporter.cpp
-rm -rf code/ObjFileParser.cpp
-rm -rf code/OFFLoader.h
-rm -rf code/OFFLoader.cpp
-rm -rf code/OgreImporter.cpp
-rm -rf code/OgreImporter.h
-rm -rf code/OgreParsingUtils.h
-rm -rf code/OgreXmlSerializer.h
-rm -rf code/OgreXmlSerializer.cpp
-rm -rf code/OgreBinarySerializer.cpp
-rm -rf code/OpenGEXExporter.cpp
-rm -rf code/OpenGEXExporter.h
-rm -rf code/OpenGEXImporter.h
-rm -rf code/OpenGEXStructs.h
-rm -rf code/OpenGEXImporter.cpp
-# rm -rf code/OptimizeGraph.h
-# rm -rf code/OptimizeMeshes.cpp
-# rm -rf code/OptimizeMeshes.h
-rm -rf code/PlyExporter.h
-rm -rf code/PlyLoader.h
-# rm -rf code/PolyTools.h
-# rm -rf code/PostStepRegistry.cpp
-# rm -rf code/PretransformVertices.h
-rm -rf code/Q3BSPFileData.h
-rm -rf code/Q3BSPFileImporter.h
-rm -rf code/Q3BSPFileParser.cpp
-rm -rf code/Q3BSPFileParser.h
-rm -rf code/Q3BSPZipArchive.cpp
-rm -rf code/Q3BSPZipArchive.h
-rm -rf code/Q3DLoader.h
-rm -rf code/Q3DLoader.cpp
-rm -rf code/Q3BSPFileImporter.cpp
-rm -rf code/RawLoader.h
-# rm -rf code/RemoveComments.cpp
-# rm -rf code/RemoveRedundantMaterials.cpp
-# rm -rf code/RemoveRedundantMaterials.h
-# rm -rf code/RemoveVCProcess.h
-# rm -rf code/ScaleProcess.cpp
-# rm -rf code/ScaleProcess.h
-# rm -rf code/scene.cpp
-# rm -rf code/ScenePreprocessor.cpp
-# rm -rf code/ScenePreprocessor.h
-# rm -rf code/ScenePrivate.h
-# rm -rf code/SGSpatialSort.cpp
-rm -rf code/SIBImporter.h
-rm -rf code/SMDLoader.cpp
-# rm -rf code/simd.cpp
-# rm -rf code/simd.h
-# rm -rf code/SortByPTypeProcess.h
-# rm -rf code/SplitByBoneCountProcess.h
-# rm -rf code/SplitLargeMeshes.h
-# rm -rf code/StdOStreamLogStream.h
-rm -rf code/StepExporter.h
-rm -rf code/StepExporter.cpp
-rm -rf code/STLExporter.cpp
-rm -rf code/STLExporter.h
-rm -rf code/STLLoader.h
-rm -rf code/STLLoader.cpp
-# rm -rf code/TargetAnimation.cpp
-# rm -rf code/TargetAnimation.h
-rm -rf code/TerragenLoader.h
-rm -rf code/TerragenLoader.cpp
-# rm -rf code/TextureTransform.h
-# rm -rf code/TriangulateProcess.h
-rm -rf code/UnrealLoader.h
-# rm -rf code/ValidateDataStructure.h
-# rm -rf code/Version.cpp
-# rm -rf code/VertexTriangleAdjacency.cpp
-# rm -rf code/VertexTriangleAdjacency.h
-# rm -rf code/Win32DebugLogStream.h
-rm -rf code/X3DImporter_Macro.hpp
-rm -rf code/X3DImporter_Metadata.cpp
-rm -rf code/X3DImporter_Networking.cpp
-rm -rf code/X3DImporter_Texturing.cpp
-rm -rf code/X3DImporter_Shape.cpp
-rm -rf code/X3DImporter_Rendering.cpp
-rm -rf code/X3DImporter_Postprocess.cpp
-rm -rf code/X3DImporter_Light.cpp
-rm -rf code/X3DImporter_Group.cpp
-rm -rf code/X3DImporter_Geometry3D.cpp
-rm -rf code/X3DImporter_Geometry2D.cpp
-rm -rf code/X3DImporter.cpp
-rm -rf code/X3DExporter.cpp
-rm -rf code/X3DVocabulary.cpp
-rm -rf code/XFileExporter.h
-rm -rf code/XFileExporter.cpp
-rm -rf code/XFileHelper.h
-rm -rf code/XFileHelper.cpp
-rm -rf code/XFileImporter.h
-rm -rf code/XFileImporter.cpp
-rm -rf code/XFileParser.h
-rm -rf code/XFileParser.cpp
-rm -rf code/XGLLoader.h
-rm -rf code/XGLLoader.cpp
-rm -rf code/Importer
-rm -rf .git
-rm -rf cmake-modules
-rm -rf doc
-rm -rf packaging
-rm -rf port
-rm -rf samples
-rm -rf scripts
-rm -rf test
-rm -rf tools
-rm -rf contrib/zlib
-rm -rf contrib/android-cmake
-rm -rf contrib/gtest
-rm -rf contrib/clipper
-rm -rf contrib/irrXML
-rm -rf contrib/Open3DGC
-rm -rf contrib/openddlparser
-rm -rf contrib/poly2tri
-#rm -rf contrib/rapidjson
-rm -rf contrib/unzip
-rm -rf contrib/zip
-rm -rf contrib/stb_image
-rm .travis*
-
diff --git a/modules/assimp/import_state.h b/modules/assimp/import_state.h
deleted file mode 100644
index cda1a854f0..0000000000
--- a/modules/assimp/import_state.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*************************************************************************/
-/* import_state.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 EDITOR_SCENE_IMPORT_STATE_H
-#define EDITOR_SCENE_IMPORT_STATE_H
-
-#include "core/bind/core_bind.h"
-#include "core/io/resource_importer.h"
-#include "core/vector.h"
-#include "editor/import/resource_importer_scene.h"
-#include "editor/project_settings_editor.h"
-#include "scene/3d/mesh_instance_3d.h"
-#include "scene/3d/node_3d.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/animation/animation_player.h"
-#include "scene/resources/animation.h"
-#include "scene/resources/surface_tool.h"
-
-#include <assimp/matrix4x4.h>
-#include <assimp/scene.h>
-#include <assimp/types.h>
-#include <assimp/DefaultLogger.hpp>
-#include <assimp/LogStream.hpp>
-#include <assimp/Logger.hpp>
-
-namespace AssimpImporter {
-/** Import state is for global scene import data
- * This makes the code simpler and contains useful lookups.
- */
-struct ImportState {
-
- String path;
- Node3D *root;
- const aiScene *assimp_scene;
- uint32_t max_bone_weights;
-
- Map<String, Ref<Mesh>> mesh_cache;
- Map<int, Ref<Material>> material_cache;
- Map<String, int> light_cache;
- Map<String, int> camera_cache;
-
- // very useful for when you need to ask assimp for the bone mesh
-
- Map<const aiNode *, Node *> assimp_node_map;
- Map<String, Ref<Image>> path_to_image_cache;
-
- // Generation 3 - determinisitic iteration
- // to lower potential recursion errors
- List<const aiNode *> nodes;
- Map<const aiNode *, Node3D *> flat_node_map;
- AnimationPlayer *animation_player;
-
- // Generation 3 - deterministic armatures
- // list of armature nodes - flat and simple to parse
- // assimp node, node in godot
- List<aiNode *> armature_nodes;
- Map<const aiNode *, Skeleton3D *> armature_skeletons;
- Map<aiBone *, Skeleton3D *> skeleton_bone_map;
- // Generation 3 - deterministic bone handling
- // bones from the stack are popped when found
- // this means we can detect
- // what bones are for other armatures
- List<aiBone *> bone_stack;
-};
-
-struct AssimpImageData {
- Ref<Image> raw_image;
- Ref<ImageTexture> texture;
- aiTextureMapMode map_mode[2];
-};
-
-/** Recursive state is used to push state into functions instead of specifying them
- * This makes the code easier to handle too and add extra arguments without breaking things
- */
-struct RecursiveState {
- RecursiveState() {} // do not construct :)
- RecursiveState(
- Transform &_node_transform,
- Skeleton3D *_skeleton,
- Node3D *_new_node,
- String &_node_name,
- aiNode *_assimp_node,
- Node *_parent_node,
- aiBone *_bone) :
- node_transform(_node_transform),
- skeleton(_skeleton),
- new_node(_new_node),
- node_name(_node_name),
- assimp_node(_assimp_node),
- parent_node(_parent_node),
- bone(_bone) {}
-
- Transform node_transform;
- Skeleton3D *skeleton = nullptr;
- Node3D *new_node = nullptr;
- String node_name;
- aiNode *assimp_node = nullptr;
- Node *parent_node = nullptr;
- aiBone *bone = nullptr;
-};
-} // namespace AssimpImporter
-
-#endif // EDITOR_SCENE_IMPORT_STATE_H
diff --git a/modules/assimp/import_utils.h b/modules/assimp/import_utils.h
deleted file mode 100644
index f78931add3..0000000000
--- a/modules/assimp/import_utils.h
+++ /dev/null
@@ -1,451 +0,0 @@
-/*************************************************************************/
-/* import_utils.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 IMPORT_UTILS_IMPORTER_ASSIMP_H
-#define IMPORT_UTILS_IMPORTER_ASSIMP_H
-
-#include "core/io/image_loader.h"
-#include "import_state.h"
-
-#include <assimp/SceneCombiner.h>
-#include <assimp/cexport.h>
-#include <assimp/cimport.h>
-#include <assimp/matrix4x4.h>
-#include <assimp/pbrmaterial.h>
-#include <assimp/postprocess.h>
-#include <assimp/scene.h>
-#include <assimp/DefaultLogger.hpp>
-#include <assimp/Importer.hpp>
-#include <assimp/LogStream.hpp>
-#include <assimp/Logger.hpp>
-#include <string>
-
-using namespace AssimpImporter;
-
-#define AI_PROPERTIES aiTextureType_UNKNOWN, 0
-#define AI_NULL 0, 0
-#define AI_MATKEY_FBX_MAYA_BASE_COLOR_FACTOR "$raw.Maya|baseColor"
-#define AI_MATKEY_FBX_MAYA_METALNESS_FACTOR "$raw.Maya|metalness"
-#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_FACTOR "$raw.Maya|diffuseRoughness"
-
-#define AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE "$raw.Maya|emissionColor|file"
-#define AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR "$raw.Maya|emission"
-#define AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE "$raw.Maya|metalness|file"
-#define AI_MATKEY_FBX_MAYA_METALNESS_UV_XFORM "$raw.Maya|metalness|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE "$raw.Maya|diffuseRoughness|file"
-#define AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_UV_XFORM "$raw.Maya|diffuseRoughness|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE "$raw.Maya|baseColor|file"
-#define AI_MATKEY_FBX_MAYA_BASE_COLOR_UV_XFORM "$raw.Maya|baseColor|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE "$raw.Maya|normalCamera|file"
-#define AI_MATKEY_FBX_MAYA_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo"
-
-#define AI_MATKEY_FBX_NORMAL_TEXTURE "$raw.Maya|normalCamera|file"
-#define AI_MATKEY_FBX_NORMAL_UV_XFORM "$raw.Maya|normalCamera|uvtrafo"
-
-#define AI_MATKEY_FBX_MAYA_STINGRAY_DISPLACEMENT_SCALING_FACTOR "$raw.Maya|displacementscaling"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_BASE_COLOR_FACTOR "$raw.Maya|base_color"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_FACTOR "$raw.Maya|emissive"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_FACTOR "$raw.Maya|metallic"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_FACTOR "$raw.Maya|roughness"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_INTENSITY_FACTOR "$raw.Maya|emissive_intensity"
-
-#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE "$raw.Maya|TEX_normal_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_UV_XFORM "$raw.Maya|TEX_normal_map|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE "$raw.Maya|TEX_color_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_UV_XFORM "$raw.Maya|TEX_color_map|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE "$raw.Maya|TEX_metallic_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_UV_XFORM "$raw.Maya|TEX_metallic_map|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE "$raw.Maya|TEX_roughness_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_UV_XFORM "$raw.Maya|TEX_roughness_map|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE "$raw.Maya|TEX_emissive_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_UV_XFORM "$raw.Maya|TEX_emissive_map|uvtrafo"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_TEXTURE "$raw.Maya|TEX_ao_map|file"
-#define AI_MATKEY_FBX_MAYA_STINGRAY_AO_UV_XFORM "$raw.Maya|TEX_ao_map|uvtrafo"
-
-/**
- * Assimp Utils
- * Conversion tools / glue code to convert from assimp to godot
-*/
-class AssimpUtils {
-public:
- /**
- * calculate tangents for mesh data from assimp data
- */
- static void calc_tangent_from_mesh(const aiMesh *ai_mesh, int i, int tri_index, int index, Color *w) {
- const aiVector3D normals = ai_mesh->mAnimMeshes[i]->mNormals[tri_index];
- const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
- const aiVector3D tangent = ai_mesh->mAnimMeshes[i]->mTangents[tri_index];
- const Vector3 godot_tangent = Vector3(tangent.x, tangent.y, tangent.z);
- const aiVector3D bitangent = ai_mesh->mAnimMeshes[i]->mBitangents[tri_index];
- const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
- float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
- Color plane_tangent = Color(tangent.x, tangent.y, tangent.z, d);
- w[index] = plane_tangent;
- }
-
- struct AssetImportFbx {
- enum ETimeMode {
- TIME_MODE_DEFAULT = 0,
- TIME_MODE_120 = 1,
- TIME_MODE_100 = 2,
- TIME_MODE_60 = 3,
- TIME_MODE_50 = 4,
- TIME_MODE_48 = 5,
- TIME_MODE_30 = 6,
- TIME_MODE_30_DROP = 7,
- TIME_MODE_NTSC_DROP_FRAME = 8,
- TIME_MODE_NTSC_FULL_FRAME = 9,
- TIME_MODE_PAL = 10,
- TIME_MODE_CINEMA = 11,
- TIME_MODE_1000 = 12,
- TIME_MODE_CINEMA_ND = 13,
- TIME_MODE_CUSTOM = 14,
- TIME_MODE_TIME_MODE_COUNT = 15
- };
- enum UpAxis {
- UP_VECTOR_AXIS_X = 1,
- UP_VECTOR_AXIS_Y = 2,
- UP_VECTOR_AXIS_Z = 3
- };
- enum FrontAxis {
- FRONT_PARITY_EVEN = 1,
- FRONT_PARITY_ODD = 2,
- };
-
- enum CoordAxis {
- COORD_RIGHT = 0,
- COORD_LEFT = 1
- };
- };
-
- /** Get assimp string
- * automatically filters the string data
- */
- static String get_assimp_string(const aiString &p_string) {
- //convert an assimp String to a Godot String
- String name;
- name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
- if (name.find(":") != -1) {
- String replaced_name = name.split(":")[1];
- print_verbose("Replacing " + name + " containing : with " + replaced_name);
- name = replaced_name;
- }
-
- return name;
- }
-
- static String get_anim_string_from_assimp(const aiString &p_string) {
-
- String name;
- name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
- if (name.find(":") != -1) {
- String replaced_name = name.split(":")[1];
- print_verbose("Replacing " + name + " containing : with " + replaced_name);
- name = replaced_name;
- }
- return name;
- }
-
- /**
- * No filter logic get_raw_string_from_assimp
- * This just convers the aiString to a parsed utf8 string
- * Without removing special chars etc
- */
- static String get_raw_string_from_assimp(const aiString &p_string) {
- String name;
- name.parse_utf8(p_string.C_Str() /*,p_string.length*/);
- return name;
- }
-
- static Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
- return Ref<Animation>();
- }
-
- /**
- * Converts aiMatrix4x4 to godot Transform
- */
- static const Transform assimp_matrix_transform(const aiMatrix4x4 p_matrix) {
- aiMatrix4x4 matrix = p_matrix;
- Transform xform;
- xform.set(matrix.a1, matrix.a2, matrix.a3, matrix.b1, matrix.b2, matrix.b3, matrix.c1, matrix.c2, matrix.c3, matrix.a4, matrix.b4, matrix.c4);
- return xform;
- }
-
- /** Get fbx fps for time mode meta data
- */
- static float get_fbx_fps(int32_t time_mode, const aiScene *p_scene) {
- switch (time_mode) {
- case AssetImportFbx::TIME_MODE_DEFAULT: return 24; //hack
- case AssetImportFbx::TIME_MODE_120: return 120;
- case AssetImportFbx::TIME_MODE_100: return 100;
- case AssetImportFbx::TIME_MODE_60: return 60;
- case AssetImportFbx::TIME_MODE_50: return 50;
- case AssetImportFbx::TIME_MODE_48: return 48;
- case AssetImportFbx::TIME_MODE_30: return 30;
- case AssetImportFbx::TIME_MODE_30_DROP: return 30;
- case AssetImportFbx::TIME_MODE_NTSC_DROP_FRAME: return 29.9700262f;
- case AssetImportFbx::TIME_MODE_NTSC_FULL_FRAME: return 29.9700262f;
- case AssetImportFbx::TIME_MODE_PAL: return 25;
- case AssetImportFbx::TIME_MODE_CINEMA: return 24;
- case AssetImportFbx::TIME_MODE_1000: return 1000;
- case AssetImportFbx::TIME_MODE_CINEMA_ND: return 23.976f;
- case AssetImportFbx::TIME_MODE_CUSTOM:
- int32_t frame_rate = -1;
- p_scene->mMetaData->Get("FrameRate", frame_rate);
- return frame_rate;
- }
- return 0;
- }
-
- /**
- * Get global transform for the current node - so we can use world space rather than
- * local space coordinates
- * useful if you need global - although recommend using local wherever possible over global
- * as you could break fbx scaling :)
- */
- static Transform _get_global_assimp_node_transform(const aiNode *p_current_node) {
- aiNode const *current_node = p_current_node;
- Transform xform;
- while (current_node != nullptr) {
- xform = assimp_matrix_transform(current_node->mTransformation) * xform;
- current_node = current_node->mParent;
- }
- return xform;
- }
-
- /**
- * Find hardcoded textures from assimp which could be in many different directories
- */
- static void find_texture_path(const String &p_path, _Directory &dir, String &path, bool &found, String extension) {
- Vector<String> paths;
- paths.push_back(path.get_basename() + extension);
- paths.push_back(path + extension);
- paths.push_back(path);
- paths.push_back(p_path.get_base_dir().plus_file(path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file(path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file(path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("textures/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("Textures/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../Textures/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../textures/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("texture/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("Texture/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../Texture/" + path.get_file()));
- paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file().get_basename() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file() + extension));
- paths.push_back(p_path.get_base_dir().plus_file("../texture/" + path.get_file()));
- for (int i = 0; i < paths.size(); i++) {
- if (dir.file_exists(paths[i])) {
- found = true;
- path = paths[i];
- return;
- }
- }
- }
-
- /** find the texture path for the supplied fbx path inside godot
- * very simple lookup for subfolders etc for a texture which may or may not be in a directory
- */
- static void find_texture_path(const String &r_p_path, String &r_path, bool &r_found) {
- _Directory dir;
-
- List<String> exts;
- ImageLoader::get_recognized_extensions(&exts);
-
- Vector<String> split_path = r_path.get_basename().split("*");
- if (split_path.size() == 2) {
- r_found = true;
- return;
- }
-
- if (dir.file_exists(r_p_path.get_base_dir() + r_path.get_file())) {
- r_path = r_p_path.get_base_dir() + r_path.get_file();
- r_found = true;
- return;
- }
-
- for (int32_t i = 0; i < exts.size(); i++) {
- if (r_found) {
- return;
- }
- find_texture_path(r_p_path, dir, r_path, r_found, "." + exts[i]);
- }
- }
-
- /**
- * set_texture_mapping_mode
- * Helper to check the mapping mode of the texture (repeat, clamp and mirror)
- */
- static void set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<ImageTexture> texture) {
- ERR_FAIL_COND(texture.is_null());
- ERR_FAIL_COND(map_mode == nullptr);
- // FIXME: Commented out during Vulkan port.
- /*
- aiTextureMapMode tex_mode = map_mode[0];
-
- int32_t flags = Texture2D::FLAGS_DEFAULT;
- if (tex_mode == aiTextureMapMode_Wrap) {
- //Default
- } else if (tex_mode == aiTextureMapMode_Clamp) {
- flags = flags & ~Texture2D::FLAG_REPEAT;
- } else if (tex_mode == aiTextureMapMode_Mirror) {
- flags = flags | Texture2D::FLAG_MIRRORED_REPEAT;
- }
- texture->set_flags(flags);
- */
- }
-
- /**
- * Load or load from cache image :)
- */
- static Ref<Image> load_image(ImportState &state, const aiScene *p_scene, String p_path) {
-
- Map<String, Ref<Image>>::Element *match = state.path_to_image_cache.find(p_path);
-
- // if our cache contains this image then don't bother
- if (match) {
- return match->get();
- }
-
- Vector<String> split_path = p_path.get_basename().split("*");
- if (split_path.size() == 2) {
- size_t texture_idx = split_path[1].to_int();
- ERR_FAIL_COND_V(texture_idx >= p_scene->mNumTextures, Ref<Image>());
- aiTexture *tex = p_scene->mTextures[texture_idx];
- String filename = AssimpUtils::get_raw_string_from_assimp(tex->mFilename);
- filename = filename.get_file();
- print_verbose("Open Asset Import: Loading embedded texture " + filename);
- if (tex->mHeight == 0) {
- if (tex->CheckFormat("png")) {
- ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, Ref<Image>());
- Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
- ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
- state.path_to_image_cache.insert(p_path, img);
- return img;
- } else if (tex->CheckFormat("jpg")) {
- ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, Ref<Image>());
- Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
- ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
- state.path_to_image_cache.insert(p_path, img);
- return img;
- } else if (tex->CheckFormat("dds")) {
- ERR_FAIL_COND_V_MSG(true, Ref<Image>(), "Open Asset Import: Embedded dds not implemented");
- }
- } else {
- Ref<Image> img;
- img.instance();
- PackedByteArray arr;
- uint32_t size = tex->mWidth * tex->mHeight;
- arr.resize(size);
- memcpy(arr.ptrw(), tex->pcData, size);
- ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Image>());
- //ARGB8888 to RGBA8888
- for (int32_t i = 0; i < arr.size() / 4; i++) {
- arr.ptrw()[(4 * i) + 3] = arr[(4 * i) + 0];
- arr.ptrw()[(4 * i) + 0] = arr[(4 * i) + 1];
- arr.ptrw()[(4 * i) + 1] = arr[(4 * i) + 2];
- arr.ptrw()[(4 * i) + 2] = arr[(4 * i) + 3];
- }
- img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr);
- ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
- state.path_to_image_cache.insert(p_path, img);
- return img;
- }
- return Ref<Image>();
- } else {
- Ref<Texture2D> texture = ResourceLoader::load(p_path);
- ERR_FAIL_COND_V(texture.is_null(), Ref<Image>());
- Ref<Image> image = texture->get_data();
- ERR_FAIL_COND_V(image.is_null(), Ref<Image>());
- state.path_to_image_cache.insert(p_path, image);
- return image;
- }
-
- return Ref<Image>();
- }
-
- /* create texture from assimp data, if found in path */
- static bool CreateAssimpTexture(
- AssimpImporter::ImportState &state,
- aiString texture_path,
- String &filename,
- String &path,
- AssimpImageData &image_state) {
- filename = get_raw_string_from_assimp(texture_path);
- path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
- bool found = false;
- find_texture_path(state.path, path, found);
- if (found) {
- image_state.raw_image = AssimpUtils::load_image(state, state.assimp_scene, path);
- if (image_state.raw_image.is_valid()) {
- image_state.texture.instance();
- image_state.texture->create_from_image(image_state.raw_image);
- // FIXME: Commented out during Vulkan port.
- //image_state.texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
- return true;
- }
- }
-
- return false;
- }
- /** GetAssimpTexture
- * Designed to retrieve textures for you
- */
- static bool GetAssimpTexture(
- AssimpImporter::ImportState &state,
- aiMaterial *ai_material,
- aiTextureType texture_type,
- String &filename,
- String &path,
- AssimpImageData &image_state) {
- aiString ai_filename = aiString();
- if (AI_SUCCESS == ai_material->GetTexture(texture_type, 0, &ai_filename, nullptr, nullptr, nullptr, nullptr, image_state.map_mode)) {
- return CreateAssimpTexture(state, ai_filename, filename, path, image_state);
- }
-
- return false;
- }
-};
-
-#endif // IMPORT_UTILS_IMPORTER_ASSIMP_H
diff --git a/modules/basis_universal/SCsub b/modules/basis_universal/SCsub
index dc7b176d24..351628a0e3 100644
--- a/modules/basis_universal/SCsub
+++ b/modules/basis_universal/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_basisu = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
# Not unbundled so far since not widespread as shared library
thirdparty_dir = "#thirdparty/basis_universal/"
tool_sources = [
@@ -41,8 +44,16 @@ if env["target"] == "debug":
env_thirdparty = env_basisu.Clone()
env_thirdparty.disable_warnings()
if env["tools"]:
- env_thirdparty.add_source_files(env.modules_sources, tool_sources)
-env_thirdparty.add_source_files(env.modules_sources, transcoder_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, tool_sources)
+env_thirdparty.add_source_files(thirdparty_obj, transcoder_sources)
+env.modules_sources += thirdparty_obj
# Godot source files
-env_basisu.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_basisu.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp
index f31c889a6d..cf5581265b 100644
--- a/modules/basis_universal/register_types.cpp
+++ b/modules/basis_universal/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -54,7 +54,6 @@ basist::etc1_global_selector_codebook *sel_codebook = nullptr;
#ifdef TOOLS_ENABLED
static Vector<uint8_t> basis_universal_packer(const Ref<Image> &p_image, Image::UsedChannels p_channels) {
-
Vector<uint8_t> budata;
{
@@ -163,7 +162,6 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
switch (*(uint32_t *)(ptr)) {
case BASIS_DECOMPRESS_RG: {
-
if (RS::get_singleton()->has_os_feature("rgtc")) {
format = basist::transcoder_texture_format::cTFBC5; // get this from renderer
imgfmt = Image::FORMAT_RGTC_RG;
@@ -186,7 +184,6 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
format = basist::transcoder_texture_format::cTFBC1; // get this from renderer
imgfmt = Image::FORMAT_DXT1;
} else if (RS::get_singleton()->has_os_feature("etc")) {
-
format = basist::transcoder_texture_format::cTFETC1; // get this from renderer
imgfmt = Image::FORMAT_ETC;
} else {
@@ -219,7 +216,7 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
format = basist::transcoder_texture_format::cTFETC2; // get this from renderer
imgfmt = Image::FORMAT_ETC2_RGBA8;
} else {
- //gles2 most likely, bad for normalmaps, nothing to do about this.
+ //gles2 most likely, bad for normal maps, nothing to do about this.
format = basist::transcoder_texture_format::cTFRGBA32;
imgfmt = Image::FORMAT_RGBA8;
}
@@ -243,13 +240,13 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) {
{
uint8_t *w = gpudata.ptrw();
uint8_t *dst = w;
- for (int i = 0; i < gpudata.size(); i++)
+ for (int i = 0; i < gpudata.size(); i++) {
dst[i] = 0x00;
+ }
int ofs = 0;
tr.start_transcoding(ptr, size);
for (uint32_t i = 0; i < info.m_total_levels; i++) {
-
basist::basisu_image_level_info level;
tr.get_image_level_info(ptr, size, level, 0, i);
@@ -279,7 +276,6 @@ void register_basis_universal_types() {
}
void unregister_basis_universal_types() {
-
#ifdef TOOLS_ENABLED
delete sel_codebook;
Image::basis_universal_packer = nullptr;
diff --git a/modules/basis_universal/register_types.h b/modules/basis_universal/register_types.h
index 5053dc27ce..30b465e344 100644
--- a/modules/basis_universal/register_types.h
+++ b/modules/basis_universal/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/basis_universal/texture_basisu.cpp b/modules/basis_universal/texture_basisu.cpp
index 2ed0340927..66eb81d7f2 100644
--- a/modules/basis_universal/texture_basisu.cpp
+++ b/modules/basis_universal/texture_basisu.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -39,44 +39,36 @@
#include <transcoder/basisu_transcoder.h>
void TextureBasisU::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_basisu_data", "data"), &TextureBasisU::set_basisu_data);
ClassDB::bind_method(D_METHOD("get_basisu_data"), &TextureBasisU::get_data);
ClassDB::bind_method(D_METHOD("import"), &TextureBasisU::import);
ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "basisu_data"), "set_basisu_data", "get_basisu_data");
-
};
int TextureBasisU::get_width() const {
-
return tex_size.x;
};
int TextureBasisU::get_height() const {
-
return tex_size.y;
};
RID TextureBasisU::get_rid() const {
-
return texture;
};
bool TextureBasisU::has_alpha() const {
-
return false;
};
void TextureBasisU::set_flags(uint32_t p_flags) {
-
flags = p_flags;
RenderingServer::get_singleton()->texture_set_flags(texture, p_flags);
};
uint32_t TextureBasisU::get_flags() const {
-
return flags;
};
@@ -95,12 +87,10 @@ void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) {
Image::Format imgfmt;
if (OS::get_singleton()->has_feature("s3tc")) {
-
format = basist::cTFBC3; // get this from renderer
imgfmt = Image::FORMAT_DXT5;
} else if (OS::get_singleton()->has_feature("etc2")) {
-
format = basist::cTFETC2;
imgfmt = Image::FORMAT_ETC2_RGBA8;
};
@@ -126,7 +116,6 @@ void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) {
int ofs = 0;
tr.start_transcoding(ptr, size);
for (int i=0; i<info.m_total_levels; i++) {
-
basist::basisu_image_level_info level;
tr.get_image_level_info(ptr, size, level, 0, i);
@@ -214,19 +203,16 @@ Error TextureBasisU::import(const Ref<Image>& p_img) {
Vector<uint8_t> TextureBasisU::get_basisu_data() const {
-
return data;
};
TextureBasisU::TextureBasisU() {
-
flags = FLAGS_DEFAULT;
texture = RenderingServer::get_singleton()->texture_create();
};
TextureBasisU::~TextureBasisU() {
-
RenderingServer::get_singleton()->free(texture);
};
diff --git a/modules/basis_universal/texture_basisu.h b/modules/basis_universal/texture_basisu.h
index 8de151ede0..0a4783eaff 100644
--- a/modules/basis_universal/texture_basisu.h
+++ b/modules/basis_universal/texture_basisu.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,6 +28,9 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef BASIS_UNIVERSAL_TEXTURE_BASISU_H
+#define BASIS_UNIVERSAL_TEXTURE_BASISU_H
+
#include "scene/resources/texture.h"
#ifdef TOOLS_ENABLED
@@ -38,7 +41,6 @@
#if 0
class TextureBasisU : public Texture {
-
GDCLASS(TextureBasisU, Texture);
RES_BASE_EXTENSION("butex");
@@ -71,7 +73,8 @@ public:
TextureBasisU();
~TextureBasisU();
-
};
#endif
+
+#endif // BASIS_UNIVERSAL_TEXTURE_BASISU_H
diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp
index ea2b2b548f..c7fdf56af4 100644
--- a/modules/bmp/image_loader_bmp.cpp
+++ b/modules/bmp/image_loader_bmp.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,16 +30,18 @@
#include "image_loader_bmp.h"
+#include "core/io/file_access_memory.h"
+
Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
const uint8_t *p_buffer,
const uint8_t *p_color_buffer,
const uint32_t color_table_size,
const bmp_header_s &p_header) {
-
Error err = OK;
- if (p_buffer == nullptr)
+ if (p_buffer == nullptr) {
err = FAILED;
+ }
if (err == OK) {
size_t index = 0;
@@ -51,17 +53,20 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
if (bits_per_pixel == 1) {
// Requires bit unpacking...
- ERR_FAIL_COND_V(width % 8 != 0, ERR_UNAVAILABLE);
- ERR_FAIL_COND_V(height % 8 != 0, ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V_MSG(width % 8 != 0, ERR_UNAVAILABLE,
+ vformat("1-bpp BMP images must have a width that is a multiple of 8, but the imported BMP is %d pixels wide.", int(width)));
+ ERR_FAIL_COND_V_MSG(height % 8 != 0, ERR_UNAVAILABLE,
+ vformat("1-bpp BMP images must have a height that is a multiple of 8, but the imported BMP is %d pixels tall.", int(height)));
} else if (bits_per_pixel == 4) {
// Requires bit unpacking...
- ERR_FAIL_COND_V(width % 2 != 0, ERR_UNAVAILABLE);
- ERR_FAIL_COND_V(height % 2 != 0, ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V_MSG(width % 2 != 0, ERR_UNAVAILABLE,
+ vformat("4-bpp BMP images must have a width that is a multiple of 2, but the imported BMP is %d pixels wide.", int(width)));
+ ERR_FAIL_COND_V_MSG(height % 2 != 0, ERR_UNAVAILABLE,
+ vformat("4-bpp BMP images must have a height that is a multiple of 2, but the imported BMP is %d pixels tall.", int(height)));
} else if (bits_per_pixel == 16) {
-
- ERR_FAIL_V(ERR_UNAVAILABLE);
+ ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "16-bpp BMP images are not supported.");
}
// Image data (might be indexed)
@@ -73,7 +78,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
} else { // color
data_len = width * height * 4;
}
- ERR_FAIL_COND_V(data_len == 0, ERR_BUG);
+ ERR_FAIL_COND_V_MSG(data_len == 0, ERR_BUG, "Couldn't parse the BMP image data.");
err = data.resize(data_len);
uint8_t *data_w = data.ptrw();
@@ -153,7 +158,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
if (p_color_buffer == nullptr || color_table_size == 0) { // regular pixels
- p_image->create(width, height, 0, Image::FORMAT_RGBA8, data);
+ p_image->create(width, height, false, Image::FORMAT_RGBA8, data);
} else { // data is in indexed format, extend it
@@ -193,7 +198,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
dest += 4;
}
- p_image->create(width, height, 0, Image::FORMAT_RGBA8, extended_data);
+ p_image->create(width, height, false, Image::FORMAT_RGBA8, extended_data);
}
}
return err;
@@ -201,7 +206,6 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
bool p_force_linear, float p_scale) {
-
bmp_header_s bmp_header;
Error err = ERR_INVALID_DATA;
@@ -217,13 +221,15 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
// Info Header
bmp_header.bmp_info_header.bmp_header_size = f->get_32();
- ERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V_MSG(bmp_header.bmp_info_header.bmp_header_size < BITMAP_INFO_HEADER_MIN_SIZE, ERR_FILE_CORRUPT,
+ vformat("Couldn't parse the BMP info header. The file is likely corrupt: %s", f->get_path()));
bmp_header.bmp_info_header.bmp_width = f->get_32();
bmp_header.bmp_info_header.bmp_height = f->get_32();
bmp_header.bmp_info_header.bmp_planes = f->get_16();
- ERR_FAIL_COND_V(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V_MSG(bmp_header.bmp_info_header.bmp_planes != 1, ERR_FILE_CORRUPT,
+ vformat("Couldn't parse the BMP planes. The file is likely corrupt: %s", f->get_path()));
bmp_header.bmp_info_header.bmp_bit_count = f->get_16();
bmp_header.bmp_info_header.bmp_compression = f->get_32();
@@ -238,10 +244,10 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
case BI_RLE4:
case BI_CMYKRLE8:
case BI_CMYKRLE4: {
- // Stop parsing
- String bmp_path = f->get_path();
+ // Stop parsing.
f->close();
- ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Compressed BMP files are not supported: " + bmp_path + ".");
+ ERR_FAIL_V_MSG(ERR_UNAVAILABLE,
+ vformat("Compressed BMP files are not supported: %s", f->get_path()));
} break;
}
// Don't rely on sizeof(bmp_file_header) as structure padding
@@ -257,7 +263,8 @@ 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_MSG(color_table_size == 0, ERR_BUG,
+ vformat("Couldn't parse the BMP color table: %s", f->get_path()));
}
Vector<uint8_t> bmp_color_table;
@@ -288,10 +295,21 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
return err;
}
-void ImageLoaderBMP::get_recognized_extensions(
- List<String> *p_extensions) const {
-
+void ImageLoaderBMP::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("bmp");
}
-ImageLoaderBMP::ImageLoaderBMP() {}
+static Ref<Image> _bmp_mem_loader_func(const uint8_t *p_bmp, int p_size) {
+ FileAccessMemory memfile;
+ Error open_memfile_error = memfile.open_custom(p_bmp, p_size);
+ ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for BMP image buffer.");
+ Ref<Image> img;
+ img.instance();
+ Error load_error = ImageLoaderBMP().load_image(img, &memfile, false, 1.0f);
+ ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load BMP image.");
+ return img;
+}
+
+ImageLoaderBMP::ImageLoaderBMP() {
+ Image::_bmp_mem_loader_func = _bmp_mem_loader_func;
+}
diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h
index 3f10a1c598..d3f12f0115 100644
--- a/modules/bmp/image_loader_bmp.h
+++ b/modules/bmp/image_loader_bmp.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bmp/register_types.cpp b/modules/bmp/register_types.cpp
index 6220e956d6..d36ce9cdaf 100644
--- a/modules/bmp/register_types.cpp
+++ b/modules/bmp/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bmp/register_types.h b/modules/bmp/register_types.h
index e7561dc32d..3ce81eba1b 100644
--- a/modules/bmp/register_types.h
+++ b/modules/bmp/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub
index b853ebfc63..bfac0df5b0 100644
--- a/modules/bullet/SCsub
+++ b/modules/bullet/SCsub
@@ -7,6 +7,8 @@ env_bullet = env_modules.Clone()
# Thirdparty source files
+thirdparty_obj = []
+
if env["builtin_bullet"]:
# Build only version 2 for now (as of 2.89)
# Sync file list with relevant upstream CMakeLists.txt for each folder.
@@ -201,15 +203,23 @@ if env["builtin_bullet"]:
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(CPPDEFINES=['BT_DEBUG'])
+ if env["target"] == "debug" or env["target"] == "release_debug":
+ env_bullet.Append(CPPDEFINES=["DEBUG"])
env_bullet.Append(CPPDEFINES=["BT_USE_OLD_DAMPING_METHOD"])
env_thirdparty = env_bullet.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
# Godot source files
-env_bullet.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_bullet.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/bullet/area_bullet.cpp b/modules/bullet/area_bullet.cpp
index 4d727529ef..c3bd84c329 100644
--- a/modules/bullet/area_bullet.cpp
+++ b/modules/bullet/area_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -44,19 +44,7 @@
*/
AreaBullet::AreaBullet() :
- RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA),
- monitorable(true),
- spOv_mode(PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED),
- spOv_gravityPoint(false),
- spOv_gravityPointDistanceScale(0),
- spOv_gravityPointAttenuation(1),
- spOv_gravityVec(0, -1, 0),
- spOv_gravityMag(10),
- spOv_linearDump(0.1),
- spOv_angularDump(1),
- spOv_priority(0),
- isScratched(false) {
-
+ RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) {
btGhost = bulletnew(btGhostObject);
reload_shapes();
setupBulletCollisionObject(btGhost);
@@ -64,19 +52,22 @@ AreaBullet::AreaBullet() :
/// In order to use collision objects as trigger, you have to disable the collision response.
set_collision_enabled(false);
- for (int i = 0; i < 5; ++i)
+ for (int i = 0; i < 5; ++i) {
call_event_res_ptr[i] = &call_event_res[i];
+ }
}
AreaBullet::~AreaBullet() {
// signal are handled by godot, so just clear without notify
- for (int i = overlappingObjects.size() - 1; 0 <= i; --i)
+ for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
overlappingObjects[i].object->on_exit_area(this);
+ }
}
void AreaBullet::dispatch_callbacks() {
- if (!isScratched)
+ if (!isScratched) {
return;
+ }
isScratched = false;
// Reverse order because I've to remove EXIT objects
@@ -102,7 +93,6 @@ void AreaBullet::dispatch_callbacks() {
}
void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) {
-
InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())];
Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id);
@@ -122,15 +112,17 @@ void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3
}
void AreaBullet::scratch() {
- if (isScratched)
+ if (isScratched) {
return;
+ }
isScratched = true;
}
void AreaBullet::clear_overlaps(bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
- if (p_notify)
+ if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
+ }
overlappingObjects[i].object->on_exit_area(this);
}
overlappingObjects.clear();
@@ -139,8 +131,9 @@ void AreaBullet::clear_overlaps(bool p_notify) {
void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
if (overlappingObjects[i].object == p_object) {
- if (p_notify)
+ if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
+ }
overlappingObjects[i].object->on_exit_area(this);
overlappingObjects.remove(i);
break;
@@ -181,6 +174,7 @@ void AreaBullet::reload_body() {
void AreaBullet::set_space(SpaceBullet *p_space) {
// Clear the old space if there is one
if (space) {
+ clear_overlaps(false);
isScratched = false;
// Remove this object form the physics world
diff --git a/modules/bullet/area_bullet.h b/modules/bullet/area_bullet.h
index 0272350510..a5fa678fec 100644
--- a/modules/bullet/area_bullet.h
+++ b/modules/bullet/area_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define AREABULLET_H
#include "collision_object_bullet.h"
-#include "core/vector.h"
+#include "core/templates/vector.h"
#include "servers/physics_server_3d.h"
#include "space_bullet.h"
@@ -61,12 +61,10 @@ public:
};
struct OverlappingObjectData {
- CollisionObjectBullet *object;
- OverlapState state;
+ CollisionObjectBullet *object = nullptr;
+ OverlapState state = OVERLAP_STATE_ENTER;
- OverlappingObjectData() :
- object(nullptr),
- state(OVERLAP_STATE_ENTER) {}
+ OverlappingObjectData() {}
OverlappingObjectData(CollisionObjectBullet *p_object, OverlapState p_state) :
object(p_object),
state(p_state) {}
@@ -86,19 +84,19 @@ private:
btGhostObject *btGhost;
Vector<OverlappingObjectData> overlappingObjects;
- bool monitorable;
-
- PhysicsServer3D::AreaSpaceOverrideMode spOv_mode;
- bool spOv_gravityPoint;
- real_t spOv_gravityPointDistanceScale;
- real_t spOv_gravityPointAttenuation;
- Vector3 spOv_gravityVec;
- real_t spOv_gravityMag;
- real_t spOv_linearDump;
- real_t spOv_angularDump;
- int spOv_priority;
-
- bool isScratched;
+ bool monitorable = true;
+
+ PhysicsServer3D::AreaSpaceOverrideMode spOv_mode = PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED;
+ bool spOv_gravityPoint = false;
+ real_t spOv_gravityPointDistanceScale = 0;
+ real_t spOv_gravityPointAttenuation = 1;
+ Vector3 spOv_gravityVec = Vector3(0, -1, 0);
+ real_t spOv_gravityMag = 10;
+ real_t spOv_linearDump = 0.1;
+ real_t spOv_angularDump = 0.1;
+ int spOv_priority = 0;
+
+ bool isScratched = false;
InOutEventCallback eventsCallbacks[2];
diff --git a/modules/bullet/btRayShape.cpp b/modules/bullet/btRayShape.cpp
index 0f54f848dc..1568cca63d 100644
--- a/modules/bullet/btRayShape.cpp
+++ b/modules/bullet/btRayShape.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -50,7 +50,6 @@ btRayShape::~btRayShape() {
}
void btRayShape::setLength(btScalar p_length) {
-
m_length = p_length;
reload_cache();
}
@@ -61,7 +60,6 @@ void btRayShape::setMargin(btScalar margin) {
}
void btRayShape::setSlipsOnSlope(bool p_slipsOnSlope) {
-
slipsOnSlope = p_slipsOnSlope;
}
@@ -70,10 +68,11 @@ btVector3 btRayShape::localGetSupportingVertex(const btVector3 &vec) const {
}
btVector3 btRayShape::localGetSupportingVertexWithoutMargin(const btVector3 &vec) const {
- if (vec.z() > 0)
+ if (vec.z() > 0) {
return m_shapeAxis * m_cacheScaledLength;
- else
+ } else {
return btVector3(0, 0, 0);
+ }
}
void btRayShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3 *vectors, btVector3 *supportVerticesOut, int numVectors) const {
@@ -101,7 +100,6 @@ void btRayShape::getPreferredPenetrationDirection(int index, btVector3 &penetrat
}
void btRayShape::reload_cache() {
-
m_cacheScaledLength = m_length * m_localScaling[2];
m_cacheSupportPoint.setIdentity();
diff --git a/modules/bullet/btRayShape.h b/modules/bullet/btRayShape.h
index df6dd93d57..dcc4cc79c7 100644
--- a/modules/bullet/btRayShape.h
+++ b/modules/bullet/btRayShape.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
/// Ray shape around z axis
ATTRIBUTE_ALIGNED16(class)
btRayShape : public btConvexInternalShape {
-
btScalar m_length;
bool slipsOnSlope;
/// The default axis is the z
diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp
index 2705c749a2..632682a15d 100644
--- a/modules/bullet/bullet_physics_server.cpp
+++ b/modules/bullet/bullet_physics_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,9 +32,9 @@
#include "bullet_utilities.h"
#include "cone_twist_joint_bullet.h"
-#include "core/class_db.h"
-#include "core/error_macros.h"
-#include "core/ustring.h"
+#include "core/error/error_macros.h"
+#include "core/object/class_db.h"
+#include "core/string/ustring.h"
#include "generic_6dof_joint_bullet.h"
#include "hinge_joint_bullet.h"
#include "pin_joint_bullet.h"
@@ -79,9 +79,7 @@ void BulletPhysicsServer3D::_bind_methods() {
}
BulletPhysicsServer3D::BulletPhysicsServer3D() :
- PhysicsServer3D(),
- active(true),
- active_spaces_count(0) {}
+ PhysicsServer3D() {}
BulletPhysicsServer3D::~BulletPhysicsServer3D() {}
@@ -90,35 +88,27 @@ RID BulletPhysicsServer3D::shape_create(ShapeType p_shape) {
switch (p_shape) {
case SHAPE_PLANE: {
-
shape = bulletnew(PlaneShapeBullet);
} break;
case SHAPE_SPHERE: {
-
shape = bulletnew(SphereShapeBullet);
} break;
case SHAPE_BOX: {
-
shape = bulletnew(BoxShapeBullet);
} break;
case SHAPE_CAPSULE: {
-
shape = bulletnew(CapsuleShapeBullet);
} break;
case SHAPE_CYLINDER: {
-
shape = bulletnew(CylinderShapeBullet);
} break;
case SHAPE_CONVEX_POLYGON: {
-
shape = bulletnew(ConvexPolygonShapeBullet);
} break;
case SHAPE_CONCAVE_POLYGON: {
-
shape = bulletnew(ConcavePolygonShapeBullet);
} break;
case SHAPE_HEIGHTMAP: {
-
shape = bulletnew(HeightMapShapeBullet);
} break;
case SHAPE_RAY: {
@@ -178,7 +168,6 @@ RID BulletPhysicsServer3D::space_create() {
}
void BulletPhysicsServer3D::space_set_active(RID p_space, bool p_active) {
-
SpaceBullet *space = space_owner.getornull(p_space);
ERR_FAIL_COND(!space);
@@ -337,8 +326,9 @@ void BulletPhysicsServer3D::area_clear_shapes(RID p_area) {
AreaBullet *area = area_owner.getornull(p_area);
ERR_FAIL_COND(!area);
- for (int i = area->get_shape_count(); 0 < i; --i)
+ for (int i = area->get_shape_count(); 0 < i; --i) {
area->remove_shape_full(0);
+ }
}
void BulletPhysicsServer3D::area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) {
@@ -373,7 +363,6 @@ void BulletPhysicsServer3D::area_set_param(RID p_area, AreaParameter p_param, co
space->set_param(p_param, p_value);
}
} else {
-
AreaBullet *area = area_owner.getornull(p_area);
ERR_FAIL_COND(!area);
@@ -455,8 +444,9 @@ RID BulletPhysicsServer3D::body_create(BodyMode p_mode, bool p_init_sleeping) {
body->set_mode(p_mode);
body->set_collision_layer(1);
body->set_collision_mask(1);
- if (p_init_sleeping)
+ if (p_init_sleeping) {
body->set_state(BODY_STATE_SLEEPING, p_init_sleeping);
+ }
CreateThenReturnRID(rigid_body_owner, body);
}
@@ -470,8 +460,9 @@ void BulletPhysicsServer3D::body_set_space(RID p_body, RID p_space) {
ERR_FAIL_COND(!space);
}
- if (body->get_space() == space)
+ if (body->get_space() == space) {
return; //pointles
+ }
body->set_space(space);
}
@@ -481,8 +472,9 @@ RID BulletPhysicsServer3D::body_get_space(RID p_body) const {
ERR_FAIL_COND_V(!body, RID());
SpaceBullet *space = body->get_space();
- if (!space)
+ if (!space) {
return RID();
+ }
return space->get_self();
}
@@ -499,7 +491,6 @@ PhysicsServer3D::BodyMode BulletPhysicsServer3D::body_get_mode(RID p_body) const
}
void BulletPhysicsServer3D::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform, bool p_disabled) {
-
RigidBodyBullet *body = rigid_body_owner.getornull(p_body);
ERR_FAIL_COND(!body);
@@ -570,14 +561,14 @@ void BulletPhysicsServer3D::body_clear_shapes(RID p_body) {
}
void BulletPhysicsServer3D::body_attach_object_instance_id(RID p_body, ObjectID p_id) {
- CollisionObjectBullet *body = get_collisin_object(p_body);
+ CollisionObjectBullet *body = get_collision_object(p_body);
ERR_FAIL_COND(!body);
body->set_instance_id(p_id);
}
ObjectID BulletPhysicsServer3D::body_get_object_instance_id(RID p_body) const {
- CollisionObjectBullet *body = get_collisin_object(p_body);
+ CollisionObjectBullet *body = get_collision_object(p_body);
ERR_FAIL_COND_V(!body, ObjectID());
return body->get_instance_id();
@@ -653,7 +644,6 @@ void BulletPhysicsServer3D::body_set_kinematic_safe_margin(RID p_body, real_t p_
ERR_FAIL_COND(!body);
if (body->get_kinematic_utilities()) {
-
body->get_kinematic_utilities()->setSafeMargin(p_margin);
}
}
@@ -663,7 +653,6 @@ real_t BulletPhysicsServer3D::body_get_kinematic_safe_margin(RID p_body) const {
ERR_FAIL_COND_V(!body, 0);
if (body->get_kinematic_utilities()) {
-
return body->get_kinematic_utilities()->safe_margin;
}
@@ -718,11 +707,11 @@ void BulletPhysicsServer3D::body_add_central_force(RID p_body, const Vector3 &p_
body->apply_central_force(p_force);
}
-void BulletPhysicsServer3D::body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_pos) {
+void BulletPhysicsServer3D::body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_position) {
RigidBodyBullet *body = rigid_body_owner.getornull(p_body);
ERR_FAIL_COND(!body);
- body->apply_force(p_force, p_pos);
+ body->apply_force(p_force, p_position);
}
void BulletPhysicsServer3D::body_add_torque(RID p_body, const Vector3 &p_torque) {
@@ -739,11 +728,11 @@ void BulletPhysicsServer3D::body_apply_central_impulse(RID p_body, const Vector3
body->apply_central_impulse(p_impulse);
}
-void BulletPhysicsServer3D::body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse) {
+void BulletPhysicsServer3D::body_apply_impulse(RID p_body, const Vector3 &p_impulse, const Vector3 &p_position) {
RigidBodyBullet *body = rigid_body_owner.getornull(p_body);
ERR_FAIL_COND(!body);
- body->apply_impulse(p_pos, p_impulse);
+ body->apply_impulse(p_impulse, p_position);
}
void BulletPhysicsServer3D::body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) {
@@ -885,8 +874,9 @@ RID BulletPhysicsServer3D::soft_body_create(bool p_init_sleeping) {
SoftBodyBullet *body = bulletnew(SoftBodyBullet);
body->set_collision_layer(1);
body->set_collision_mask(1);
- if (p_init_sleeping)
+ if (p_init_sleeping) {
body->set_activation_state(false);
+ }
CreateThenReturnRID(soft_body_owner, body);
}
@@ -907,8 +897,9 @@ void BulletPhysicsServer3D::soft_body_set_space(RID p_body, RID p_space) {
ERR_FAIL_COND(!space);
}
- if (body->get_space() == space)
+ if (body->get_space() == space) {
return; //pointles
+ }
body->set_space(space);
}
@@ -918,8 +909,9 @@ RID BulletPhysicsServer3D::soft_body_get_space(RID p_body) const {
ERR_FAIL_COND_V(!body, RID());
SpaceBullet *space = body->get_space();
- if (!space)
+ if (!space) {
return RID();
+ }
return space->get_self();
}
@@ -1471,25 +1463,8 @@ bool BulletPhysicsServer3D::generic_6dof_joint_get_flag(RID p_joint, Vector3::Ax
return generic_6dof_joint->get_flag(p_axis, p_flag);
}
-void BulletPhysicsServer3D::generic_6dof_joint_set_precision(RID p_joint, int p_precision) {
- JointBullet *joint = joint_owner.getornull(p_joint);
- ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type() != JOINT_6DOF);
- Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint);
- generic_6dof_joint->set_precision(p_precision);
-}
-
-int BulletPhysicsServer3D::generic_6dof_joint_get_precision(RID p_joint) {
- JointBullet *joint = joint_owner.getornull(p_joint);
- ERR_FAIL_COND_V(!joint, 0);
- ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, 0);
- Generic6DOFJointBullet *generic_6dof_joint = static_cast<Generic6DOFJointBullet *>(joint);
- return generic_6dof_joint->get_precision();
-}
-
void BulletPhysicsServer3D::free(RID p_rid) {
if (shape_owner.owns(p_rid)) {
-
ShapeBullet *shape = shape_owner.getornull(p_rid);
// Notify the shape is configured
@@ -1500,7 +1475,6 @@ void BulletPhysicsServer3D::free(RID p_rid) {
shape_owner.free(p_rid);
bulletdelete(shape);
} else if (rigid_body_owner.owns(p_rid)) {
-
RigidBodyBullet *body = rigid_body_owner.getornull(p_rid);
body->set_space(nullptr);
@@ -1511,7 +1485,6 @@ void BulletPhysicsServer3D::free(RID p_rid) {
bulletdelete(body);
} else if (soft_body_owner.owns(p_rid)) {
-
SoftBodyBullet *body = soft_body_owner.getornull(p_rid);
body->set_space(nullptr);
@@ -1520,7 +1493,6 @@ void BulletPhysicsServer3D::free(RID p_rid) {
bulletdelete(body);
} else if (area_owner.owns(p_rid)) {
-
AreaBullet *area = area_owner.getornull(p_rid);
area->set_space(nullptr);
@@ -1531,14 +1503,12 @@ void BulletPhysicsServer3D::free(RID p_rid) {
bulletdelete(area);
} else if (joint_owner.owns(p_rid)) {
-
JointBullet *joint = joint_owner.getornull(p_rid);
joint->destroy_internal_constraint();
joint_owner.free(p_rid);
bulletdelete(joint);
} else if (space_owner.owns(p_rid)) {
-
SpaceBullet *space = space_owner.getornull(p_rid);
space->remove_all_collision_objects();
@@ -1547,7 +1517,6 @@ void BulletPhysicsServer3D::free(RID p_rid) {
space_owner.free(p_rid);
bulletdelete(space);
} else {
-
ERR_FAIL_MSG("Invalid ID.");
}
}
@@ -1557,21 +1526,25 @@ void BulletPhysicsServer3D::init() {
}
void BulletPhysicsServer3D::step(float p_deltaTime) {
- if (!active)
+ if (!active) {
return;
+ }
BulletPhysicsDirectBodyState3D::singleton_setDeltaTime(p_deltaTime);
for (int i = 0; i < active_spaces_count; ++i) {
-
active_spaces[i]->step(p_deltaTime);
}
}
-void BulletPhysicsServer3D::sync() {
-}
-
void BulletPhysicsServer3D::flush_queries() {
+ if (!active) {
+ return;
+ }
+
+ for (int i = 0; i < active_spaces_count; ++i) {
+ active_spaces[i]->flush_queries();
+ }
}
void BulletPhysicsServer3D::finish() {
@@ -1582,7 +1555,17 @@ int BulletPhysicsServer3D::get_process_info(ProcessInfo p_info) {
return 0;
}
-CollisionObjectBullet *BulletPhysicsServer3D::get_collisin_object(RID p_object) const {
+SpaceBullet *BulletPhysicsServer3D::get_space(RID p_rid) const {
+ ERR_FAIL_COND_V_MSG(space_owner.owns(p_rid) == false, nullptr, "The RID is not valid.");
+ return space_owner.getornull(p_rid);
+}
+
+ShapeBullet *BulletPhysicsServer3D::get_shape(RID p_rid) const {
+ ERR_FAIL_COND_V_MSG(shape_owner.owns(p_rid) == false, nullptr, "The RID is not valid.");
+ return shape_owner.getornull(p_rid);
+}
+
+CollisionObjectBullet *BulletPhysicsServer3D::get_collision_object(RID p_object) const {
if (rigid_body_owner.owns(p_object)) {
return rigid_body_owner.getornull(p_object);
}
@@ -1592,15 +1575,20 @@ CollisionObjectBullet *BulletPhysicsServer3D::get_collisin_object(RID p_object)
if (soft_body_owner.owns(p_object)) {
return soft_body_owner.getornull(p_object);
}
- return nullptr;
+ ERR_FAIL_V_MSG(nullptr, "The RID is no valid.");
}
-RigidCollisionObjectBullet *BulletPhysicsServer3D::get_rigid_collisin_object(RID p_object) const {
+RigidCollisionObjectBullet *BulletPhysicsServer3D::get_rigid_collision_object(RID p_object) const {
if (rigid_body_owner.owns(p_object)) {
return rigid_body_owner.getornull(p_object);
}
if (area_owner.owns(p_object)) {
return area_owner.getornull(p_object);
}
- return nullptr;
+ ERR_FAIL_V_MSG(nullptr, "The RID is no valid.");
+}
+
+JointBullet *BulletPhysicsServer3D::get_joint(RID p_rid) const {
+ ERR_FAIL_COND_V_MSG(joint_owner.owns(p_rid) == false, nullptr, "The RID is not valid.");
+ return joint_owner.getornull(p_rid);
}
diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h
index ea9c5e589e..b5dc84c8f5 100644
--- a/modules/bullet/bullet_physics_server.h
+++ b/modules/bullet/bullet_physics_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,14 +32,15 @@
#define BULLET_PHYSICS_SERVER_H
#include "area_bullet.h"
-#include "core/rid.h"
-#include "core/rid_owner.h"
+#include "core/templates/rid.h"
+#include "core/templates/rid_owner.h"
#include "joint_bullet.h"
#include "rigid_body_bullet.h"
#include "servers/physics_server_3d.h"
#include "shape_bullet.h"
#include "soft_body_bullet.h"
#include "space_bullet.h"
+
/**
@author AndreaCatania
*/
@@ -49,8 +50,8 @@ class BulletPhysicsServer3D : public PhysicsServer3D {
friend class BulletPhysicsDirectSpaceState;
- bool active;
- char active_spaces_count;
+ bool active = true;
+ char active_spaces_count = 0;
Vector<SpaceBullet *> active_spaces;
mutable RID_PtrOwner<SpaceBullet> space_owner;
@@ -87,35 +88,35 @@ public:
}
/* SHAPE API */
- virtual RID shape_create(ShapeType p_shape);
- virtual void shape_set_data(RID p_shape, const Variant &p_data);
- virtual ShapeType shape_get_type(RID p_shape) const;
- virtual Variant shape_get_data(RID p_shape) const;
+ virtual RID shape_create(ShapeType p_shape) override;
+ virtual void shape_set_data(RID p_shape, const Variant &p_data) override;
+ virtual ShapeType shape_get_type(RID p_shape) const override;
+ virtual Variant shape_get_data(RID p_shape) const override;
- virtual void shape_set_margin(RID p_shape, real_t p_margin);
- virtual real_t shape_get_margin(RID p_shape) const;
+ virtual void shape_set_margin(RID p_shape, real_t p_margin) override;
+ virtual real_t shape_get_margin(RID p_shape) const override;
/// Not supported
- virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias);
+ virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) override;
/// Not supported
- virtual real_t shape_get_custom_solver_bias(RID p_shape) const;
+ virtual real_t shape_get_custom_solver_bias(RID p_shape) const override;
/* SPACE API */
- virtual RID space_create();
- virtual void space_set_active(RID p_space, bool p_active);
- virtual bool space_is_active(RID p_space) const;
+ virtual RID space_create() override;
+ virtual void space_set_active(RID p_space, bool p_active) override;
+ virtual bool space_is_active(RID p_space) const override;
/// Not supported
- virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value);
+ virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) override;
/// Not supported
- virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const;
+ virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const override;
- virtual PhysicsDirectSpaceState3D *space_get_direct_state(RID p_space);
+ virtual PhysicsDirectSpaceState3D *space_get_direct_state(RID p_space) override;
- virtual void space_set_debug_contacts(RID p_space, int p_max_contacts);
- virtual Vector<Vector3> space_get_contacts(RID p_space) const;
- virtual int space_get_contact_count(RID p_space) const;
+ virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) override;
+ virtual Vector<Vector3> space_get_contacts(RID p_space) const override;
+ virtual int space_get_contact_count(RID p_space) const override;
/* AREA API */
@@ -124,265 +125,262 @@ public:
/// The API area_set_param is a bit hacky, and allow Godot to set some parameters on Bullet's world, a different use print a warning to console.
/// All other APIs returns a warning message if used
- virtual RID area_create();
+ virtual RID area_create() override;
- virtual void area_set_space(RID p_area, RID p_space);
+ virtual void area_set_space(RID p_area, RID p_space) override;
- virtual RID area_get_space(RID p_area) const;
+ virtual RID area_get_space(RID p_area) const override;
- virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode);
- virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const;
+ virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) override;
+ virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const override;
- virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false);
- virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape);
- virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform);
- virtual int area_get_shape_count(RID p_area) const;
- virtual RID area_get_shape(RID p_area, int p_shape_idx) const;
- virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const;
- virtual void area_remove_shape(RID p_area, int p_shape_idx);
- virtual void area_clear_shapes(RID p_area);
- virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled);
- virtual void area_attach_object_instance_id(RID p_area, ObjectID p_id);
- virtual ObjectID area_get_object_instance_id(RID p_area) const;
+ virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false) override;
+ virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) override;
+ virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) override;
+ virtual int area_get_shape_count(RID p_area) const override;
+ virtual RID area_get_shape(RID p_area, int p_shape_idx) const override;
+ virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const override;
+ virtual void area_remove_shape(RID p_area, int p_shape_idx) override;
+ virtual void area_clear_shapes(RID p_area) override;
+ virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) override;
+ virtual void area_attach_object_instance_id(RID p_area, ObjectID p_id) override;
+ virtual ObjectID area_get_object_instance_id(RID p_area) const override;
/// If you pass as p_area the SpaceBullet you can set some parameters as specified below
/// AREA_PARAM_GRAVITY
/// AREA_PARAM_GRAVITY_VECTOR
/// Otherwise you can set area parameters
- virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value);
- virtual Variant area_get_param(RID p_area, AreaParameter p_param) const;
+ virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) override;
+ virtual Variant area_get_param(RID p_area, AreaParameter p_param) const override;
- virtual void area_set_transform(RID p_area, const Transform &p_transform);
- virtual Transform area_get_transform(RID p_area) const;
+ virtual void area_set_transform(RID p_area, const Transform &p_transform) override;
+ virtual Transform area_get_transform(RID p_area) const override;
- virtual void area_set_collision_mask(RID p_area, uint32_t p_mask);
- virtual void area_set_collision_layer(RID p_area, uint32_t p_layer);
+ virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) override;
+ virtual void area_set_collision_layer(RID p_area, uint32_t p_layer) override;
- virtual void area_set_monitorable(RID p_area, bool p_monitorable);
- virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method);
- virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method);
- virtual void area_set_ray_pickable(RID p_area, bool p_enable);
- virtual bool area_is_ray_pickable(RID p_area) const;
+ virtual void area_set_monitorable(RID p_area, bool p_monitorable) override;
+ virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) override;
+ virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) override;
+ virtual void area_set_ray_pickable(RID p_area, bool p_enable) override;
+ virtual bool area_is_ray_pickable(RID p_area) const override;
/* RIGID BODY API */
- virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false);
+ virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) override;
- virtual void body_set_space(RID p_body, RID p_space);
- virtual RID body_get_space(RID p_body) const;
+ virtual void body_set_space(RID p_body, RID p_space) override;
+ virtual RID body_get_space(RID p_body) const override;
- virtual void body_set_mode(RID p_body, BodyMode p_mode);
- virtual BodyMode body_get_mode(RID p_body) const;
+ virtual void body_set_mode(RID p_body, BodyMode p_mode) override;
+ virtual BodyMode body_get_mode(RID p_body) const override;
- virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false);
+ virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false) override;
// Not supported, Please remove and add new shape
- virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape);
- virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform);
+ virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) override;
+ virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) override;
- virtual int body_get_shape_count(RID p_body) const;
- virtual RID body_get_shape(RID p_body, int p_shape_idx) const;
- virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const;
+ virtual int body_get_shape_count(RID p_body) const override;
+ virtual RID body_get_shape(RID p_body, int p_shape_idx) const override;
+ virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const override;
- virtual void body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled);
+ virtual void body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled) override;
- virtual void body_remove_shape(RID p_body, int p_shape_idx);
- virtual void body_clear_shapes(RID p_body);
+ virtual void body_remove_shape(RID p_body, int p_shape_idx) override;
+ virtual void body_clear_shapes(RID p_body) override;
// Used for Rigid and Soft Bodies
- virtual void body_attach_object_instance_id(RID p_body, ObjectID p_id);
- virtual ObjectID body_get_object_instance_id(RID p_body) const;
+ virtual void body_attach_object_instance_id(RID p_body, ObjectID p_id) override;
+ virtual ObjectID body_get_object_instance_id(RID p_body) const override;
- virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable);
- virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const;
+ virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) override;
+ virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const override;
- virtual void body_set_collision_layer(RID p_body, uint32_t p_layer);
- virtual uint32_t body_get_collision_layer(RID p_body) const;
+ virtual void body_set_collision_layer(RID p_body, uint32_t p_layer) override;
+ virtual uint32_t body_get_collision_layer(RID p_body) const override;
- virtual void body_set_collision_mask(RID p_body, uint32_t p_mask);
- virtual uint32_t body_get_collision_mask(RID p_body) const;
+ virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) override;
+ virtual uint32_t body_get_collision_mask(RID p_body) const override;
/// This is not supported by physics server
- virtual void body_set_user_flags(RID p_body, uint32_t p_flags);
+ virtual void body_set_user_flags(RID p_body, uint32_t p_flags) override;
/// This is not supported by physics server
- virtual uint32_t body_get_user_flags(RID p_body) const;
+ virtual uint32_t body_get_user_flags(RID p_body) const override;
- virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value);
- virtual float body_get_param(RID p_body, BodyParameter p_param) const;
+ virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) override;
+ virtual float body_get_param(RID p_body, BodyParameter p_param) const override;
- virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin);
- virtual real_t body_get_kinematic_safe_margin(RID p_body) const;
+ virtual void body_set_kinematic_safe_margin(RID p_body, real_t p_margin) override;
+ virtual real_t body_get_kinematic_safe_margin(RID p_body) const override;
- virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant);
- virtual Variant body_get_state(RID p_body, BodyState p_state) const;
+ virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) override;
+ virtual Variant body_get_state(RID p_body, BodyState p_state) const override;
- virtual void body_set_applied_force(RID p_body, const Vector3 &p_force);
- virtual Vector3 body_get_applied_force(RID p_body) const;
+ virtual void body_set_applied_force(RID p_body, const Vector3 &p_force) override;
+ virtual Vector3 body_get_applied_force(RID p_body) const override;
- virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque);
- virtual Vector3 body_get_applied_torque(RID p_body) const;
+ virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque) override;
+ virtual Vector3 body_get_applied_torque(RID p_body) const override;
- virtual void body_add_central_force(RID p_body, const Vector3 &p_force);
- virtual void body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_pos);
- virtual void body_add_torque(RID p_body, const Vector3 &p_torque);
+ virtual void body_add_central_force(RID p_body, const Vector3 &p_force) override;
+ virtual void body_add_force(RID p_body, const Vector3 &p_force, const Vector3 &p_position = Vector3()) override;
+ virtual void body_add_torque(RID p_body, const Vector3 &p_torque) override;
- virtual void body_apply_central_impulse(RID p_body, const Vector3 &p_impulse);
- virtual void body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse);
- virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse);
- virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity);
+ virtual void body_apply_central_impulse(RID p_body, const Vector3 &p_impulse) override;
+ virtual void body_apply_impulse(RID p_body, const Vector3 &p_impulse, const Vector3 &p_position = Vector3()) override;
+ virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) override;
+ virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) override;
- virtual void body_set_axis_lock(RID p_body, BodyAxis p_axis, bool p_lock);
- virtual bool body_is_axis_locked(RID p_body, BodyAxis p_axis) const;
+ virtual void body_set_axis_lock(RID p_body, BodyAxis p_axis, bool p_lock) override;
+ virtual bool body_is_axis_locked(RID p_body, BodyAxis p_axis) const override;
- virtual void body_add_collision_exception(RID p_body, RID p_body_b);
- virtual void body_remove_collision_exception(RID p_body, RID p_body_b);
- virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions);
+ virtual void body_add_collision_exception(RID p_body, RID p_body_b) override;
+ virtual void body_remove_collision_exception(RID p_body, RID p_body_b) override;
+ virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) override;
- virtual void body_set_max_contacts_reported(RID p_body, int p_contacts);
- virtual int body_get_max_contacts_reported(RID p_body) const;
+ virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) override;
+ virtual int body_get_max_contacts_reported(RID p_body) const override;
- virtual void body_set_contacts_reported_depth_threshold(RID p_body, float p_threshold);
- virtual float body_get_contacts_reported_depth_threshold(RID p_body) const;
+ virtual void body_set_contacts_reported_depth_threshold(RID p_body, float p_threshold) override;
+ virtual float body_get_contacts_reported_depth_threshold(RID p_body) const override;
- virtual void body_set_omit_force_integration(RID p_body, bool p_omit);
- virtual bool body_is_omitting_force_integration(RID p_body) const;
+ virtual void body_set_omit_force_integration(RID p_body, bool p_omit) override;
+ virtual bool body_is_omitting_force_integration(RID p_body) const override;
- virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant());
+ virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()) override;
- virtual void body_set_ray_pickable(RID p_body, bool p_enable);
- virtual bool body_is_ray_pickable(RID p_body) const;
+ virtual void body_set_ray_pickable(RID p_body, bool p_enable) override;
+ virtual bool body_is_ray_pickable(RID p_body) const override;
// this function only works on physics process, errors and returns null otherwise
- virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body);
+ virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) override;
- virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true);
- virtual int body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, float p_margin = 0.001);
+ virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true) override;
+ virtual int body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, float p_margin = 0.001) override;
/* SOFT BODY API */
- virtual RID soft_body_create(bool p_init_sleeping = false);
+ virtual RID soft_body_create(bool p_init_sleeping = false) override;
- virtual void soft_body_update_rendering_server(RID p_body, class SoftBodyRenderingServerHandler *p_rendering_server_handler);
+ virtual void soft_body_update_rendering_server(RID p_body, class SoftBodyRenderingServerHandler *p_rendering_server_handler) override;
- virtual void soft_body_set_space(RID p_body, RID p_space);
- virtual RID soft_body_get_space(RID p_body) const;
+ virtual void soft_body_set_space(RID p_body, RID p_space) override;
+ virtual RID soft_body_get_space(RID p_body) const override;
- virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh);
+ virtual void soft_body_set_mesh(RID p_body, const REF &p_mesh) override;
- virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer);
- virtual uint32_t soft_body_get_collision_layer(RID p_body) const;
+ virtual void soft_body_set_collision_layer(RID p_body, uint32_t p_layer) override;
+ virtual uint32_t soft_body_get_collision_layer(RID p_body) const override;
- virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask);
- virtual uint32_t soft_body_get_collision_mask(RID p_body) const;
+ virtual void soft_body_set_collision_mask(RID p_body, uint32_t p_mask) override;
+ virtual uint32_t soft_body_get_collision_mask(RID p_body) const override;
- virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b);
- virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b);
- virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions);
+ virtual void soft_body_add_collision_exception(RID p_body, RID p_body_b) override;
+ virtual void soft_body_remove_collision_exception(RID p_body, RID p_body_b) override;
+ virtual void soft_body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) override;
- virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant);
- virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const;
+ virtual void soft_body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) override;
+ virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const override;
/// Special function. This function has bad performance
- virtual void soft_body_set_transform(RID p_body, const Transform &p_transform);
- virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const;
+ virtual void soft_body_set_transform(RID p_body, const Transform &p_transform) override;
+ virtual Vector3 soft_body_get_vertex_position(RID p_body, int vertex_index) const override;
- virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable);
- virtual bool soft_body_is_ray_pickable(RID p_body) const;
+ virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) override;
+ virtual bool soft_body_is_ray_pickable(RID p_body) const override;
- virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision);
- virtual int soft_body_get_simulation_precision(RID p_body);
+ virtual void soft_body_set_simulation_precision(RID p_body, int p_simulation_precision) override;
+ virtual int soft_body_get_simulation_precision(RID p_body) override;
- virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass);
- virtual real_t soft_body_get_total_mass(RID p_body);
+ virtual void soft_body_set_total_mass(RID p_body, real_t p_total_mass) override;
+ virtual real_t soft_body_get_total_mass(RID p_body) override;
- virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness);
- virtual real_t soft_body_get_linear_stiffness(RID p_body);
+ virtual void soft_body_set_linear_stiffness(RID p_body, real_t p_stiffness) override;
+ virtual real_t soft_body_get_linear_stiffness(RID p_body) override;
- virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness);
- virtual real_t soft_body_get_areaAngular_stiffness(RID p_body);
+ virtual void soft_body_set_areaAngular_stiffness(RID p_body, real_t p_stiffness) override;
+ virtual real_t soft_body_get_areaAngular_stiffness(RID p_body) override;
- virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness);
- virtual real_t soft_body_get_volume_stiffness(RID p_body);
+ virtual void soft_body_set_volume_stiffness(RID p_body, real_t p_stiffness) override;
+ virtual real_t soft_body_get_volume_stiffness(RID p_body) override;
- virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient);
- virtual real_t soft_body_get_pressure_coefficient(RID p_body);
+ virtual void soft_body_set_pressure_coefficient(RID p_body, real_t p_pressure_coefficient) override;
+ virtual real_t soft_body_get_pressure_coefficient(RID p_body) override;
- virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient);
- virtual real_t soft_body_get_pose_matching_coefficient(RID p_body);
+ virtual void soft_body_set_pose_matching_coefficient(RID p_body, real_t p_pose_matching_coefficient) override;
+ virtual real_t soft_body_get_pose_matching_coefficient(RID p_body) override;
- virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient);
- virtual real_t soft_body_get_damping_coefficient(RID p_body);
+ virtual void soft_body_set_damping_coefficient(RID p_body, real_t p_damping_coefficient) override;
+ virtual real_t soft_body_get_damping_coefficient(RID p_body) override;
- virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient);
- virtual real_t soft_body_get_drag_coefficient(RID p_body);
+ virtual void soft_body_set_drag_coefficient(RID p_body, real_t p_drag_coefficient) override;
+ virtual real_t soft_body_get_drag_coefficient(RID p_body) override;
- virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position);
- virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index);
+ virtual void soft_body_move_point(RID p_body, int p_point_index, const Vector3 &p_global_position) override;
+ virtual Vector3 soft_body_get_point_global_position(RID p_body, int p_point_index) override;
- virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const;
+ virtual Vector3 soft_body_get_point_offset(RID p_body, int p_point_index) const override;
- virtual void soft_body_remove_all_pinned_points(RID p_body);
- virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin);
- virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index);
+ virtual void soft_body_remove_all_pinned_points(RID p_body) override;
+ virtual void soft_body_pin_point(RID p_body, int p_point_index, bool p_pin) override;
+ virtual bool soft_body_is_point_pinned(RID p_body, int p_point_index) override;
/* JOINT API */
- virtual JointType joint_get_type(RID p_joint) const;
+ virtual JointType joint_get_type(RID p_joint) const override;
- virtual void joint_set_solver_priority(RID p_joint, int p_priority);
- virtual int joint_get_solver_priority(RID p_joint) const;
+ virtual void joint_set_solver_priority(RID p_joint, int p_priority) override;
+ virtual int joint_get_solver_priority(RID p_joint) const override;
- virtual void joint_disable_collisions_between_bodies(RID p_joint, const bool p_disable);
- virtual bool joint_is_disabled_collisions_between_bodies(RID p_joint) const;
+ virtual void joint_disable_collisions_between_bodies(RID p_joint, const bool p_disable) override;
+ virtual bool joint_is_disabled_collisions_between_bodies(RID p_joint) const override;
- virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B);
+ virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) override;
- virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, float p_value);
- virtual float pin_joint_get_param(RID p_joint, PinJointParam p_param) const;
+ virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, float p_value) override;
+ virtual float pin_joint_get_param(RID p_joint, PinJointParam p_param) const override;
- virtual void pin_joint_set_local_a(RID p_joint, const Vector3 &p_A);
- virtual Vector3 pin_joint_get_local_a(RID p_joint) const;
+ virtual void pin_joint_set_local_a(RID p_joint, const Vector3 &p_A) override;
+ virtual Vector3 pin_joint_get_local_a(RID p_joint) const override;
- virtual void pin_joint_set_local_b(RID p_joint, const Vector3 &p_B);
- virtual Vector3 pin_joint_get_local_b(RID p_joint) const;
+ virtual void pin_joint_set_local_b(RID p_joint, const Vector3 &p_B) override;
+ virtual Vector3 pin_joint_get_local_b(RID p_joint) const override;
- virtual RID joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B);
- virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B);
+ virtual RID joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B) override;
+ virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) override;
- virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, float p_value);
- virtual float hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const;
+ virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, float p_value) override;
+ virtual float hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const override;
- virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value);
- virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const;
+ virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) override;
+ virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const override;
/// Reference frame is A
- virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B);
+ virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override;
- virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, float p_value);
- virtual float slider_joint_get_param(RID p_joint, SliderJointParam p_param) const;
+ virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, float p_value) override;
+ virtual float slider_joint_get_param(RID p_joint, SliderJointParam p_param) const override;
/// Reference frame is A
- virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B);
+ virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override;
- virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, float p_value);
- virtual float cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const;
+ virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, float p_value) override;
+ virtual float cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const override;
/// Reference frame is A
- virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B);
-
- virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, float p_value);
- virtual float generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param);
+ virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override;
- virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable);
- virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag);
+ virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, float p_value) override;
+ virtual float generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) override;
- virtual void generic_6dof_joint_set_precision(RID p_joint, int precision);
- virtual int generic_6dof_joint_get_precision(RID p_joint);
+ virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable) override;
+ virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag) override;
/* MISC */
- virtual void free(RID p_rid);
+ virtual void free(RID p_rid) override;
- virtual void set_active(bool p_active) {
+ virtual void set_active(bool p_active) override {
active = p_active;
}
@@ -394,21 +392,20 @@ public:
return active;
}
- virtual void init();
- virtual void step(float p_deltaTime);
- virtual void sync();
- virtual void flush_queries();
- virtual void finish();
+ virtual void init() override;
+ virtual void step(float p_deltaTime) override;
+ virtual void flush_queries() override;
+ virtual void finish() override;
- virtual bool is_flushing_queries() const { return false; }
+ virtual bool is_flushing_queries() const override { return false; }
- virtual int get_process_info(ProcessInfo p_info);
+ virtual int get_process_info(ProcessInfo p_info) override;
- CollisionObjectBullet *get_collisin_object(RID p_object) const;
- RigidCollisionObjectBullet *get_rigid_collisin_object(RID p_object) const;
-
- /// Internal APIs
-public:
+ SpaceBullet *get_space(RID p_rid) const;
+ ShapeBullet *get_shape(RID p_rid) const;
+ CollisionObjectBullet *get_collision_object(RID p_object) const;
+ RigidCollisionObjectBullet *get_rigid_collision_object(RID p_object) const;
+ JointBullet *get_joint(RID p_rid) const;
};
#endif
diff --git a/modules/bullet/bullet_types_converter.cpp b/modules/bullet/bullet_types_converter.cpp
index c9493d8892..7b21e4e4b2 100644
--- a/modules/bullet/bullet_types_converter.cpp
+++ b/modules/bullet/bullet_types_converter.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -95,12 +95,61 @@ void G_TO_B(Transform const &inVal, btTransform &outVal) {
}
void UNSCALE_BT_BASIS(btTransform &scaledBasis) {
- btMatrix3x3 &m(scaledBasis.getBasis());
- btVector3 column0(m[0][0], m[1][0], m[2][0]);
- btVector3 column1(m[0][1], m[1][1], m[2][1]);
- btVector3 column2(m[0][2], m[1][2], m[2][2]);
+ btMatrix3x3 &basis(scaledBasis.getBasis());
+ btVector3 column0 = basis.getColumn(0);
+ btVector3 column1 = basis.getColumn(1);
+ btVector3 column2 = basis.getColumn(2);
+
+ // Check for zero scaling.
+ if (column0.fuzzyZero()) {
+ if (column1.fuzzyZero()) {
+ if (column2.fuzzyZero()) {
+ // All dimensions are fuzzy zero. Create a default basis.
+ column0 = btVector3(1, 0, 0);
+ column1 = btVector3(0, 1, 0);
+ column2 = btVector3(0, 0, 1);
+ } else { // Column 2 scale not fuzzy zero.
+ // Create two vectors orthogonal to row 2.
+ // Ensure that a default basis is created if row 2 = <0, 0, 1>
+ column1 = btVector3(0, column2[2], -column2[1]);
+ column0 = column1.cross(column2);
+ }
+ } else { // Column 1 scale not fuzzy zero.
+ if (column2.fuzzyZero()) {
+ // Create two vectors othogonal to column 1.
+ // Ensure that a default basis is created if column 1 = <0, 1, 0>
+ column0 = btVector3(column1[1], -column1[0], 0);
+ column2 = column0.cross(column1);
+ } else { // Column 1 and column 2 scales not fuzzy zero.
+ // Create column 0 orthogonal to column 1 and column 2.
+ column0 = column1.cross(column2);
+ }
+ }
+ } else { // Column 0 scale not fuzzy zero.
+ if (column1.fuzzyZero()) {
+ if (column2.fuzzyZero()) {
+ // Create two vectors orthogonal to column 0.
+ // Ensure that a default basis is created if column 0 = <1, 0, 0>
+ column2 = btVector3(-column0[2], 0, column0[0]);
+ column1 = column2.cross(column0);
+ } else { // Column 0 and column 2 scales not fuzzy zero.
+ // Create column 1 orthogonal to column 0 and column 2.
+ column1 = column2.cross(column0);
+ }
+ } else { // Column 0 and column 1 scales not fuzzy zero.
+ if (column2.fuzzyZero()) {
+ // Create column 2 orthogonal to column 0 and column 1.
+ column2 = column0.cross(column1);
+ }
+ }
+ }
+
+ // Normalize
column0.normalize();
column1.normalize();
column2.normalize();
- m.setValue(column0[0], column1[0], column2[0], column0[1], column1[1], column2[1], column0[2], column1[2], column2[2]);
+
+ basis.setValue(column0[0], column1[0], column2[0],
+ column0[1], column1[1], column2[1],
+ column0[2], column1[2], column2[2]);
}
diff --git a/modules/bullet/bullet_types_converter.h b/modules/bullet/bullet_types_converter.h
index fef07c55b7..ca9b7175dd 100644
--- a/modules/bullet/bullet_types_converter.h
+++ b/modules/bullet/bullet_types_converter.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/bullet_utilities.h b/modules/bullet/bullet_utilities.h
index a5e33d9829..a7c0fafbea 100644
--- a/modules/bullet/bullet_utilities.h
+++ b/modules/bullet/bullet_utilities.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp
index 1b72c2f577..bce8ec8076 100644
--- a/modules/bullet/collision_object_bullet.cpp
+++ b/modules/bullet/collision_object_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -80,27 +80,17 @@ btTransform CollisionObjectBullet::ShapeWrapper::get_adjusted_transform() const
void CollisionObjectBullet::ShapeWrapper::claim_bt_shape(const btVector3 &body_scale) {
if (!bt_shape) {
- if (active)
+ if (active) {
bt_shape = shape->create_bt_shape(scale * body_scale);
- else
+ } else {
bt_shape = ShapeBullet::create_shape_empty();
+ }
}
}
CollisionObjectBullet::CollisionObjectBullet(Type p_type) :
RIDBullet(),
- type(p_type),
- instance_id(ObjectID()),
- collisionLayer(0),
- collisionMask(0),
- collisionsEnabled(true),
- m_isStatic(false),
- ray_pickable(false),
- bt_collision_object(nullptr),
- body_scale(1., 1., 1.),
- force_shape_reset(false),
- space(nullptr),
- isTransformChanged(false) {}
+ type(p_type) {}
CollisionObjectBullet::~CollisionObjectBullet() {
// Remove all overlapping, notify is not required since godot take care of it
@@ -147,18 +137,21 @@ void CollisionObjectBullet::setupBulletCollisionObject(btCollisionObject *p_coll
void CollisionObjectBullet::add_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) {
exceptions.insert(p_ignoreCollisionObject->get_self());
- if (!bt_collision_object)
+ if (!bt_collision_object) {
return;
+ }
bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, true);
- if (space)
+ if (space) {
space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher());
+ }
}
void CollisionObjectBullet::remove_collision_exception(const CollisionObjectBullet *p_ignoreCollisionObject) {
exceptions.erase(p_ignoreCollisionObject->get_self());
bt_collision_object->setIgnoreCollisionCheck(p_ignoreCollisionObject->bt_collision_object, false);
- if (space)
+ if (space) {
space->get_broadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bt_collision_object->getBroadphaseHandle(), space->get_dispatcher());
+ }
}
bool CollisionObjectBullet::has_collision_exception(const CollisionObjectBullet *p_otherCollisionObject) const {
@@ -195,7 +188,6 @@ int CollisionObjectBullet::get_godot_object_flags() const {
}
void CollisionObjectBullet::set_transform(const Transform &p_global_transform) {
-
set_body_scale(p_global_transform.basis.get_scale_abs());
btTransform bt_transform;
@@ -225,11 +217,6 @@ void CollisionObjectBullet::notify_transform_changed() {
isTransformChanged = true;
}
-RigidCollisionObjectBullet::RigidCollisionObjectBullet(Type p_type) :
- CollisionObjectBullet(p_type),
- mainShape(nullptr) {
-}
-
RigidCollisionObjectBullet::~RigidCollisionObjectBullet() {
remove_all_shapes(true, true);
if (mainShape && mainShape->isCompound()) {
@@ -266,8 +253,9 @@ btCollisionShape *RigidCollisionObjectBullet::get_bt_shape(int p_index) const {
int RigidCollisionObjectBullet::find_shape(ShapeBullet *p_shape) const {
const int size = shapes.size();
for (int i = 0; i < size; ++i) {
- if (shapes[i].shape == p_shape)
+ if (shapes[i].shape == p_shape) {
return i;
+ }
}
return -1;
}
@@ -297,8 +285,9 @@ void RigidCollisionObjectBullet::remove_all_shapes(bool p_permanentlyFromThisBod
internal_shape_destroy(i, p_permanentlyFromThisBody);
}
shapes.clear();
- if (!p_force_not_reload)
+ if (!p_force_not_reload) {
reload_shapes();
+ }
}
void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transform &p_transform) {
@@ -319,8 +308,9 @@ Transform RigidCollisionObjectBullet::get_shape_transform(int p_index) const {
}
void RigidCollisionObjectBullet::set_shape_disabled(int p_index, bool p_disabled) {
- if (shapes[p_index].active != p_disabled)
+ if (shapes[p_index].active != p_disabled) {
return;
+ }
shapes.write[p_index].active = !p_disabled;
shape_changed(p_index);
}
@@ -339,7 +329,6 @@ void RigidCollisionObjectBullet::shape_changed(int p_shape_index) {
}
void RigidCollisionObjectBullet::reload_shapes() {
-
if (mainShape && mainShape->isCompound()) {
// Destroy compound
bulletdelete(mainShape);
diff --git a/modules/bullet/collision_object_bullet.h b/modules/bullet/collision_object_bullet.h
index 25176458a7..bea28f2183 100644
--- a/modules/bullet/collision_object_bullet.h
+++ b/modules/bullet/collision_object_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,8 +33,8 @@
#include "core/math/transform.h"
#include "core/math/vector3.h"
-#include "core/object.h"
-#include "core/vset.h"
+#include "core/object/class_db.h"
+#include "core/templates/vset.h"
#include "shape_owner_bullet.h"
#include <LinearMath/btTransform.h>
@@ -69,27 +69,22 @@ public:
};
struct ShapeWrapper {
- ShapeBullet *shape;
- btCollisionShape *bt_shape;
+ ShapeBullet *shape = nullptr;
+ btCollisionShape *bt_shape = nullptr;
btTransform transform;
btVector3 scale;
- bool active;
+ bool active = true;
- ShapeWrapper() :
- shape(nullptr),
- bt_shape(nullptr),
- active(true) {}
+ ShapeWrapper() {}
ShapeWrapper(ShapeBullet *p_shape, const btTransform &p_transform, bool p_active) :
shape(p_shape),
- bt_shape(nullptr),
active(p_active) {
set_transform(p_transform);
}
ShapeWrapper(ShapeBullet *p_shape, const Transform &p_transform, bool p_active) :
shape(p_shape),
- bt_shape(nullptr),
active(p_active) {
set_transform(p_transform);
}
@@ -117,15 +112,15 @@ public:
protected:
Type type;
ObjectID instance_id;
- uint32_t collisionLayer;
- uint32_t collisionMask;
- bool collisionsEnabled;
- bool m_isStatic;
- bool ray_pickable;
- btCollisionObject *bt_collision_object;
- Vector3 body_scale;
- bool force_shape_reset;
- SpaceBullet *space;
+ uint32_t collisionLayer = 0;
+ uint32_t collisionMask = 0;
+ bool collisionsEnabled = true;
+ bool m_isStatic = false;
+ bool ray_pickable = false;
+ btCollisionObject *bt_collision_object = nullptr;
+ Vector3 body_scale = Vector3(1, 1, 1);
+ bool force_shape_reset = false;
+ SpaceBullet *space = nullptr;
VSet<RID> exceptions;
@@ -133,7 +128,7 @@ protected:
/// New area is added when overlap with new area (AreaBullet::addOverlap), then is removed when it exit (CollisionObjectBullet::onExitArea)
/// This array is used mainly to know which area hold the pointer of this object
Vector<AreaBullet *> areasOverlapped;
- bool isTransformChanged;
+ bool isTransformChanged = false;
public:
CollisionObjectBullet(Type p_type);
@@ -218,11 +213,12 @@ public:
class RigidCollisionObjectBullet : public CollisionObjectBullet, public ShapeOwnerBullet {
protected:
- btCollisionShape *mainShape;
+ btCollisionShape *mainShape = nullptr;
Vector<ShapeWrapper> shapes;
public:
- RigidCollisionObjectBullet(Type p_type);
+ RigidCollisionObjectBullet(Type p_type) :
+ CollisionObjectBullet(p_type) {}
~RigidCollisionObjectBullet();
_FORCE_INLINE_ const Vector<ShapeWrapper> &get_shapes_wrappers() const { return shapes; }
diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp
index aac51034b8..e785780c5b 100644
--- a/modules/bullet/cone_twist_joint_bullet.cpp
+++ b/modules/bullet/cone_twist_joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &rbAFrame, const Transform &rbBFrame) :
JointBullet() {
-
Transform scaled_AFrame(rbAFrame.scaled(rbA->get_body_scale()));
scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis);
@@ -50,7 +49,6 @@ ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet
G_TO_B(scaled_AFrame, btFrameA);
if (rbB) {
-
Transform scaled_BFrame(rbBFrame.scaled(rbB->get_body_scale()));
scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis);
diff --git a/modules/bullet/cone_twist_joint_bullet.h b/modules/bullet/cone_twist_joint_bullet.h
index ed4baa9d1b..7d6bafd292 100644
--- a/modules/bullet/cone_twist_joint_bullet.h
+++ b/modules/bullet/cone_twist_joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/constraint_bullet.cpp b/modules/bullet/constraint_bullet.cpp
index 469b58521e..e610727685 100644
--- a/modules/bullet/constraint_bullet.cpp
+++ b/modules/bullet/constraint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,10 +37,7 @@
@author AndreaCatania
*/
-ConstraintBullet::ConstraintBullet() :
- space(nullptr),
- constraint(nullptr),
- disabled_collisions_between_bodies(true) {}
+ConstraintBullet::ConstraintBullet() {}
void ConstraintBullet::setup(btTypedConstraint *p_constraint) {
constraint = p_constraint;
diff --git a/modules/bullet/constraint_bullet.h b/modules/bullet/constraint_bullet.h
index 1946807bad..6afd8c9b52 100644
--- a/modules/bullet/constraint_bullet.h
+++ b/modules/bullet/constraint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,11 +45,10 @@ class SpaceBullet;
class btTypedConstraint;
class ConstraintBullet : public RIDBullet {
-
protected:
- SpaceBullet *space;
- btTypedConstraint *constraint;
- bool disabled_collisions_between_bodies;
+ SpaceBullet *space = nullptr;
+ btTypedConstraint *constraint = nullptr;
+ bool disabled_collisions_between_bodies = true;
public:
ConstraintBullet();
diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp
index 638944df76..43ad6c56d5 100644
--- a/modules/bullet/generic_6dof_joint_bullet.cpp
+++ b/modules/bullet/generic_6dof_joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) :
JointBullet() {
-
for (int i = 0; i < 3; i++) {
for (int j = 0; j < PhysicsServer3D::G6DOF_JOINT_FLAG_MAX; j++) {
flags[i][j] = false;
@@ -274,11 +273,3 @@ bool Generic6DOFJointBullet::get_flag(Vector3::Axis p_axis, PhysicsServer3D::G6D
ERR_FAIL_INDEX_V(p_axis, 3, false);
return flags[p_axis][p_flag];
}
-
-void Generic6DOFJointBullet::set_precision(int p_precision) {
- sixDOFConstraint->setOverrideNumSolverIterations(MAX(1, p_precision));
-}
-
-int Generic6DOFJointBullet::get_precision() const {
- return sixDOFConstraint->getOverrideNumSolverIterations();
-}
diff --git a/modules/bullet/generic_6dof_joint_bullet.h b/modules/bullet/generic_6dof_joint_bullet.h
index 316708bb11..62b8e85a81 100644
--- a/modules/bullet/generic_6dof_joint_bullet.h
+++ b/modules/bullet/generic_6dof_joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -68,9 +68,6 @@ public:
void set_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag, bool p_value);
bool get_flag(Vector3::Axis p_axis, PhysicsServer3D::G6DOFJointAxisFlag p_flag) const;
-
- void set_precision(int p_precision);
- int get_precision() const;
};
#endif
diff --git a/modules/bullet/godot_collision_configuration.cpp b/modules/bullet/godot_collision_configuration.cpp
index 8e29845a36..94f150b712 100644
--- a/modules/bullet/godot_collision_configuration.cpp
+++ b/modules/bullet/godot_collision_configuration.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -41,7 +41,6 @@
GodotCollisionConfiguration::GodotCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) :
btDefaultCollisionConfiguration(constructionInfo) {
-
void *mem = nullptr;
mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16);
@@ -60,44 +59,33 @@ GodotCollisionConfiguration::~GodotCollisionConfiguration() {
}
btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) {
-
if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
// This collision is not supported
return m_emptyCreateFunc;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) {
-
return m_rayWorldCF;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
return m_swappedRayWorldCF;
} else {
-
return btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1);
}
}
btCollisionAlgorithmCreateFunc *GodotCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) {
-
if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
// This collision is not supported
return m_emptyCreateFunc;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) {
-
return m_rayWorldCF;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
return m_swappedRayWorldCF;
} else {
-
return btDefaultCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1);
}
}
GodotSoftCollisionConfiguration::GodotSoftCollisionConfiguration(const btDiscreteDynamicsWorld *world, const btDefaultCollisionConstructionInfo &constructionInfo) :
btSoftBodyRigidBodyCollisionConfiguration(constructionInfo) {
-
void *mem = nullptr;
mem = btAlignedAlloc(sizeof(GodotRayWorldAlgorithm::CreateFunc), 16);
@@ -116,37 +104,27 @@ GodotSoftCollisionConfiguration::~GodotSoftCollisionConfiguration() {
}
btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0, int proxyType1) {
-
if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
// This collision is not supported
return m_emptyCreateFunc;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) {
-
return m_rayWorldCF;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
return m_swappedRayWorldCF;
} else {
-
return btSoftBodyRigidBodyCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0, proxyType1);
}
}
btCollisionAlgorithmCreateFunc *GodotSoftCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(int proxyType0, int proxyType1) {
-
if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0 && CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
// This collision is not supported
return m_emptyCreateFunc;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType0) {
-
return m_rayWorldCF;
} else if (CUSTOM_CONVEX_SHAPE_TYPE == proxyType1) {
-
return m_swappedRayWorldCF;
} else {
-
return btSoftBodyRigidBodyCollisionConfiguration::getClosestPointsAlgorithmCreateFunc(proxyType0, proxyType1);
}
}
diff --git a/modules/bullet/godot_collision_configuration.h b/modules/bullet/godot_collision_configuration.h
index ffad1b1bda..8ed55cb1da 100644
--- a/modules/bullet/godot_collision_configuration.h
+++ b/modules/bullet/godot_collision_configuration.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/godot_collision_dispatcher.cpp b/modules/bullet/godot_collision_dispatcher.cpp
index d919c85469..5d1e4d34d8 100644
--- a/modules/bullet/godot_collision_dispatcher.cpp
+++ b/modules/bullet/godot_collision_dispatcher.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/godot_collision_dispatcher.h b/modules/bullet/godot_collision_dispatcher.h
index 5a96268ee9..77472a9432 100644
--- a/modules/bullet/godot_collision_dispatcher.h
+++ b/modules/bullet/godot_collision_dispatcher.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef GODOT_COLLISION_DISPATCHER_H
#define GODOT_COLLISION_DISPATCHER_H
-#include "core/int_types.h"
+#include <cstdint>
#include <btBulletDynamicsCommon.h>
diff --git a/modules/bullet/godot_motion_state.h b/modules/bullet/godot_motion_state.h
index e2c1b10e94..0669d2739a 100644
--- a/modules/bullet/godot_motion_state.h
+++ b/modules/bullet/godot_motion_state.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,7 +46,6 @@ class RigidBodyBullet;
/// DOC:
/// http://www.bulletphysics.org/mediawiki-1.5.8/index.php/MotionStates#What.27s_a_MotionState.3F
class GodotMotionState : public btMotionState {
-
/// This data is used to store the new world position for kinematic body
btTransform bodyKinematicWorldTransf;
/// This data is used to store last world position
diff --git a/modules/bullet/godot_ray_world_algorithm.cpp b/modules/bullet/godot_ray_world_algorithm.cpp
index 2ef277cf5b..a8291d4ab4 100644
--- a/modules/bullet/godot_ray_world_algorithm.cpp
+++ b/modules/bullet/godot_ray_world_algorithm.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -52,7 +52,6 @@ GodotRayWorldAlgorithm::GodotRayWorldAlgorithm(const btDiscreteDynamicsWorld *wo
btActivatingCollisionAlgorithm(ci, body0Wrap, body1Wrap),
m_world(world),
m_manifoldPtr(mf),
- m_ownManifold(false),
m_isSwapped(isSwapped) {}
GodotRayWorldAlgorithm::~GodotRayWorldAlgorithm() {
@@ -62,7 +61,6 @@ GodotRayWorldAlgorithm::~GodotRayWorldAlgorithm() {
}
void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap, const btDispatcherInfo &dispatchInfo, btManifoldResult *resultOut) {
-
if (!m_manifoldPtr) {
if (m_isSwapped) {
m_manifoldPtr = m_dispatcher->getNewManifold(body1Wrap->getCollisionObject(), body0Wrap->getCollisionObject());
@@ -80,13 +78,11 @@ void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *bo
const btCollisionObjectWrapper *other_co_wrapper;
if (m_isSwapped) {
-
ray_shape = static_cast<const btRayShape *>(body1Wrap->getCollisionShape());
ray_transform = body1Wrap->getWorldTransform();
other_co_wrapper = body0Wrap;
} else {
-
ray_shape = static_cast<const btRayShape *>(body0Wrap->getCollisionShape());
ray_transform = body0Wrap->getWorldTransform();
@@ -100,15 +96,15 @@ void GodotRayWorldAlgorithm::processCollision(const btCollisionObjectWrapper *bo
m_world->rayTestSingleInternal(ray_transform, to, other_co_wrapper, btResult);
if (btResult.hasHit()) {
-
btScalar depth(ray_shape->getScaledLength() * (btResult.m_closestHitFraction - 1));
- if (depth > -RAY_PENETRATION_DEPTH_EPSILON)
+ if (depth > -RAY_PENETRATION_DEPTH_EPSILON) {
depth = 0.0;
+ }
- if (ray_shape->getSlipsOnSlope())
+ if (ray_shape->getSlipsOnSlope()) {
resultOut->addContactPoint(btResult.m_hitNormalWorld, btResult.m_hitPointWorld, depth);
- else {
+ } else {
resultOut->addContactPoint((ray_transform.getOrigin() - to.getOrigin()).normalize(), btResult.m_hitPointWorld, depth);
}
}
diff --git a/modules/bullet/godot_ray_world_algorithm.h b/modules/bullet/godot_ray_world_algorithm.h
index 2cdea6c133..f705edef81 100644
--- a/modules/bullet/godot_ray_world_algorithm.h
+++ b/modules/bullet/godot_ray_world_algorithm.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,10 +42,9 @@
class btDiscreteDynamicsWorld;
class GodotRayWorldAlgorithm : public btActivatingCollisionAlgorithm {
-
const btDiscreteDynamicsWorld *m_world;
btPersistentManifold *m_manifoldPtr;
- bool m_ownManifold;
+ bool m_ownManifold = false;
bool m_isSwapped;
public:
@@ -57,11 +56,11 @@ public:
virtual void getAllContactManifolds(btManifoldArray &manifoldArray) {
///should we use m_ownManifold to avoid adding duplicates?
- if (m_manifoldPtr && m_ownManifold)
+ if (m_manifoldPtr && m_ownManifold) {
manifoldArray.push_back(m_manifoldPtr);
+ }
}
struct CreateFunc : public btCollisionAlgorithmCreateFunc {
-
const btDiscreteDynamicsWorld *m_world;
CreateFunc(const btDiscreteDynamicsWorld *world);
@@ -72,7 +71,6 @@ public:
};
struct SwappedCreateFunc : public btCollisionAlgorithmCreateFunc {
-
const btDiscreteDynamicsWorld *m_world;
SwappedCreateFunc(const btDiscreteDynamicsWorld *world);
diff --git a/modules/bullet/godot_result_callbacks.cpp b/modules/bullet/godot_result_callbacks.cpp
index ad20a7e451..15d625afeb 100644
--- a/modules/bullet/godot_result_callbacks.cpp
+++ b/modules/bullet/godot_result_callbacks.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -62,11 +62,13 @@ bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) co
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) {
- if (!collide_with_areas)
+ if (!collide_with_areas) {
return false;
+ }
} else {
- if (!collide_with_bodies)
+ if (!collide_with_bodies) {
return false;
+ }
}
if (m_pickRay && !gObj->is_ray_pickable()) {
@@ -84,8 +86,9 @@ bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) co
}
bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const {
- if (count >= m_resultMax)
+ if (count >= m_resultMax) {
return false;
+ }
const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask);
if (needs) {
@@ -102,8 +105,9 @@ bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) con
}
btScalar GodotAllConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) {
- if (count >= m_resultMax)
+ if (count >= m_resultMax) {
return 1; // not used by bullet
+ }
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(convexResult.m_hitCollisionObject->getUserPointer());
@@ -126,16 +130,18 @@ bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *prox
if (gObj == m_self_object) {
return false;
} else {
-
// A kinematic body can't be stopped by a rigid body since the mass of kinematic body is infinite
- if (m_infinite_inertia && !btObj->isStaticOrKinematicObject())
+ if (m_infinite_inertia && !btObj->isStaticOrKinematicObject()) {
return false;
+ }
- if (gObj->getType() == CollisionObjectBullet::TYPE_AREA)
+ if (gObj->getType() == CollisionObjectBullet::TYPE_AREA) {
return false;
+ }
- if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object))
+ if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object)) {
return false;
+ }
}
return true;
} else {
@@ -150,11 +156,13 @@ bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0)
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) {
- if (!collide_with_areas)
+ if (!collide_with_areas) {
return false;
+ }
} else {
- if (!collide_with_bodies)
+ if (!collide_with_bodies) {
return false;
+ }
}
if (m_exclude->has(gObj->get_self())) {
@@ -167,16 +175,18 @@ bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0)
}
btScalar GodotClosestConvexResultCallback::addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace) {
- if (convexResult.m_localShapeInfo)
+ if (convexResult.m_localShapeInfo) {
m_shapeId = convexResult.m_localShapeInfo->m_triangleIndex; // "m_triangleIndex" Is a odd name but contains the compound shape ID
- else
+ } else {
m_shapeId = 0;
+ }
return btCollisionWorld::ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
}
bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const {
- if (m_count >= m_resultMax)
+ if (m_count >= m_resultMax) {
return false;
+ }
const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask);
if (needs) {
@@ -184,11 +194,13 @@ bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) co
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) {
- if (!collide_with_areas)
+ if (!collide_with_areas) {
return false;
+ }
} else {
- if (!collide_with_bodies)
+ if (!collide_with_bodies) {
return false;
+ }
}
if (m_exclude->has(gObj->get_self())) {
@@ -201,12 +213,11 @@ bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) co
}
btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) {
-
- if (m_count >= m_resultMax)
+ if (m_count >= m_resultMax) {
return cp.getDistance();
+ }
if (cp.getDistance() <= 0) {
-
PhysicsDirectSpaceState3D::ShapeResult &result = m_results[m_count];
// Penetrated
@@ -229,8 +240,9 @@ btScalar GodotAllContactResultCallback::addSingleResult(btManifoldPoint &cp, con
}
bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const {
- if (m_count >= m_resultMax)
+ if (m_count >= m_resultMax) {
return false;
+ }
const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask);
if (needs) {
@@ -238,11 +250,13 @@ bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *pr
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) {
- if (!collide_with_areas)
+ if (!collide_with_areas) {
return false;
+ }
} else {
- if (!collide_with_bodies)
+ if (!collide_with_bodies) {
return false;
+ }
}
if (m_exclude->has(gObj->get_self())) {
@@ -255,8 +269,9 @@ bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *pr
}
btScalar GodotContactPairContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) {
- if (m_count >= m_resultMax)
+ if (m_count >= m_resultMax) {
return 1; // not used by bullet
+ }
if (m_self_object == colObj0Wrap->getCollisionObject()) {
B_TO_G(cp.m_localPointA, m_results[m_count * 2 + 0]); // Local contact
@@ -278,11 +293,13 @@ bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy
CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer());
if (CollisionObjectBullet::TYPE_AREA == gObj->getType()) {
- if (!collide_with_areas)
+ if (!collide_with_areas) {
return false;
+ }
} else {
- if (!collide_with_bodies)
+ if (!collide_with_bodies) {
return false;
+ }
}
if (m_exclude->has(gObj->get_self())) {
@@ -295,7 +312,6 @@ bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy
}
btScalar GodotRestInfoContactResultCallback::addSingleResult(btManifoldPoint &cp, const btCollisionObjectWrapper *colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper *colObj1Wrap, int partId1, int index1) {
-
if (cp.getDistance() <= m_min_distance) {
m_min_distance = cp.getDistance();
@@ -325,7 +341,6 @@ btScalar GodotRestInfoContactResultCallback::addSingleResult(btManifoldPoint &cp
}
void GodotDeepPenetrationContactResultCallback::addContactPoint(const btVector3 &normalOnBInWorld, const btVector3 &pointInWorldOnB, btScalar depth) {
-
if (m_penetration_distance > depth) { // Has penetration?
const bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject();
diff --git a/modules/bullet/godot_result_callbacks.h b/modules/bullet/godot_result_callbacks.h
index 7e74a2b22e..4f40f7ecfd 100644
--- a/modules/bullet/godot_result_callbacks.h
+++ b/modules/bullet/godot_result_callbacks.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -56,8 +56,8 @@ struct GodotFilterCallback : public btOverlapFilterCallback {
/// It performs an additional check allow exclusions.
struct GodotClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback {
const Set<RID> *m_exclude;
- bool m_pickRay;
- int m_shapeId;
+ bool m_pickRay = false;
+ int m_shapeId = 0;
bool collide_with_bodies;
bool collide_with_areas;
@@ -66,18 +66,17 @@ public:
GodotClosestRayResultCallback(const btVector3 &rayFromWorld, const btVector3 &rayToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) :
btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld),
m_exclude(p_exclude),
- m_pickRay(false),
- m_shapeId(0),
collide_with_bodies(p_collide_with_bodies),
collide_with_areas(p_collide_with_areas) {}
virtual bool needsCollision(btBroadphaseProxy *proxy0) const;
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) {
- if (rayResult.m_localShapeInfo)
+ if (rayResult.m_localShapeInfo) {
m_shapeId = rayResult.m_localShapeInfo->m_triangleIndex; // "m_triangleIndex" Is a odd name but contains the compound shape ID
- else
+ } else {
m_shapeId = 0;
+ }
return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
};
@@ -88,13 +87,12 @@ public:
PhysicsDirectSpaceState3D::ShapeResult *m_results;
int m_resultMax;
const Set<RID> *m_exclude;
- int count;
+ int count = 0;
GodotAllConvexResultCallback(PhysicsDirectSpaceState3D::ShapeResult *p_results, int p_resultMax, const Set<RID> *p_exclude) :
m_results(p_results),
m_resultMax(p_resultMax),
- m_exclude(p_exclude),
- count(0) {}
+ m_exclude(p_exclude) {}
virtual bool needsCollision(btBroadphaseProxy *proxy0) const;
@@ -117,7 +115,7 @@ public:
struct GodotClosestConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback {
public:
const Set<RID> *m_exclude;
- int m_shapeId;
+ int m_shapeId = 0;
bool collide_with_bodies;
bool collide_with_areas;
@@ -125,7 +123,6 @@ public:
GodotClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const Set<RID> *p_exclude, bool p_collide_with_bodies, bool p_collide_with_areas) :
btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld),
m_exclude(p_exclude),
- m_shapeId(0),
collide_with_bodies(p_collide_with_bodies),
collide_with_areas(p_collide_with_areas) {}
@@ -140,7 +137,7 @@ public:
PhysicsDirectSpaceState3D::ShapeResult *m_results;
int m_resultMax;
const Set<RID> *m_exclude;
- int m_count;
+ int m_count = 0;
bool collide_with_bodies;
bool collide_with_areas;
@@ -150,7 +147,6 @@ public:
m_results(p_results),
m_resultMax(p_resultMax),
m_exclude(p_exclude),
- m_count(0),
collide_with_bodies(p_collide_with_bodies),
collide_with_areas(p_collide_with_areas) {}
@@ -166,7 +162,7 @@ public:
Vector3 *m_results;
int m_resultMax;
const Set<RID> *m_exclude;
- int m_count;
+ int m_count = 0;
bool collide_with_bodies;
bool collide_with_areas;
@@ -176,7 +172,6 @@ public:
m_results(p_results),
m_resultMax(p_resultMax),
m_exclude(p_exclude),
- m_count(0),
collide_with_bodies(p_collide_with_bodies),
collide_with_areas(p_collide_with_areas) {}
@@ -190,8 +185,8 @@ public:
const btCollisionObject *m_self_object;
PhysicsDirectSpaceState3D::ShapeRestInfo *m_result;
const Set<RID> *m_exclude;
- bool m_collided;
- real_t m_min_distance;
+ bool m_collided = false;
+ real_t m_min_distance = 0;
const btCollisionObject *m_rest_info_collision_object;
btVector3 m_rest_info_bt_point;
bool collide_with_bodies;
@@ -201,8 +196,6 @@ public:
m_self_object(p_self_object),
m_result(p_result),
m_exclude(p_exclude),
- m_collided(false),
- m_min_distance(0),
collide_with_bodies(p_collide_with_bodies),
collide_with_areas(p_collide_with_areas) {}
@@ -214,13 +207,11 @@ public:
struct GodotDeepPenetrationContactResultCallback : public btManifoldResult {
btVector3 m_pointNormalWorld;
btVector3 m_pointWorld;
- btScalar m_penetration_distance;
- int m_other_compound_shape_index;
+ btScalar m_penetration_distance = 0;
+ int m_other_compound_shape_index = 0;
GodotDeepPenetrationContactResultCallback(const btCollisionObjectWrapper *body0Wrap, const btCollisionObjectWrapper *body1Wrap) :
- btManifoldResult(body0Wrap, body1Wrap),
- m_penetration_distance(0),
- m_other_compound_shape_index(0) {}
+ btManifoldResult(body0Wrap, body1Wrap) {}
void reset() {
m_penetration_distance = 0;
diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp
index 4bea9f87c0..4ceb98729f 100644
--- a/modules/bullet/hinge_joint_bullet.cpp
+++ b/modules/bullet/hinge_joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameA, const Transform &frameB) :
JointBullet() {
-
Transform scaled_AFrame(frameA.scaled(rbA->get_body_scale()));
scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis);
@@ -50,7 +49,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c
G_TO_B(scaled_AFrame, btFrameA);
if (rbB) {
-
Transform scaled_BFrame(frameB.scaled(rbB->get_body_scale()));
scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis);
@@ -59,7 +57,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c
hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btFrameA, btFrameB));
} else {
-
hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btFrameA));
}
@@ -68,7 +65,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c
HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB) :
JointBullet() {
-
btVector3 btPivotA;
btVector3 btAxisA;
G_TO_B(pivotInA * rbA->get_body_scale(), btPivotA);
@@ -82,7 +78,6 @@ HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, c
hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), *rbB->get_bt_rigid_body(), btPivotA, btPivotB, btAxisA, btAxisB));
} else {
-
hingeConstraint = bulletnew(btHingeConstraint(*rbA->get_bt_rigid_body(), btPivotA, btAxisA));
}
@@ -162,7 +157,8 @@ void HingeJointBullet::set_flag(PhysicsServer3D::HingeJointFlag p_flag, bool p_v
case PhysicsServer3D::HINGE_JOINT_FLAG_ENABLE_MOTOR:
hingeConstraint->enableMotor(p_value);
break;
- case PhysicsServer3D::HINGE_JOINT_FLAG_MAX: break; // Can't happen, but silences warning
+ case PhysicsServer3D::HINGE_JOINT_FLAG_MAX:
+ break; // Can't happen, but silences warning
}
}
diff --git a/modules/bullet/hinge_joint_bullet.h b/modules/bullet/hinge_joint_bullet.h
index 120c40e5c0..06a95be374 100644
--- a/modules/bullet/hinge_joint_bullet.h
+++ b/modules/bullet/hinge_joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/joint_bullet.cpp b/modules/bullet/joint_bullet.cpp
index 6257ff0058..ac371658f5 100644
--- a/modules/bullet/joint_bullet.cpp
+++ b/modules/bullet/joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/joint_bullet.h b/modules/bullet/joint_bullet.h
index 9cb8aab276..5bb8b50961 100644
--- a/modules/bullet/joint_bullet.h
+++ b/modules/bullet/joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@ class RigidBodyBullet;
class btTypedConstraint;
class JointBullet : public ConstraintBullet {
-
public:
JointBullet();
virtual ~JointBullet();
diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp
index 68b40d7405..8e8ff57f11 100644
--- a/modules/bullet/pin_joint_bullet.cpp
+++ b/modules/bullet/pin_joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
PinJointBullet::PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b) :
JointBullet() {
if (p_body_b) {
-
btVector3 btPivotA;
btVector3 btPivotB;
G_TO_B(p_pos_a * p_body_a->get_body_scale(), btPivotA);
diff --git a/modules/bullet/pin_joint_bullet.h b/modules/bullet/pin_joint_bullet.h
index e7d05f34d4..6fbb6f7e02 100644
--- a/modules/bullet/pin_joint_bullet.h
+++ b/modules/bullet/pin_joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/register_types.cpp b/modules/bullet/register_types.cpp
index 009d0dff63..b5ad5749a6 100644
--- a/modules/bullet/register_types.cpp
+++ b/modules/bullet/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#include "register_types.h"
#include "bullet_physics_server.h"
-#include "core/class_db.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
+#include "core/object/class_db.h"
/**
@author AndreaCatania
diff --git a/modules/bullet/register_types.h b/modules/bullet/register_types.h
index 5a01a1422e..e405996705 100644
--- a/modules/bullet/register_types.h
+++ b/modules/bullet/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/rid_bullet.h b/modules/bullet/rid_bullet.h
index 3551ca05f9..0b74a0cc4d 100644
--- a/modules/bullet/rid_bullet.h
+++ b/modules/bullet/rid_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef RID_BULLET_H
#define RID_BULLET_H
-#include "core/rid.h"
+#include "core/templates/rid.h"
/**
@author AndreaCatania
diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp
index e393396713..4763098584 100644
--- a/modules/bullet/rigid_body_bullet.cpp
+++ b/modules/bullet/rigid_body_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -118,8 +118,8 @@ void BulletPhysicsDirectBodyState3D::add_central_force(const Vector3 &p_force) {
body->apply_central_force(p_force);
}
-void BulletPhysicsDirectBodyState3D::add_force(const Vector3 &p_force, const Vector3 &p_pos) {
- body->apply_force(p_force, p_pos);
+void BulletPhysicsDirectBodyState3D::add_force(const Vector3 &p_force, const Vector3 &p_position) {
+ body->apply_force(p_force, p_position);
}
void BulletPhysicsDirectBodyState3D::add_torque(const Vector3 &p_torque) {
@@ -130,8 +130,8 @@ void BulletPhysicsDirectBodyState3D::apply_central_impulse(const Vector3 &p_impu
body->apply_central_impulse(p_impulse);
}
-void BulletPhysicsDirectBodyState3D::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
- body->apply_impulse(p_pos, p_impulse);
+void BulletPhysicsDirectBodyState3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
+ body->apply_impulse(p_impulse, p_position);
}
void BulletPhysicsDirectBodyState3D::apply_torque_impulse(const Vector3 &p_impulse) {
@@ -256,26 +256,7 @@ void RigidBodyBullet::KinematicUtilities::just_delete_shapes(int new_size) {
}
RigidBodyBullet::RigidBodyBullet() :
- RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY),
- kinematic_utilities(nullptr),
- locked_axis(0),
- mass(1),
- gravity_scale(1),
- linearDamp(0),
- angularDamp(0),
- can_sleep(true),
- omit_forces_integration(false),
- can_integrate_forces(false),
- maxCollisionsDetection(0),
- collisionsCount(0),
- prev_collision_count(0),
- maxAreasWhereIam(10),
- areaWhereIamCount(0),
- countGravityPointSpaces(0),
- isScratchedSpaceOverrideModificator(false),
- previousActiveState(true),
- force_integration_callback(nullptr) {
-
+ RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_RIGID_BODY) {
godotMotionState = bulletnew(GodotMotionState(this));
// Initial properties
@@ -283,6 +264,7 @@ RigidBodyBullet::RigidBodyBullet() :
btRigidBody::btRigidBodyConstructionInfo cInfo(mass, godotMotionState, nullptr, localInertia);
btBody = bulletnew(btRigidBody(cInfo));
+ btBody->setFriction(1.0);
reload_shapes();
setupBulletCollisionObject(btBody);
@@ -302,8 +284,9 @@ RigidBodyBullet::RigidBodyBullet() :
RigidBodyBullet::~RigidBodyBullet() {
bulletdelete(godotMotionState);
- if (force_integration_callback)
+ if (force_integration_callback) {
memdelete(force_integration_callback);
+ }
destroy_kinematic_utilities();
}
@@ -328,8 +311,9 @@ void RigidBodyBullet::main_shape_changed() {
void RigidBodyBullet::reload_body() {
if (space) {
space->remove_rigid_body(this);
- if (get_main_shape())
+ if (get_main_shape()) {
space->add_rigid_body(this);
+ }
}
}
@@ -337,10 +321,9 @@ void RigidBodyBullet::set_space(SpaceBullet *p_space) {
// Clear the old space if there is one
if (space) {
can_integrate_forces = false;
-
- // Remove all eventual constraints
- assert_no_constraints();
-
+ isScratchedSpaceOverrideModificator = false;
+ // Remove any constraints
+ space->remove_rigid_body_constraints(this);
// Remove this object form the physics world
space->remove_rigid_body(this);
}
@@ -355,9 +338,9 @@ void RigidBodyBullet::set_space(SpaceBullet *p_space) {
void RigidBodyBullet::dispatch_callbacks() {
/// The check isFirstTransformChanged is necessary in order to call integrated forces only when the first transform is sent
if ((btBody->isKinematicObject() || btBody->isActive() || previousActiveState != btBody->isActive()) && force_integration_callback && can_integrate_forces) {
-
- if (omit_forces_integration)
+ if (omit_forces_integration) {
btBody->clearForces();
+ }
BulletPhysicsDirectBodyState3D *bodyDirect = BulletPhysicsDirectBodyState3D::get_singleton(this);
@@ -389,7 +372,6 @@ void RigidBodyBullet::dispatch_callbacks() {
}
void RigidBodyBullet::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
-
if (force_integration_callback) {
memdelete(force_integration_callback);
force_integration_callback = nullptr;
@@ -416,7 +398,6 @@ void RigidBodyBullet::on_collision_filters_change() {
}
void RigidBodyBullet::on_collision_checker_start() {
-
prev_collision_count = collisionsCount;
collisionsCount = 0;
@@ -432,7 +413,6 @@ void RigidBodyBullet::on_collision_checker_end() {
}
bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const float &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index) {
-
if (collisionsCount >= maxCollisionsDetection) {
return false;
}
@@ -454,23 +434,13 @@ bool RigidBodyBullet::add_collision_object(RigidBodyBullet *p_otherObject, const
bool RigidBodyBullet::was_colliding(RigidBodyBullet *p_other_object) {
for (int i = prev_collision_count - 1; 0 <= i; --i) {
- if ((*prev_collision_traces)[i] == p_other_object)
+ if ((*prev_collision_traces)[i] == p_other_object) {
return true;
+ }
}
return false;
}
-void RigidBodyBullet::assert_no_constraints() {
- if (btBody->getNumConstraintRefs()) {
- WARN_PRINT("A body with a joints is destroyed. Please check the implementation in order to destroy the joint before the body.");
- }
- /*for(int i = btBody->getNumConstraintRefs()-1; 0<=i; --i){
- btTypedConstraint* btConst = btBody->getConstraintRef(i);
- JointBullet* joint = static_cast<JointBullet*>( btConst->getUserConstraintPtr() );
- space->removeConstraint(joint);
- }*/
-}
-
void RigidBodyBullet::set_activation_state(bool p_active) {
if (p_active) {
btBody->activate();
@@ -578,12 +548,12 @@ void RigidBodyBullet::set_mode(PhysicsServer3D::BodyMode p_mode) {
btBody->setAngularVelocity(btVector3(0, 0, 0));
btBody->setLinearVelocity(btVector3(0, 0, 0));
}
+
PhysicsServer3D::BodyMode RigidBodyBullet::get_mode() const {
return mode;
}
void RigidBodyBullet::set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant) {
-
switch (p_state) {
case PhysicsServer3D::BODY_STATE_TRANSFORM:
set_transform(p_variant);
@@ -628,62 +598,69 @@ Variant RigidBodyBullet::get_state(PhysicsServer3D::BodyState p_state) const {
}
void RigidBodyBullet::apply_central_impulse(const Vector3 &p_impulse) {
- btVector3 btImpu;
- G_TO_B(p_impulse, btImpu);
- if (Vector3() != p_impulse)
+ btVector3 btImpulse;
+ G_TO_B(p_impulse, btImpulse);
+ if (Vector3() != p_impulse) {
btBody->activate();
- btBody->applyCentralImpulse(btImpu);
+ }
+ btBody->applyCentralImpulse(btImpulse);
}
-void RigidBodyBullet::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
- btVector3 btImpu;
- btVector3 btPos;
- G_TO_B(p_impulse, btImpu);
- G_TO_B(p_pos, btPos);
- if (Vector3() != p_impulse)
+void RigidBodyBullet::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
+ btVector3 btImpulse;
+ btVector3 btPosition;
+ G_TO_B(p_impulse, btImpulse);
+ G_TO_B(p_position, btPosition);
+ if (Vector3() != p_impulse) {
btBody->activate();
- btBody->applyImpulse(btImpu, btPos);
+ }
+ btBody->applyImpulse(btImpulse, btPosition);
}
void RigidBodyBullet::apply_torque_impulse(const Vector3 &p_impulse) {
btVector3 btImp;
G_TO_B(p_impulse, btImp);
- if (Vector3() != p_impulse)
+ if (Vector3() != p_impulse) {
btBody->activate();
+ }
btBody->applyTorqueImpulse(btImp);
}
-void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_pos) {
+void RigidBodyBullet::apply_force(const Vector3 &p_force, const Vector3 &p_position) {
btVector3 btForce;
- btVector3 btPos;
+ btVector3 btPosition;
G_TO_B(p_force, btForce);
- G_TO_B(p_pos, btPos);
- if (Vector3() != p_force)
+ G_TO_B(p_position, btPosition);
+ if (Vector3() != p_force) {
btBody->activate();
- btBody->applyForce(btForce, btPos);
+ }
+ btBody->applyForce(btForce, btPosition);
}
void RigidBodyBullet::apply_central_force(const Vector3 &p_force) {
btVector3 btForce;
G_TO_B(p_force, btForce);
- if (Vector3() != p_force)
+ if (Vector3() != p_force) {
btBody->activate();
+ }
btBody->applyCentralForce(btForce);
}
void RigidBodyBullet::apply_torque(const Vector3 &p_torque) {
btVector3 btTorq;
G_TO_B(p_torque, btTorq);
- if (Vector3() != p_torque)
+ if (Vector3() != p_torque) {
btBody->activate();
+ }
btBody->applyTorque(btTorq);
}
void RigidBodyBullet::set_applied_force(const Vector3 &p_force) {
btVector3 btVec = btBody->getTotalTorque();
- if (Vector3() != p_force)
+ if (Vector3() != p_force) {
btBody->activate();
+ }
btBody->clearForces();
btBody->applyTorque(btVec);
@@ -701,8 +678,9 @@ Vector3 RigidBodyBullet::get_applied_force() const {
void RigidBodyBullet::set_applied_torque(const Vector3 &p_torque) {
btVector3 btVec = btBody->getTotalForce();
- if (Vector3() != p_torque)
+ if (Vector3() != p_torque) {
btBody->activate();
+ }
btBody->clearForces();
btBody->applyCentralForce(btVec);
@@ -732,7 +710,6 @@ bool RigidBodyBullet::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const {
}
void RigidBodyBullet::reload_axis_lock() {
-
btBody->setLinearFactor(btVector3(float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)), float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)), float(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z))));
if (PhysicsServer3D::BODY_MODE_CHARACTER == mode) {
/// When character angular is always locked
@@ -759,7 +736,7 @@ void RigidBodyBullet::set_continuous_collision_detection(bool p_enable) {
}
btBody->setCcdSweptSphereRadius(radius * 0.2);
} else {
- btBody->setCcdMotionThreshold(10000.0);
+ btBody->setCcdMotionThreshold(0.);
btBody->setCcdSweptSphereRadius(0.);
}
}
@@ -771,8 +748,9 @@ bool RigidBodyBullet::is_continuous_collision_detection_enabled() const {
void RigidBodyBullet::set_linear_velocity(const Vector3 &p_velocity) {
btVector3 btVec;
G_TO_B(p_velocity, btVec);
- if (Vector3() != p_velocity)
+ if (Vector3() != p_velocity) {
btBody->activate();
+ }
btBody->setLinearVelocity(btVec);
}
@@ -785,8 +763,9 @@ Vector3 RigidBodyBullet::get_linear_velocity() const {
void RigidBodyBullet::set_angular_velocity(const Vector3 &p_velocity) {
btVector3 btVec;
G_TO_B(p_velocity, btVec);
- if (Vector3() != p_velocity)
+ if (Vector3() != p_velocity) {
btBody->activate();
+ }
btBody->setAngularVelocity(btVec);
}
@@ -798,8 +777,9 @@ Vector3 RigidBodyBullet::get_angular_velocity() const {
void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transform) {
if (mode == PhysicsServer3D::BODY_MODE_KINEMATIC) {
- if (space && space->get_delta_time() != 0)
+ if (space && space->get_delta_time() != 0) {
btBody->setLinearVelocity((p_global_transform.getOrigin() - btBody->getWorldTransform().getOrigin()) / space->get_delta_time());
+ }
// The kinematic use MotionState class
godotMotionState->moveBody(p_global_transform);
} else {
@@ -811,10 +791,8 @@ void RigidBodyBullet::set_transform__bullet(const btTransform &p_global_transfor
const btTransform &RigidBodyBullet::get_transform__bullet() const {
if (is_static()) {
-
return RigidCollisionObjectBullet::get_transform__bullet();
} else {
-
return godotMotionState->getCurrentWorldTransform();
}
}
@@ -830,14 +808,15 @@ void RigidBodyBullet::reload_shapes() {
// shapes incorrectly do not set the vector in calculateLocalIntertia.
// Arbitrary zero is preferable to undefined behaviour.
btVector3 inertia(0, 0, 0);
- if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) // Necessary to avoid assertion of the empty shape
+ if (EMPTY_SHAPE_PROXYTYPE != mainShape->getShapeType()) { // Necessary to avoid assertion of the empty shape
mainShape->calculateLocalInertia(mass, inertia);
+ }
btBody->setMassProps(mass, inertia);
}
btBody->updateInertiaTensor();
reload_kinematic_shapes();
- set_continuous_collision_detection(btBody->getCcdMotionThreshold() < 9998.0);
+ set_continuous_collision_detection(is_continuous_collision_detection_enabled());
reload_body();
}
@@ -849,7 +828,6 @@ void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
return;
}
for (int i = 0; i < areaWhereIamCount; ++i) {
-
if (nullptr == areasWhereIam[i]) {
// This area has the highest priority
areasWhereIam.write[i] = p_area;
@@ -857,8 +835,8 @@ void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
} else {
if (areasWhereIam[i]->get_spOv_priority() > p_area->get_spOv_priority()) {
// The position was found, just shift all elements
- for (int j = i; j < areaWhereIamCount; ++j) {
- areasWhereIam.write[j + 1] = areasWhereIam[j];
+ for (int j = areaWhereIamCount; j > i; j--) {
+ areasWhereIam.write[j] = areasWhereIam[j - 1];
}
areasWhereIam.write[i] = p_area;
break;
@@ -905,9 +883,9 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) {
}
void RigidBodyBullet::reload_space_override_modificator() {
- // Make sure that kinematic bodies have their total gravity calculated
- if (!is_active() && PhysicsServer3D::BODY_MODE_KINEMATIC != mode)
+ if (mode == PhysicsServer3D::BODY_MODE_STATIC) {
return;
+ }
Vector3 newGravity(0.0, 0.0, 0.0);
real_t newLinearDamp = MAX(0.0, linearDamp);
@@ -919,7 +897,6 @@ void RigidBodyBullet::reload_space_override_modificator() {
bool stopped = false;
for (int i = areaWhereIamCount - 1; (0 <= i) && !stopped; --i) {
-
currentArea = areasWhereIam[i];
if (!currentArea || PhysicsServer3D::AREA_SPACE_OVERRIDE_DISABLED == currentArea->get_spOv_mode()) {
@@ -928,7 +905,6 @@ void RigidBodyBullet::reload_space_override_modificator() {
/// Here is calculated the gravity
if (currentArea->is_spOv_gravityPoint()) {
-
/// It calculates the direction of new gravity
support_gravity = currentArea->get_transform().xform(currentArea->get_spOv_gravityVec()) - get_transform().get_origin();
real_t distanceMag = support_gravity.length();
@@ -1022,7 +998,6 @@ void RigidBodyBullet::notify_transform_changed() {
}
void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
-
btVector3 localInertia(0, 0, 0);
int clearedCurrentFlags = btBody->getCollisionFlags();
@@ -1031,19 +1006,18 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
// Rigidbody is dynamic if and only if mass is non Zero, otherwise static
const bool isDynamic = p_mass != 0.f;
if (isDynamic) {
-
- if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode)
+ if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode) {
return;
+ }
m_isStatic = false;
- if (mainShape)
+ if (mainShape) {
mainShape->calculateLocalInertia(p_mass, localInertia);
+ }
if (PhysicsServer3D::BODY_MODE_RIGID == mode) {
-
btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static
} else {
-
btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT);
}
@@ -1053,16 +1027,14 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) {
btBody->forceActivationState(DISABLE_DEACTIVATION); // DISABLE_DEACTIVATION 4
}
} else {
-
- if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode)
+ if (PhysicsServer3D::BODY_MODE_STATIC != mode && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) {
return;
+ }
m_isStatic = true;
if (PhysicsServer3D::BODY_MODE_STATIC == mode) {
-
btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_STATIC_OBJECT);
} else {
-
btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_KINEMATIC_OBJECT);
set_transform__bullet(btBody->getWorldTransform()); // Set current Transform using kinematic method
}
diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h
index 420b5cc443..fc3f2db796 100644
--- a/modules/bullet/rigid_body_bullet.h
+++ b/modules/bullet/rigid_body_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -88,61 +88,60 @@ private:
BulletPhysicsDirectBodyState3D() {}
public:
- virtual Vector3 get_total_gravity() const;
- virtual float get_total_angular_damp() const;
- virtual float get_total_linear_damp() const;
+ virtual Vector3 get_total_gravity() const override;
+ virtual float get_total_angular_damp() const override;
+ virtual float get_total_linear_damp() const override;
- virtual Vector3 get_center_of_mass() const;
- virtual Basis get_principal_inertia_axes() const;
+ virtual Vector3 get_center_of_mass() const override;
+ virtual Basis get_principal_inertia_axes() const override;
// get the mass
- virtual float get_inverse_mass() const;
+ virtual float get_inverse_mass() const override;
// get density of this body space
- virtual Vector3 get_inverse_inertia() const;
+ virtual Vector3 get_inverse_inertia() const override;
// get density of this body space
- virtual Basis get_inverse_inertia_tensor() const;
+ virtual Basis get_inverse_inertia_tensor() const override;
- virtual void set_linear_velocity(const Vector3 &p_velocity);
- virtual Vector3 get_linear_velocity() const;
+ virtual void set_linear_velocity(const Vector3 &p_velocity) override;
+ virtual Vector3 get_linear_velocity() const override;
- virtual void set_angular_velocity(const Vector3 &p_velocity);
- virtual Vector3 get_angular_velocity() const;
+ virtual void set_angular_velocity(const Vector3 &p_velocity) override;
+ virtual Vector3 get_angular_velocity() const override;
- virtual void set_transform(const Transform &p_transform);
- virtual Transform get_transform() const;
+ virtual void set_transform(const Transform &p_transform) override;
+ virtual Transform get_transform() const override;
- virtual void add_central_force(const Vector3 &p_force);
- virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos);
- virtual void add_torque(const Vector3 &p_torque);
- virtual void apply_central_impulse(const Vector3 &p_impulse);
- virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse);
- virtual void apply_torque_impulse(const Vector3 &p_impulse);
+ virtual void add_central_force(const Vector3 &p_force) override;
+ virtual void add_force(const Vector3 &p_force, const Vector3 &p_position = Vector3()) override;
+ virtual void add_torque(const Vector3 &p_torque) override;
+ virtual void apply_central_impulse(const Vector3 &p_impulse) override;
+ virtual void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3()) override;
+ virtual void apply_torque_impulse(const Vector3 &p_impulse) override;
- virtual void set_sleep_state(bool p_sleep);
- virtual bool is_sleeping() const;
+ virtual void set_sleep_state(bool p_sleep) override;
+ virtual bool is_sleeping() const override;
- virtual int get_contact_count() const;
+ virtual int get_contact_count() const override;
- virtual Vector3 get_contact_local_position(int p_contact_idx) const;
- virtual Vector3 get_contact_local_normal(int p_contact_idx) const;
- virtual float get_contact_impulse(int p_contact_idx) const;
- virtual int get_contact_local_shape(int p_contact_idx) const;
+ virtual Vector3 get_contact_local_position(int p_contact_idx) const override;
+ virtual Vector3 get_contact_local_normal(int p_contact_idx) const override;
+ virtual float get_contact_impulse(int p_contact_idx) const override;
+ virtual int get_contact_local_shape(int p_contact_idx) const override;
- virtual RID get_contact_collider(int p_contact_idx) const;
- virtual Vector3 get_contact_collider_position(int p_contact_idx) const;
- virtual ObjectID get_contact_collider_id(int p_contact_idx) const;
- virtual int get_contact_collider_shape(int p_contact_idx) const;
- virtual Vector3 get_contact_collider_velocity_at_position(int p_contact_idx) const;
+ virtual RID get_contact_collider(int p_contact_idx) const override;
+ virtual Vector3 get_contact_collider_position(int p_contact_idx) const override;
+ virtual ObjectID get_contact_collider_id(int p_contact_idx) const override;
+ virtual int get_contact_collider_shape(int p_contact_idx) const override;
+ virtual Vector3 get_contact_collider_velocity_at_position(int p_contact_idx) const override;
- virtual real_t get_step() const { return deltaTime; }
- virtual void integrate_forces() {
+ virtual real_t get_step() const override { return deltaTime; }
+ virtual void integrate_forces() override {
// Skip the execution of this function
}
- virtual PhysicsDirectSpaceState3D *get_space_state();
+ virtual PhysicsDirectSpaceState3D *get_space_state() override;
};
class RigidBodyBullet : public RigidCollisionObjectBullet {
-
public:
struct CollisionData {
RigidBodyBullet *otherObject;
@@ -162,11 +161,10 @@ public:
/// Used to hold shapes
struct KinematicShape {
- class btConvexShape *shape;
+ class btConvexShape *shape = nullptr;
btTransform transform;
- KinematicShape() :
- shape(nullptr) {}
+ KinematicShape() {}
bool is_active() const { return shape; }
};
@@ -190,19 +188,19 @@ private:
friend class BulletPhysicsDirectBodyState3D;
// This is required only for Kinematic movement
- KinematicUtilities *kinematic_utilities;
+ KinematicUtilities *kinematic_utilities = nullptr;
PhysicsServer3D::BodyMode mode;
GodotMotionState *godotMotionState;
btRigidBody *btBody;
- uint16_t locked_axis;
- real_t mass;
- real_t gravity_scale;
- real_t linearDamp;
- real_t angularDamp;
- bool can_sleep;
- bool omit_forces_integration;
- bool can_integrate_forces;
+ uint16_t locked_axis = 0;
+ real_t mass = 1;
+ real_t gravity_scale = 1;
+ real_t linearDamp = 0;
+ real_t angularDamp = 0;
+ bool can_sleep = true;
+ bool omit_forces_integration = false;
+ bool can_integrate_forces = false;
Vector<CollisionData> collisions;
Vector<RigidBodyBullet *> collision_traces_1;
@@ -211,21 +209,21 @@ private:
Vector<RigidBodyBullet *> *curr_collision_traces;
// these parameters are used to avoid vector resize
- int maxCollisionsDetection;
- int collisionsCount;
- int prev_collision_count;
+ int maxCollisionsDetection = 0;
+ int collisionsCount = 0;
+ int prev_collision_count = 0;
Vector<AreaBullet *> areasWhereIam;
// these parameters are used to avoid vector resize
- int maxAreasWhereIam;
- int areaWhereIamCount;
+ int maxAreasWhereIam = 10;
+ int areaWhereIamCount = 0;
// Used to know if the area is used as gravity point
- int countGravityPointSpaces;
- bool isScratchedSpaceOverrideModificator;
+ int countGravityPointSpaces = 0;
+ bool isScratchedSpaceOverrideModificator = false;
- bool previousActiveState; // Last check state
+ bool previousActiveState = true; // Last check state
- ForceIntegrationCallback *force_integration_callback;
+ ForceIntegrationCallback *force_integration_callback = nullptr;
public:
RigidBodyBullet();
@@ -250,7 +248,6 @@ public:
virtual void on_collision_checker_end();
void set_max_collisions_detection(int p_maxCollisionsDetection) {
-
ERR_FAIL_COND(0 > p_maxCollisionsDetection);
maxCollisionsDetection = p_maxCollisionsDetection;
@@ -270,8 +267,6 @@ public:
bool add_collision_object(RigidBodyBullet *p_otherObject, const Vector3 &p_hitWorldLocation, const Vector3 &p_hitLocalLocation, const Vector3 &p_hitNormal, const float &p_appliedImpulse, int p_other_shape_index, int p_local_shape_index);
bool was_colliding(RigidBodyBullet *p_other_object);
- void assert_no_constraints();
-
void set_activation_state(bool p_active);
bool is_active() const;
@@ -287,12 +282,12 @@ public:
void set_state(PhysicsServer3D::BodyState p_state, const Variant &p_variant);
Variant get_state(PhysicsServer3D::BodyState p_state) const;
- void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse);
void apply_central_impulse(const Vector3 &p_impulse);
+ void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3());
void apply_torque_impulse(const Vector3 &p_impulse);
- void apply_force(const Vector3 &p_force, const Vector3 &p_pos);
void apply_central_force(const Vector3 &p_force);
+ void apply_force(const Vector3 &p_force, const Vector3 &p_position = Vector3());
void apply_torque(const Vector3 &p_torque);
void set_applied_force(const Vector3 &p_force);
diff --git a/modules/bullet/shape_bullet.cpp b/modules/bullet/shape_bullet.cpp
index 8ac26a0fdb..cc2ec28a9e 100644
--- a/modules/bullet/shape_bullet.cpp
+++ b/modules/bullet/shape_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,7 @@
#include "bullet_physics_server.h"
#include "bullet_types_converter.h"
#include "bullet_utilities.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
#include "shape_owner_bullet.h"
#include <BulletCollision/CollisionDispatch/btInternalEdgeUtility.h>
@@ -46,8 +46,7 @@
@author AndreaCatania
*/
-ShapeBullet::ShapeBullet() :
- margin(0.04) {}
+ShapeBullet::ShapeBullet() {}
ShapeBullet::~ShapeBullet() {}
@@ -81,7 +80,9 @@ void ShapeBullet::add_owner(ShapeOwnerBullet *p_owner) {
void ShapeBullet::remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFromThisBody) {
Map<ShapeOwnerBullet *, int>::Element *E = owners.find(p_owner);
- if (!E) return;
+ if (!E) {
+ return;
+ }
E->get()--;
if (p_permanentlyFromThisBody || 0 >= E->get()) {
owners.erase(E);
@@ -89,7 +90,6 @@ void ShapeBullet::remove_owner(ShapeOwnerBullet *p_owner, bool p_permanentlyFrom
}
bool ShapeBullet::is_owner(ShapeOwnerBullet *p_owner) const {
-
return owners.has(p_owner);
}
@@ -151,8 +151,9 @@ btHeightfieldTerrainShape *ShapeBullet::create_shape_height_field(Vector<real_t>
btHeightfieldTerrainShape *heightfield = bulletnew(btHeightfieldTerrainShape(p_width, p_depth, heightsPtr, ignoredHeightScale, p_min_height, p_max_height, YAxis, PHY_FLOAT, flipQuadEdges));
// The shape can be created without params when you do PhysicsServer3D.shape_create(PhysicsServer3D.SHAPE_HEIGHTMAP)
- if (heightsPtr)
+ if (heightsPtr) {
heightfield->buildAccelerator(16);
+ }
return heightfield;
}
@@ -274,7 +275,7 @@ void CapsuleShapeBullet::setup(real_t p_height, real_t p_radius) {
}
btCollisionShape *CapsuleShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) {
- return prepare(ShapeBullet::create_shape_capsule(radius * p_implicit_scale[0] + p_extra_edge, height * p_implicit_scale[1] + p_extra_edge));
+ return prepare(ShapeBullet::create_shape_capsule(radius * p_implicit_scale[0] + p_extra_edge, height * p_implicit_scale[1]));
}
/* Cylinder */
@@ -349,9 +350,10 @@ void ConvexPolygonShapeBullet::setup(const Vector<Vector3> &p_vertices) {
}
btCollisionShape *ConvexPolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) {
- if (!vertices.size())
+ if (!vertices.size()) {
// This is necessary since 0 vertices
return prepare(ShapeBullet::create_shape_empty());
+ }
btCollisionShape *cs(ShapeBullet::create_shape_convex(vertices));
cs->setLocalScaling(p_implicit_scale);
prepare(cs);
@@ -361,8 +363,7 @@ btCollisionShape *ConvexPolygonShapeBullet::create_bt_shape(const btVector3 &p_i
/* Concave polygon */
ConcavePolygonShapeBullet::ConcavePolygonShapeBullet() :
- ShapeBullet(),
- meshShape(nullptr) {}
+ ShapeBullet() {}
ConcavePolygonShapeBullet::~ConcavePolygonShapeBullet() {
if (meshShape) {
@@ -395,7 +396,6 @@ void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) {
}
int src_face_count = faces.size();
if (0 < src_face_count) {
-
// It counts the faces and assert the array contains the correct number of vertices.
ERR_FAIL_COND(src_face_count % 3);
@@ -433,9 +433,10 @@ void ConcavePolygonShapeBullet::setup(Vector<Vector3> p_faces) {
btCollisionShape *ConcavePolygonShapeBullet::create_bt_shape(const btVector3 &p_implicit_scale, real_t p_extra_edge) {
btCollisionShape *cs = ShapeBullet::create_shape_concave(meshShape);
- if (!cs)
+ if (!cs) {
// This is necessary since if 0 faces the creation of concave return null
cs = ShapeBullet::create_shape_empty();
+ }
cs->setLocalScaling(p_implicit_scale);
prepare(cs);
cs->setMargin(0);
@@ -458,16 +459,21 @@ void HeightMapShapeBullet::set_data(const Variant &p_data) {
real_t l_max_height = 0.0;
// If specified, min and max height will be used as precomputed values
- if (d.has("min_height"))
+ if (d.has("min_height")) {
l_min_height = d["min_height"];
- if (d.has("max_height"))
+ }
+ if (d.has("max_height")) {
l_max_height = d["max_height"];
+ }
ERR_FAIL_COND(l_min_height > l_max_height);
int l_width = d["width"];
int l_depth = d["depth"];
+ ERR_FAIL_COND_MSG(l_width < 2, "Map width must be at least 2.");
+ ERR_FAIL_COND_MSG(l_depth < 2, "Map depth must be at least 2.");
+
// TODO This code will need adjustments if real_t is set to `double`,
// because that precision is unnecessary for a heightmap and Bullet doesn't support it...
@@ -514,7 +520,6 @@ void HeightMapShapeBullet::set_data(const Variant &p_data) {
// Compute min and max heights if not specified.
if (!d.has("min_height") && !d.has("max_height")) {
-
const real_t *r = l_heights.ptr();
int heights_size = l_heights.size();
@@ -562,18 +567,14 @@ btCollisionShape *HeightMapShapeBullet::create_bt_shape(const btVector3 &p_impli
/* Ray shape */
RayShapeBullet::RayShapeBullet() :
- ShapeBullet(),
- length(1),
- slips_on_slope(false) {}
+ ShapeBullet() {}
void RayShapeBullet::set_data(const Variant &p_data) {
-
Dictionary d = p_data;
setup(d["length"], d["slips_on_slope"]);
}
Variant RayShapeBullet::get_data() const {
-
Dictionary d;
d["length"] = length;
d["slips_on_slope"] = slips_on_slope;
diff --git a/modules/bullet/shape_bullet.h b/modules/bullet/shape_bullet.h
index 0dbc616fe5..63475822de 100644
--- a/modules/bullet/shape_bullet.h
+++ b/modules/bullet/shape_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef SHAPE_BULLET_H
#define SHAPE_BULLET_H
-#include "core/math/geometry.h"
-#include "core/variant.h"
+#include "core/math/geometry_3d.h"
+#include "core/variant/variant.h"
#include "rid_bullet.h"
#include "servers/physics_server_3d.h"
@@ -50,9 +50,8 @@ class ShapeOwnerBullet;
class btBvhTriangleMeshShape;
class ShapeBullet : public RIDBullet {
-
Map<ShapeOwnerBullet *, int> owners;
- real_t margin;
+ real_t margin = 0.04;
protected:
/// return self
@@ -95,7 +94,6 @@ public:
};
class PlaneShapeBullet : public ShapeBullet {
-
Plane plane;
public:
@@ -111,7 +109,6 @@ private:
};
class SphereShapeBullet : public ShapeBullet {
-
real_t radius;
public:
@@ -128,7 +125,6 @@ private:
};
class BoxShapeBullet : public ShapeBullet {
-
btVector3 half_extents;
public:
@@ -145,7 +141,6 @@ private:
};
class CapsuleShapeBullet : public ShapeBullet {
-
real_t height;
real_t radius;
@@ -164,7 +159,6 @@ private:
};
class CylinderShapeBullet : public ShapeBullet {
-
real_t height;
real_t radius;
@@ -183,7 +177,6 @@ private:
};
class ConvexPolygonShapeBullet : public ShapeBullet {
-
public:
btAlignedObjectArray<btVector3> vertices;
@@ -200,7 +193,7 @@ private:
};
class ConcavePolygonShapeBullet : public ShapeBullet {
- class btBvhTriangleMeshShape *meshShape;
+ class btBvhTriangleMeshShape *meshShape = nullptr;
public:
Vector<Vector3> faces;
@@ -218,7 +211,6 @@ private:
};
class HeightMapShapeBullet : public ShapeBullet {
-
public:
Vector<real_t> heights;
int width;
@@ -238,10 +230,9 @@ private:
};
class RayShapeBullet : public ShapeBullet {
-
public:
- real_t length;
- bool slips_on_slope;
+ real_t length = 1;
+ bool slips_on_slope = false;
RayShapeBullet();
diff --git a/modules/bullet/shape_owner_bullet.cpp b/modules/bullet/shape_owner_bullet.cpp
index d63096d9a3..ea8821eaec 100644
--- a/modules/bullet/shape_owner_bullet.cpp
+++ b/modules/bullet/shape_owner_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/shape_owner_bullet.h b/modules/bullet/shape_owner_bullet.h
index f909632c99..4bd583e096 100644
--- a/modules/bullet/shape_owner_bullet.h
+++ b/modules/bullet/shape_owner_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/slider_joint_bullet.cpp b/modules/bullet/slider_joint_bullet.cpp
index f193daef39..45c892851b 100644
--- a/modules/bullet/slider_joint_bullet.cpp
+++ b/modules/bullet/slider_joint_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -42,7 +42,6 @@
SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) :
JointBullet() {
-
Transform scaled_AFrame(frameInA.scaled(rbA->get_body_scale()));
scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis);
@@ -50,7 +49,6 @@ SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB,
G_TO_B(scaled_AFrame, btFrameA);
if (rbB) {
-
Transform scaled_BFrame(frameInB.scaled(rbB->get_body_scale()));
scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis);
@@ -121,6 +119,7 @@ real_t SliderJointBullet::getLowerLinLimit() const {
void SliderJointBullet::setLowerLinLimit(real_t lowerLimit) {
sliderConstraint->setLowerLinLimit(lowerLimit);
}
+
real_t SliderJointBullet::getUpperLinLimit() const {
return sliderConstraint->getUpperLinLimit();
}
@@ -344,56 +343,123 @@ real_t SliderJointBullet::getLinearPos() {
void SliderJointBullet::set_param(PhysicsServer3D::SliderJointParam p_param, real_t p_value) {
switch (p_param) {
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: setUpperLinLimit(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: setLowerLinLimit(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: setSoftnessLimLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: setRestitutionLimLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: setDampingLimLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: setSoftnessDirLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: setRestitutionDirLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: setDampingDirLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: setSoftnessOrthoLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: setRestitutionOrthoLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: setDampingOrthoLin(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: setUpperAngLimit(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: setLowerAngLimit(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: setSoftnessLimAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: setRestitutionLimAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: setDampingLimAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: setSoftnessDirAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: setRestitutionDirAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: setDampingDirAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: setSoftnessOrthoAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: setRestitutionOrthoAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: setDampingOrthoAng(p_value); break;
- case PhysicsServer3D::SLIDER_JOINT_MAX: break; // Can't happen, but silences warning
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER:
+ setUpperLinLimit(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER:
+ setLowerLinLimit(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS:
+ setSoftnessLimLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION:
+ setRestitutionLimLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING:
+ setDampingLimLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS:
+ setSoftnessDirLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION:
+ setRestitutionDirLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING:
+ setDampingDirLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS:
+ setSoftnessOrthoLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION:
+ setRestitutionOrthoLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING:
+ setDampingOrthoLin(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER:
+ setUpperAngLimit(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER:
+ setLowerAngLimit(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS:
+ setSoftnessLimAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION:
+ setRestitutionLimAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING:
+ setDampingLimAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS:
+ setSoftnessDirAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION:
+ setRestitutionDirAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING:
+ setDampingDirAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS:
+ setSoftnessOrthoAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION:
+ setRestitutionOrthoAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING:
+ setDampingOrthoAng(p_value);
+ break;
+ case PhysicsServer3D::SLIDER_JOINT_MAX:
+ break; // Can't happen, but silences warning
}
}
real_t SliderJointBullet::get_param(PhysicsServer3D::SliderJointParam p_param) const {
switch (p_param) {
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER: return getUpperLinLimit();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER: return getLowerLinLimit();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: return getSoftnessLimLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: return getRestitutionLimLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: return getDampingLimLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: return getSoftnessDirLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: return getRestitutionDirLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING: return getDampingDirLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: return getSoftnessOrthoLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: return getRestitutionOrthoLin();
- case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: return getDampingOrthoLin();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: return getUpperAngLimit();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: return getLowerAngLimit();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: return getSoftnessLimAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: return getRestitutionLimAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: return getDampingLimAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: return getSoftnessDirAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: return getRestitutionDirAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: return getDampingDirAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: return getSoftnessOrthoAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: return getRestitutionOrthoAng();
- case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: return getDampingOrthoAng();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_UPPER:
+ return getUpperLinLimit();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_LOWER:
+ return getLowerLinLimit();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS:
+ return getSoftnessLimLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION:
+ return getRestitutionLimLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_LIMIT_DAMPING:
+ return getDampingLimLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS:
+ return getSoftnessDirLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION:
+ return getRestitutionDirLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_MOTION_DAMPING:
+ return getDampingDirLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS:
+ return getSoftnessOrthoLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION:
+ return getRestitutionOrthoLin();
+ case PhysicsServer3D::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING:
+ return getDampingOrthoLin();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_UPPER:
+ return getUpperAngLimit();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_LOWER:
+ return getLowerAngLimit();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS:
+ return getSoftnessLimAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION:
+ return getRestitutionLimAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING:
+ return getDampingLimAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS:
+ return getSoftnessDirAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION:
+ return getRestitutionDirAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_MOTION_DAMPING:
+ return getDampingDirAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS:
+ return getSoftnessOrthoAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION:
+ return getRestitutionOrthoAng();
+ case PhysicsServer3D::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING:
+ return getDampingOrthoAng();
default:
return 0;
}
diff --git a/modules/bullet/slider_joint_bullet.h b/modules/bullet/slider_joint_bullet.h
index 6410b952ed..90964671c2 100644
--- a/modules/bullet/slider_joint_bullet.h
+++ b/modules/bullet/slider_joint_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp
index 236bdc7c8a..a490179964 100644
--- a/modules/bullet/soft_body_bullet.cpp
+++ b/modules/bullet/soft_body_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,18 +36,7 @@
#include "space_bullet.h"
SoftBodyBullet::SoftBodyBullet() :
- CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY),
- bt_soft_body(nullptr),
- isScratched(false),
- simulation_precision(5),
- total_mass(1.),
- linear_stiffness(0.5),
- areaAngular_stiffness(0.5),
- volume_stiffness(0.5),
- pressure_coefficient(0.),
- pose_matching_coefficient(0.),
- damping_coefficient(0.01),
- drag_coefficient(0.) {}
+ CollisionObjectBullet(CollisionObjectBullet::TYPE_SOFT_BODY) {}
SoftBodyBullet::~SoftBodyBullet() {
}
@@ -77,8 +66,9 @@ void SoftBodyBullet::on_enter_area(AreaBullet *p_area) {}
void SoftBodyBullet::on_exit_area(AreaBullet *p_area) {}
void SoftBodyBullet::update_rendering_server(SoftBodyRenderingServerHandler *p_rendering_server_handler) {
- if (!bt_soft_body)
+ if (!bt_soft_body) {
return;
+ }
/// Update visual server vertices
const btSoftBody::tNodeArray &nodes(bt_soft_body->m_nodes);
@@ -116,14 +106,13 @@ void SoftBodyBullet::update_rendering_server(SoftBodyRenderingServerHandler *p_r
}
void SoftBodyBullet::set_soft_mesh(const Ref<Mesh> &p_mesh) {
-
- if (p_mesh.is_null())
+ if (p_mesh.is_null()) {
soft_mesh.unref();
- else
+ } else {
soft_mesh = p_mesh;
+ }
if (soft_mesh.is_null()) {
-
destroy_soft_body();
return;
}
@@ -134,9 +123,9 @@ void SoftBodyBullet::set_soft_mesh(const Ref<Mesh> &p_mesh) {
}
void SoftBodyBullet::destroy_soft_body() {
-
- if (!bt_soft_body)
+ if (!bt_soft_body) {
return;
+ }
if (space) {
/// Remove from world before deletion
@@ -153,8 +142,9 @@ void SoftBodyBullet::set_soft_transform(const Transform &p_transform) {
}
void SoftBodyBullet::move_all_nodes(const Transform &p_transform) {
- if (!bt_soft_body)
+ if (!bt_soft_body) {
return;
+ }
btTransform bt_transf;
G_TO_B(p_transform, bt_transf);
bt_soft_body->transform(bt_transf);
@@ -180,8 +170,9 @@ void SoftBodyBullet::get_node_position(int p_node_index, Vector3 &r_position) co
}
void SoftBodyBullet::get_node_offset(int p_node_index, Vector3 &r_offset) const {
- if (soft_mesh.is_null())
+ if (soft_mesh.is_null()) {
return;
+ }
Array arrays = soft_mesh->surface_get_arrays(0);
Vector<Vector3> vertices(arrays[RS::ARRAY_VERTEX]);
@@ -226,15 +217,15 @@ void SoftBodyBullet::reset_all_node_mass() {
}
void SoftBodyBullet::reset_all_node_positions() {
- if (soft_mesh.is_null())
+ if (soft_mesh.is_null()) {
return;
+ }
Array arrays = soft_mesh->surface_get_arrays(0);
Vector<Vector3> vs_vertices(arrays[RS::ARRAY_VERTEX]);
const Vector3 *vs_vertices_read = vs_vertices.ptr();
for (int vertex_index = bt_soft_body->m_nodes.size() - 1; 0 <= vertex_index; --vertex_index) {
-
G_TO_B(vs_vertices_read[indices_table[vertex_index][0]], bt_soft_body->m_nodes[vertex_index].m_x);
bt_soft_body->m_nodes[vertex_index].m_q = bt_soft_body->m_nodes[vertex_index].m_x;
@@ -342,7 +333,6 @@ void SoftBodyBullet::set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector
const Vector3 *p_vertices_read = p_vertices.ptr();
for (int vs_vertex_index = 0; vs_vertex_index < vs_vertices_size; ++vs_vertex_index) {
-
Map<Vector3, int>::Element *e = unique_vertices.find(p_vertices_read[vs_vertex_index]);
int vertex_id;
if (e) {
@@ -398,9 +388,9 @@ void SoftBodyBullet::set_trimesh_body_shape(Vector<int> p_indices, Vector<Vector
}
void SoftBodyBullet::setup_soft_body() {
-
- if (!bt_soft_body)
+ if (!bt_soft_body) {
return;
+ }
// Soft body setup
setupBulletCollisionObject(bt_soft_body);
diff --git a/modules/bullet/soft_body_bullet.h b/modules/bullet/soft_body_bullet.h
index 3c6871e0d6..b15b72daf9 100644
--- a/modules/bullet/soft_body_bullet.h
+++ b/modules/bullet/soft_body_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -56,24 +56,23 @@
*/
class SoftBodyBullet : public CollisionObjectBullet {
-
private:
- btSoftBody *bt_soft_body;
+ btSoftBody *bt_soft_body = nullptr;
Vector<Vector<int>> indices_table;
btSoftBody::Material *mat0; // This is just a copy of pointer managed by btSoftBody
- bool isScratched;
+ bool isScratched = false;
Ref<Mesh> soft_mesh;
- int simulation_precision;
- real_t total_mass;
- real_t linear_stiffness; // [0,1]
- real_t areaAngular_stiffness; // [0,1]
- real_t volume_stiffness; // [0,1]
- real_t pressure_coefficient; // [-inf,+inf]
- real_t pose_matching_coefficient; // [0,1]
- real_t damping_coefficient; // [0,1]
- real_t drag_coefficient; // [0,1]
+ int simulation_precision = 5;
+ real_t total_mass = 1.;
+ real_t linear_stiffness = 0.5; // [0,1]
+ real_t areaAngular_stiffness = 0.5; // [0,1]
+ real_t volume_stiffness = 0.5; // [0,1]
+ real_t pressure_coefficient = 0.; // [-inf,+inf]
+ real_t pose_matching_coefficient = 0.; // [0,1]
+ real_t damping_coefficient = 0.01; // [0,1]
+ real_t drag_coefficient = 0.; // [0,1]
Vector<int> pinned_nodes;
// Other property to add
diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp
index d49e635fd5..d7dd11d2a5 100644
--- a/modules/bullet/space_bullet.cpp
+++ b/modules/bullet/space_bullet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,8 +34,8 @@
#include "bullet_types_converter.h"
#include "bullet_utilities.h"
#include "constraint_bullet.h"
-#include "core/project_settings.h"
-#include "core/ustring.h"
+#include "core/config/project_settings.h"
+#include "core/string/ustring.h"
#include "godot_collision_configuration.h"
#include "godot_collision_dispatcher.h"
#include "rigid_body_bullet.h"
@@ -63,9 +63,9 @@ BulletPhysicsDirectSpaceState::BulletPhysicsDirectSpaceState(SpaceBullet *p_spac
space(p_space) {}
int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
-
- if (p_result_max <= 0)
+ if (p_result_max <= 0) {
return 0;
+ }
btVector3 bt_point;
G_TO_B(p_point, bt_point);
@@ -86,7 +86,6 @@ int BulletPhysicsDirectSpaceState::intersect_point(const Vector3 &p_point, Shape
}
bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, bool p_pick_ray) {
-
btVector3 btVec_from;
btVector3 btVec_to;
@@ -119,10 +118,12 @@ bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const V
}
int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
- if (p_result_max <= 0)
+ if (p_result_max <= 0) {
return 0;
+ }
ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
+ ERR_FAIL_COND_V(!shape, 0);
btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale_abs(), p_margin);
if (!btShape->isConvex()) {
@@ -152,7 +153,13 @@ int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Tra
}
bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) {
+ r_closest_safe = 0.0f;
+ r_closest_unsafe = 0.0f;
+ btVector3 bt_motion;
+ G_TO_B(p_motion, bt_motion);
+
ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
+ ERR_FAIL_COND_V(!shape, false);
btCollisionShape *btShape = shape->create_bt_shape(p_xform.basis.get_scale(), p_margin);
if (!btShape->isConvex()) {
@@ -162,9 +169,6 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf
}
btConvexShape *bt_convex_shape = static_cast<btConvexShape *>(btShape);
- btVector3 bt_motion;
- G_TO_B(p_motion, bt_motion);
-
btTransform bt_xform_from;
G_TO_B(p_xform, bt_xform_from);
UNSCALE_BT_BASIS(bt_xform_from);
@@ -172,15 +176,19 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf
btTransform bt_xform_to(bt_xform_from);
bt_xform_to.getOrigin() += bt_motion;
+ if ((bt_xform_to.getOrigin() - bt_xform_from.getOrigin()).fuzzyZero()) {
+ r_closest_safe = 1.0f;
+ r_closest_unsafe = 1.0f;
+ bulletdelete(btShape);
+ return true;
+ }
+
GodotClosestConvexResultCallback btResult(bt_xform_from.getOrigin(), bt_xform_to.getOrigin(), &p_exclude, p_collide_with_bodies, p_collide_with_areas);
btResult.m_collisionFilterGroup = 0;
btResult.m_collisionFilterMask = p_collision_mask;
space->dynamicsWorld->convexSweepTest(bt_convex_shape, bt_xform_from, bt_xform_to, btResult, space->dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration);
- r_closest_unsafe = 1.0;
- r_closest_safe = 1.0;
-
if (btResult.hasHit()) {
const btScalar l = bt_motion.length();
r_closest_unsafe = btResult.m_closestHitFraction;
@@ -196,6 +204,9 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf
r_info->collider_id = collision_object->get_instance_id();
r_info->shape = btResult.m_shapeId;
}
+ } else {
+ r_closest_safe = 1.0f;
+ r_closest_unsafe = 1.0f;
}
bulletdelete(bt_convex_shape);
@@ -204,16 +215,18 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf
/// Returns the list of contacts pairs in this order: Local contact, other body contact
bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
- if (p_result_max <= 0)
- return 0;
+ if (p_result_max <= 0) {
+ return false;
+ }
ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
+ ERR_FAIL_COND_V(!shape, false);
btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
if (!btShape->isConvex()) {
bulletdelete(btShape);
ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
- return 0;
+ return false;
}
btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
@@ -238,14 +251,14 @@ bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &
}
bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) {
-
ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape);
+ ERR_FAIL_COND_V(!shape, false);
btCollisionShape *btShape = shape->create_bt_shape(p_shape_xform.basis.get_scale_abs(), p_margin);
if (!btShape->isConvex()) {
bulletdelete(btShape);
ERR_PRINT("The shape is not a convex shape, then is not supported: shape type: " + itos(shape->get_type()));
- return 0;
+ return false;
}
btConvexShape *btConvex = static_cast<btConvexShape *>(btShape);
@@ -276,8 +289,7 @@ bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_sh
}
Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const {
-
- RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collisin_object(p_object);
+ RigidCollisionObjectBullet *rigid_object = space->get_physics_server()->get_rigid_collision_object(p_object);
ERR_FAIL_COND_V(!rigid_object, Vector3());
btVector3 out_closest_point(0, 0, 0);
@@ -320,33 +332,16 @@ Vector3 BulletPhysicsDirectSpaceState::get_closest_point_to_object_volume(RID p_
}
if (shapes_found) {
-
Vector3 out;
B_TO_G(out_closest_point, out);
return out;
} else {
-
// no shapes found, use distance to origin.
return rigid_object->get_transform().get_origin();
}
}
-SpaceBullet::SpaceBullet() :
- broadphase(nullptr),
- collisionConfiguration(nullptr),
- dispatcher(nullptr),
- solver(nullptr),
- dynamicsWorld(nullptr),
- soft_body_world_info(nullptr),
- ghostPairCallback(nullptr),
- godotFilterCallback(nullptr),
- gravityDirection(0, -1, 0),
- gravityMagnitude(10),
- linear_damp(0.0),
- angular_damp(0.0),
- contactDebugCount(0),
- delta_time(0.) {
-
+SpaceBullet::SpaceBullet() {
create_empty_world(GLOBAL_DEF("physics/3d/active_soft_world", true));
direct_access = memnew(BulletPhysicsDirectSpaceState(this));
}
@@ -484,11 +479,25 @@ void SpaceBullet::add_rigid_body(RigidBodyBullet *p_body) {
}
}
+void SpaceBullet::remove_rigid_body_constraints(RigidBodyBullet *p_body) {
+ btRigidBody *btBody = p_body->get_bt_rigid_body();
+
+ int constraints = btBody->getNumConstraintRefs();
+ if (constraints > 0) {
+ ERR_PRINT("A body connected to joints was removed.");
+ for (int i = 0; i < constraints; i++) {
+ dynamicsWorld->removeConstraint(btBody->getConstraintRef(i));
+ }
+ }
+}
+
void SpaceBullet::remove_rigid_body(RigidBodyBullet *p_body) {
+ btRigidBody *btBody = p_body->get_bt_rigid_body();
+
if (p_body->is_static()) {
- dynamicsWorld->removeCollisionObject(p_body->get_bt_rigid_body());
+ dynamicsWorld->removeCollisionObject(btBody);
} else {
- dynamicsWorld->removeRigidBody(p_body->get_bt_rigid_body());
+ dynamicsWorld->removeRigidBody(btBody);
}
}
@@ -549,12 +558,7 @@ void SpaceBullet::remove_all_collision_objects() {
}
}
-void onBulletPreTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
- static_cast<SpaceBullet *>(p_dynamicsWorld->getWorldUserInfo())->flush_queries();
-}
-
void onBulletTickCallback(btDynamicsWorld *p_dynamicsWorld, btScalar timeStep) {
-
const btCollisionObjectArray &colObjArray = p_dynamicsWorld->getCollisionObjectArray();
// Notify all Collision objects the collision checker is started
@@ -576,17 +580,14 @@ BulletPhysicsDirectSpaceState *SpaceBullet::get_direct_state() {
}
btScalar calculateGodotCombinedRestitution(const btCollisionObject *body0, const btCollisionObject *body1) {
-
return CLAMP(body0->getRestitution() + body1->getRestitution(), 0, 1);
}
btScalar calculateGodotCombinedFriction(const btCollisionObject *body0, const btCollisionObject *body1) {
-
return ABS(MIN(body0->getFriction(), body1->getFriction()));
}
void SpaceBullet::create_empty_world(bool p_create_soft_world) {
-
gjk_epa_pen_solver = bulletnew(btGjkEpaPenetrationDepthSolver);
gjk_simplex_solver = bulletnew(btVoronoiSimplexSolver);
@@ -624,7 +625,6 @@ void SpaceBullet::create_empty_world(bool p_create_soft_world) {
dynamicsWorld->setWorldUserInfo(this);
- dynamicsWorld->setInternalTickCallback(onBulletPreTickCallback, this, true);
dynamicsWorld->setInternalTickCallback(onBulletTickCallback, this, false);
dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(ghostPairCallback); // Setup ghost check
dynamicsWorld->getPairCache()->setOverlapFilterCallback(godotFilterCallback);
@@ -639,7 +639,6 @@ void SpaceBullet::create_empty_world(bool p_create_soft_world) {
}
void SpaceBullet::destroy_world() {
-
/// The world elements (like: Collision Objects, Constraints, Shapes) are managed by godot
dynamicsWorld->getBroadphase()->getOverlappingPairCache()->setInternalGhostPairCallback(nullptr);
@@ -663,7 +662,6 @@ void SpaceBullet::destroy_world() {
}
void SpaceBullet::check_ghost_overlaps() {
-
/// Algorithm support variables
btCollisionShape *other_body_shape;
btConvexShape *area_shape;
@@ -677,8 +675,9 @@ void SpaceBullet::check_ghost_overlaps() {
btVector3 area_scale(area->get_bt_body_scale());
- if (!area->is_monitoring())
+ if (!area->is_monitoring()) {
continue;
+ }
/// 1. Reset all states
for (i = area->overlappingObjects.size() - 1; 0 <= i; --i) {
@@ -696,7 +695,6 @@ void SpaceBullet::check_ghost_overlaps() {
// For each overlapping
for (i = ghostOverlaps.size() - 1; 0 <= i; --i) {
-
bool hasOverlap = false;
btCollisionObject *overlapped_bt_co = ghostOverlaps[i];
RigidCollisionObjectBullet *otherObject = static_cast<RigidCollisionObjectBullet *>(overlapped_bt_co->getUserPointer());
@@ -708,15 +706,18 @@ void SpaceBullet::check_ghost_overlaps() {
}
if (overlapped_bt_co->getUserIndex() == CollisionObjectBullet::TYPE_AREA) {
- if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable())
+ if (!static_cast<AreaBullet *>(overlapped_bt_co->getUserPointer())->is_monitorable()) {
continue;
- } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY)
+ }
+ } else if (overlapped_bt_co->getUserIndex() != CollisionObjectBullet::TYPE_RIGID_BODY) {
continue;
+ }
// For each area shape
for (y = area->get_shape_count() - 1; 0 <= y; --y) {
- if (!area->get_bt_shape(y)->isConvex())
+ if (!area->get_bt_shape(y)->isConvex()) {
continue;
+ }
btTransform area_shape_treansform(area->get_bt_shape_transform(y));
area_shape_treansform.getOrigin() *= area_scale;
@@ -729,7 +730,6 @@ void SpaceBullet::check_ghost_overlaps() {
// For each other object shape
for (z = otherObject->get_shape_count() - 1; 0 <= z; --z) {
-
other_body_shape = static_cast<btCollisionShape *>(otherObject->get_bt_shape(z));
btTransform other_shape_transform(otherObject->get_bt_shape_transform(z));
@@ -740,7 +740,6 @@ void SpaceBullet::check_ghost_overlaps() {
other_shape_transform;
if (other_body_shape->isConvex()) {
-
btPointCollector result;
btGjkPairDetector gjk_pair_detector(
area_shape,
@@ -755,14 +754,14 @@ void SpaceBullet::check_ghost_overlaps() {
}
} else {
-
btCollisionObjectWrapper obA(nullptr, area_shape, area->get_bt_ghost(), gjk_input.m_transformA, -1, y);
btCollisionObjectWrapper obB(nullptr, other_body_shape, otherObject->get_bt_collision_object(), gjk_input.m_transformB, -1, z);
btCollisionAlgorithm *algorithm = dispatcher->findAlgorithm(&obA, &obB, nullptr, BT_CONTACT_POINT_ALGORITHMS);
- if (!algorithm)
+ if (!algorithm) {
continue;
+ }
GodotDeepPenetrationContactResultCallback contactPointResult(&obA, &obB);
algorithm->processCollision(&obA, &obB, dynamicsWorld->getDispatchInfo(), &contactPointResult);
@@ -780,8 +779,9 @@ void SpaceBullet::check_ghost_overlaps() {
} // ~For each area shape
collision_found:
- if (!hasOverlap)
+ if (!hasOverlap) {
continue;
+ }
indexOverlap = area->find_overlapping_object(otherObject);
if (-1 == indexOverlap) {
@@ -838,24 +838,35 @@ void SpaceBullet::check_body_collision() {
pt.getDistance() <= 0.0 ||
bodyA->was_colliding(bodyB) ||
bodyB->was_colliding(bodyA)) {
-
Vector3 collisionWorldPosition;
Vector3 collisionLocalPosition;
Vector3 normalOnB;
float appliedImpulse = pt.m_appliedImpulse;
B_TO_G(pt.m_normalWorldOnB, normalOnB);
+ // The pt.m_index only contains the shape index when more than one collision shape is used
+ // and only if the collision shape is not a concave collision shape.
+ // A value of -1 in pt.m_partId indicates the pt.m_index is a shape index.
+ int shape_index_a = 0;
+ if (bodyA->get_shape_count() > 1 && pt.m_partId0 == -1) {
+ shape_index_a = pt.m_index0;
+ }
+ int shape_index_b = 0;
+ if (bodyB->get_shape_count() > 1 && pt.m_partId1 == -1) {
+ shape_index_b = pt.m_index1;
+ }
+
if (bodyA->can_add_collision()) {
B_TO_G(pt.getPositionWorldOnB(), collisionWorldPosition);
/// pt.m_localPointB Doesn't report the exact point in local space
B_TO_G(pt.getPositionWorldOnB() - contactManifold->getBody1()->getWorldTransform().getOrigin(), collisionLocalPosition);
- bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, pt.m_index1, pt.m_index0);
+ bodyA->add_collision_object(bodyB, collisionWorldPosition, collisionLocalPosition, normalOnB, appliedImpulse, shape_index_b, shape_index_a);
}
if (bodyB->can_add_collision()) {
B_TO_G(pt.getPositionWorldOnA(), collisionWorldPosition);
/// pt.m_localPointA Doesn't report the exact point in local space
B_TO_G(pt.getPositionWorldOnA() - contactManifold->getBody0()->getWorldTransform().getOrigin(), collisionLocalPosition);
- bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, pt.m_index0, pt.m_index1);
+ bodyB->add_collision_object(bodyA, collisionWorldPosition, collisionLocalPosition, normalOnB * -1, appliedImpulse * -1, shape_index_a, shape_index_b);
}
#ifdef DEBUG_ENABLED
@@ -898,7 +909,6 @@ static Ref<StandardMaterial3D> blue_mat;
#endif
bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes) {
-
#if debug_test_motion
/// Yes I know this is not good, but I've used it as fast debugging hack.
/// I'm leaving it here just for speedup the other eventual debugs
@@ -908,8 +918,8 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f
SceneTree::get_singleton()->get_current_scene()->add_child(motionVec);
SceneTree::get_singleton()->get_current_scene()->add_child(normalLine);
- motionVec->set_as_toplevel(true);
- normalLine->set_as_toplevel(true);
+ motionVec->set_as_top_level(true);
+ normalLine->set_as_top_level(true);
red_mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
red_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
@@ -963,7 +973,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f
motionVec->end();
#endif
- for (int shIndex = 0; shIndex < shape_count && !motion.fuzzyZero(); ++shIndex) {
+ for (int shIndex = 0; shIndex < shape_count; ++shIndex) {
if (p_body->is_shape_disabled(shIndex)) {
continue;
}
@@ -985,6 +995,11 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f
btTransform shape_world_to(shape_world_from);
shape_world_to.getOrigin() += motion;
+ if ((shape_world_to.getOrigin() - shape_world_from.getOrigin()).fuzzyZero()) {
+ motion = btVector3(0, 0, 0);
+ break;
+ }
+
GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia);
btResult.m_collisionFilterGroup = p_body->get_collision_layer();
btResult.m_collisionFilterMask = p_body->get_collision_mask();
@@ -1015,7 +1030,6 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f
B_TO_G(motion + initial_recover_motion + __rec, r_result->motion);
if (has_penetration) {
-
const btRigidBody *btRigid = static_cast<const btRigidBody *>(r_recover_result.other_collision_object);
CollisionObjectBullet *collisionObject = static_cast<CollisionObjectBullet *>(btRigid->getUserPointer());
@@ -1049,7 +1063,6 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f
}
int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, float p_margin) {
-
btTransform body_transform;
G_TO_B(p_transform, body_transform);
UNSCALE_BT_BASIS(body_transform);
@@ -1114,14 +1127,12 @@ public:
self_collision_object(p_self_collision_object),
collision_layer(p_collision_layer),
collision_mask(p_collision_mask) {
-
bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max);
}
virtual ~RecoverPenetrationBroadPhaseCallback() {}
virtual bool process(const btBroadphaseProxy *proxy) {
-
btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject);
if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) {
if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) {
@@ -1165,13 +1176,11 @@ public:
};
bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
-
// Calculate the cumulative AABB of all shapes of the kinematic body
btVector3 aabb_min, aabb_max;
bool shapes_found = false;
for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
-
const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
if (!kin_shape.is_active()) {
continue;
@@ -1216,7 +1225,6 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran
// Perform narrowphase per shape
for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
-
const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
if (!kin_shape.is_active()) {
continue;
@@ -1235,8 +1243,9 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran
if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
otherObject->activate(); // Force activation of hitten rigid, soft body
continue;
- } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
+ } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
continue;
+ }
if (otherObject->getCollisionShape()->isCompound()) {
const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
@@ -1245,23 +1254,19 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran
if (cs->getChildShape(shape_idx)->isConvex()) {
if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(cs->getChildShape(shape_idx)), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
-
penetration = true;
}
} else {
if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
-
penetration = true;
}
}
} else if (otherObject->getCollisionShape()->isConvex()) { /// Execute GJK test against object shape
if (RFP_convex_convex_test(kin_shape.shape, static_cast<const btConvexShape *>(otherObject->getCollisionShape()), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
-
penetration = true;
}
} else {
if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, r_recover_result)) {
-
penetration = true;
}
}
@@ -1272,7 +1277,6 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran
}
bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
-
// Initialize GJK input
btGjkPairDetector::ClosestPointInput gjk_input;
gjk_input.m_transformA = p_transformA;
@@ -1303,7 +1307,6 @@ bool SpaceBullet::RFP_convex_convex_test(const btConvexShape *p_shapeA, const bt
}
bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btCollisionShape *p_shapeB, btCollisionObject *p_objectA, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) {
-
/// Contact test
btTransform tA(p_transformA);
@@ -1340,7 +1343,6 @@ bool SpaceBullet::RFP_convex_world_test(const btConvexShape *p_shapeA, const btC
}
int SpaceBullet::add_separation_result(PhysicsServer3D::SeparationResult *r_result, const SpaceBullet::RecoverResult &p_recover_result, int p_shape_id, const btCollisionObject *p_other_object) const {
-
// optimize results (ignore non-colliding)
if (p_recover_result.penetration_distance < 0.0) {
const btRigidBody *btRigid = static_cast<const btRigidBody *>(p_other_object);
@@ -1362,13 +1364,11 @@ int SpaceBullet::add_separation_result(PhysicsServer3D::SeparationResult *r_resu
}
int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, int p_result_max, btVector3 &r_delta_recover_movement, PhysicsServer3D::SeparationResult *r_results) {
-
// Calculate the cumulative AABB of all shapes of the kinematic body
btVector3 aabb_min, aabb_max;
bool shapes_found = false;
for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
-
const RigidBodyBullet::KinematicShape &kin_shape(p_body->get_kinematic_utilities()->shapes[kinIndex]);
if (!kin_shape.is_active()) {
continue;
@@ -1412,7 +1412,6 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT
// Perform narrowphase per shape
for (int kinIndex = p_body->get_kinematic_utilities()->shapes.size() - 1; 0 <= kinIndex; --kinIndex) {
-
if (ray_count >= p_result_max) {
break;
}
@@ -1434,8 +1433,9 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT
if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) {
otherObject->activate(); // Force activation of hitten rigid, soft body
continue;
- } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object()))
+ } else if (!p_body->get_bt_collision_object()->checkCollideWith(otherObject) || !otherObject->checkCollideWith(p_body->get_bt_collision_object())) {
continue;
+ }
if (otherObject->getCollisionShape()->isCompound()) {
const btCompoundShape *cs = static_cast<const btCompoundShape *>(otherObject->getCollisionShape());
@@ -1444,14 +1444,11 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT
RecoverResult recover_result;
if (RFP_convex_world_test(kin_shape.shape, cs->getChildShape(shape_idx), p_body->get_bt_collision_object(), otherObject, kinIndex, shape_idx, shape_transform, otherObject->getWorldTransform() * cs->getChildTransform(shape_idx), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
-
ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
}
} else {
-
RecoverResult recover_result;
if (RFP_convex_world_test(kin_shape.shape, otherObject->getCollisionShape(), p_body->get_bt_collision_object(), otherObject, kinIndex, 0, shape_transform, otherObject->getWorldTransform(), p_recover_movement_scale, r_delta_recover_movement, &recover_result)) {
-
ray_count = add_separation_result(&r_results[ray_count], recover_result, kinIndex, otherObject);
}
}
diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h
index 3d4a2aeceb..0f2482e551 100644
--- a/modules/bullet/space_bullet.h
+++ b/modules/bullet/space_bullet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef SPACE_BULLET_H
#define SPACE_BULLET_H
-#include "core/variant.h"
-#include "core/vector.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
#include "godot_result_callbacks.h"
#include "rid_bullet.h"
#include "servers/physics_server_3d.h"
@@ -76,46 +76,45 @@ private:
public:
BulletPhysicsDirectSpaceState(SpaceBullet *p_space);
- virtual int intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false);
- virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, bool p_pick_ray = false);
- virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false);
- virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr);
+ virtual int intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override;
+ virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, bool p_pick_ray = false) override;
+ virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override;
+ virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &r_closest_safe, float &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr) override;
/// Returns the list of contacts pairs in this order: Local contact, other body contact
- virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false);
- virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false);
- virtual Vector3 get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const;
+ virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override;
+ virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override;
+ virtual Vector3 get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const override;
};
class SpaceBullet : public RIDBullet {
-
friend class AreaBullet;
friend void onBulletTickCallback(btDynamicsWorld *world, btScalar timeStep);
friend class BulletPhysicsDirectSpaceState;
- btBroadphaseInterface *broadphase;
- btDefaultCollisionConfiguration *collisionConfiguration;
- btCollisionDispatcher *dispatcher;
- btConstraintSolver *solver;
- btDiscreteDynamicsWorld *dynamicsWorld;
- btSoftBodyWorldInfo *soft_body_world_info;
- btGhostPairCallback *ghostPairCallback;
- GodotFilterCallback *godotFilterCallback;
+ btBroadphaseInterface *broadphase = nullptr;
+ btDefaultCollisionConfiguration *collisionConfiguration = nullptr;
+ btCollisionDispatcher *dispatcher = nullptr;
+ btConstraintSolver *solver = nullptr;
+ btDiscreteDynamicsWorld *dynamicsWorld = nullptr;
+ btSoftBodyWorldInfo *soft_body_world_info = nullptr;
+ btGhostPairCallback *ghostPairCallback = nullptr;
+ GodotFilterCallback *godotFilterCallback = nullptr;
btGjkEpaPenetrationDepthSolver *gjk_epa_pen_solver;
btVoronoiSimplexSolver *gjk_simplex_solver;
BulletPhysicsDirectSpaceState *direct_access;
- Vector3 gravityDirection;
- real_t gravityMagnitude;
+ Vector3 gravityDirection = Vector3(0, -1, 0);
+ real_t gravityMagnitude = 10;
- real_t linear_damp;
- real_t angular_damp;
+ real_t linear_damp = 0.0;
+ real_t angular_damp = 0.0;
Vector<AreaBullet *> areas;
Vector<Vector3> contactDebug;
- int contactDebugCount;
- real_t delta_time;
+ int contactDebugCount = 0;
+ real_t delta_time = 0.;
public:
SpaceBullet();
@@ -125,9 +124,12 @@ public:
real_t get_delta_time() { return delta_time; }
void step(real_t p_delta_time);
- _FORCE_INLINE_ btBroadphaseInterface *get_broadphase() { return broadphase; }
- _FORCE_INLINE_ btCollisionDispatcher *get_dispatcher() { return dispatcher; }
- _FORCE_INLINE_ btSoftBodyWorldInfo *get_soft_body_world_info() { return soft_body_world_info; }
+ _FORCE_INLINE_ btBroadphaseInterface *get_broadphase() const { return broadphase; }
+ _FORCE_INLINE_ btDefaultCollisionConfiguration *get_collision_configuration() const { return collisionConfiguration; }
+ _FORCE_INLINE_ btCollisionDispatcher *get_dispatcher() const { return dispatcher; }
+ _FORCE_INLINE_ btConstraintSolver *get_solver() const { return solver; }
+ _FORCE_INLINE_ btDiscreteDynamicsWorld *get_dynamic_world() const { return dynamicsWorld; }
+ _FORCE_INLINE_ btSoftBodyWorldInfo *get_soft_body_world_info() const { return soft_body_world_info; }
_FORCE_INLINE_ bool is_using_soft_world() { return soft_body_world_info; }
/// Used to set some parameters to Bullet world
@@ -149,6 +151,7 @@ public:
void reload_collision_filters(AreaBullet *p_area);
void add_rigid_body(RigidBodyBullet *p_body);
+ void remove_rigid_body_constraints(RigidBodyBullet *p_body);
void remove_rigid_body(RigidBodyBullet *p_body);
void reload_collision_filters(RigidBodyBullet *p_body);
@@ -165,12 +168,14 @@ public:
BulletPhysicsDirectSpaceState *get_direct_state();
void set_debug_contacts(int p_amount) { contactDebug.resize(p_amount); }
- _FORCE_INLINE_ bool is_debugging_contacts() const { return !contactDebug.empty(); }
+ _FORCE_INLINE_ bool is_debugging_contacts() const { return !contactDebug.is_empty(); }
_FORCE_INLINE_ void reset_debug_contact_count() {
contactDebugCount = 0;
}
_FORCE_INLINE_ void add_debug_contact(const Vector3 &p_contact) {
- if (contactDebugCount < contactDebug.size()) contactDebug.write[contactDebugCount++] = p_contact;
+ if (contactDebugCount < contactDebug.size()) {
+ contactDebug.write[contactDebugCount++] = p_contact;
+ }
}
_FORCE_INLINE_ Vector<Vector3> get_debug_contacts() { return contactDebug; }
_FORCE_INLINE_ int get_debug_contact_count() { return contactDebugCount; }
@@ -193,22 +198,15 @@ private:
void check_body_collision();
struct RecoverResult {
- bool hasPenetration;
- btVector3 normal;
- btVector3 pointWorld;
- btScalar penetration_distance; // Negative mean penetration
- int other_compound_shape_index;
- const btCollisionObject *other_collision_object;
- int local_shape_most_recovered;
-
- RecoverResult() :
- hasPenetration(false),
- normal(0, 0, 0),
- pointWorld(0, 0, 0),
- penetration_distance(1e20),
- other_compound_shape_index(0),
- other_collision_object(nullptr),
- local_shape_most_recovered(0) {}
+ bool hasPenetration = false;
+ btVector3 normal = btVector3(0, 0, 0);
+ btVector3 pointWorld = btVector3(0, 0, 0);
+ btScalar penetration_distance = 1e20; // Negative mean penetration
+ int other_compound_shape_index = 0;
+ const btCollisionObject *other_collision_object = nullptr;
+ int local_shape_most_recovered = 0;
+
+ RecoverResult() {}
};
bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr);
diff --git a/modules/camera/SCsub b/modules/camera/SCsub
index 63c4e9fbab..de97724d09 100644
--- a/modules/camera/SCsub
+++ b/modules/camera/SCsub
@@ -5,14 +5,7 @@ Import("env_modules")
env_camera = env_modules.Clone()
-if env["platform"] == "iphone":
- # (iOS) Build as separate static library
- modules_sources = []
- env_camera.add_source_files(modules_sources, "register_types.cpp")
- env_camera.add_source_files(modules_sources, "camera_ios.mm")
- mod_lib = env_modules.add_library("#bin/libgodot_camera_module" + env["LIBSUFFIX"], modules_sources)
-
-elif env["platform"] == "windows":
+if env["platform"] == "windows":
env_camera.add_source_files(env.modules_sources, "register_types.cpp")
env_camera.add_source_files(env.modules_sources, "camera_win.cpp")
diff --git a/modules/camera/camera_osx.h b/modules/camera/camera_osx.h
index a07b83c6af..964b7c1edc 100644
--- a/modules/camera/camera_osx.h
+++ b/modules/camera/camera_osx.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/camera/camera_osx.mm b/modules/camera/camera_osx.mm
index 9a72174723..3d2053ad23 100644
--- a/modules/camera/camera_osx.mm
+++ b/modules/camera/camera_osx.mm
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -313,7 +313,12 @@ MyDeviceNotifications *device_notifications = nil;
// CameraOSX - Subclass for our camera server on OSX
void CameraOSX::update_feeds() {
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101500
+ AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeExternalUnknown, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
+ NSArray *devices = session.devices;
+#else
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
+#endif
// remove devices that are gone..
for (int i = feeds.size() - 1; i >= 0; i--) {
@@ -325,7 +330,6 @@ void CameraOSX::update_feeds() {
};
};
- // add new devices..
for (AVCaptureDevice *device in devices) {
bool found = false;
for (int i = 0; i < feeds.size() && !found; i++) {
diff --git a/modules/camera/camera_win.cpp b/modules/camera/camera_win.cpp
index 875f0b26bc..226a642dcf 100644
--- a/modules/camera/camera_win.cpp
+++ b/modules/camera/camera_win.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -53,9 +53,9 @@ public:
void deactivate_feed();
};
-CameraFeedWindows::CameraFeedWindows(){
+CameraFeedWindows::CameraFeedWindows() {
///@TODO implement this, should store information about our available camera
-};
+}
CameraFeedWindows::~CameraFeedWindows() {
// make sure we stop recording if we are!
@@ -75,16 +75,16 @@ bool CameraFeedWindows::activate_feed() {
///@TODO we should probably have a callback method here that is being called by the
// camera API which provides frames and call back into the CameraServer to update our texture
-void CameraFeedWindows::deactivate_feed(){
+void CameraFeedWindows::deactivate_feed() {
///@TODO this should deactivate our camera and stop the process of capturing frames
-};
+}
//////////////////////////////////////////////////////////////////////////
// CameraWindows - Subclass for our camera server on windows
-void CameraWindows::add_active_cameras(){
+void CameraWindows::add_active_cameras() {
///@TODO scan through any active cameras and create CameraFeedWindows objects for them
-};
+}
CameraWindows::CameraWindows() {
// Find cameras active right now
@@ -92,7 +92,3 @@ CameraWindows::CameraWindows() {
// need to add something that will react to devices being connected/removed...
};
-
-CameraWindows::~CameraWindows(){
-
-};
diff --git a/modules/camera/camera_win.h b/modules/camera/camera_win.h
index 39a1b0b86f..671e7d5beb 100644
--- a/modules/camera/camera_win.h
+++ b/modules/camera/camera_win.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,7 +40,7 @@ private:
public:
CameraWindows();
- ~CameraWindows();
+ ~CameraWindows() {}
};
#endif /* CAMERAWIN_H */
diff --git a/modules/camera/config.py b/modules/camera/config.py
index 87d7542741..8a22751aa7 100644
--- a/modules/camera/config.py
+++ b/modules/camera/config.py
@@ -1,5 +1,5 @@
def can_build(env, platform):
- return platform == "iphone" or platform == "osx" or platform == "windows"
+ return platform == "osx" or platform == "windows"
def configure(env):
diff --git a/modules/camera/register_types.cpp b/modules/camera/register_types.cpp
index 3b6c916914..0d33ff9ddc 100644
--- a/modules/camera/register_types.cpp
+++ b/modules/camera/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,9 +33,6 @@
#if defined(WINDOWS_ENABLED)
#include "camera_win.h"
#endif
-#if defined(IPHONE_ENABLED)
-#include "camera_ios.h"
-#endif
#if defined(OSX_ENABLED)
#include "camera_osx.h"
#endif
@@ -44,9 +41,6 @@ void register_camera_types() {
#if defined(WINDOWS_ENABLED)
CameraServer::make_default<CameraWindows>();
#endif
-#if defined(IPHONE_ENABLED)
- CameraServer::make_default<CameraIOS>();
-#endif
#if defined(OSX_ENABLED)
CameraServer::make_default<CameraOSX>();
#endif
diff --git a/modules/camera/register_types.h b/modules/camera/register_types.h
index f2753cb6d7..0ae9aa2c0b 100644
--- a/modules/camera/register_types.h
+++ b/modules/camera/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,5 +28,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef CAMERA_REGISTER_TYPES_H
+#define CAMERA_REGISTER_TYPES_H
+
void register_camera_types();
void unregister_camera_types();
+
+#endif // CAMERA_REGISTER_TYPES_H
diff --git a/modules/camera_iphone/SCsub b/modules/camera_iphone/SCsub
new file mode 100644
index 0000000000..0a37d9a6f5
--- /dev/null
+++ b/modules/camera_iphone/SCsub
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_camera = env_modules.Clone()
+
+# (iOS) Enable module support
+env_camera.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])
+
+# (iOS) Build as separate static library
+modules_sources = []
+env_camera.add_source_files(modules_sources, "*.cpp")
+env_camera.add_source_files(modules_sources, "*.mm")
+mod_lib = env_modules.add_library("#bin/libgodot_camera_module" + env["LIBSUFFIX"], modules_sources)
diff --git a/modules/camera_iphone/camera.gdip b/modules/camera_iphone/camera.gdip
new file mode 100644
index 0000000000..09017b8d27
--- /dev/null
+++ b/modules/camera_iphone/camera.gdip
@@ -0,0 +1,18 @@
+[config]
+name="Camera"
+binary="camera_lib.a"
+
+initialization="register_camera_types"
+deinitialization="unregister_camera_types"
+
+[dependencies]
+linked=[]
+embedded=[]
+system=["AVFoundation.framework"]
+
+capabilities=[]
+
+files=[]
+
+[plist]
+NSCameraUsageDescription="Device camera is used for some functionality"
diff --git a/modules/camera/camera_ios.h b/modules/camera_iphone/camera_ios.h
index 7da43e4851..0566457a0f 100644
--- a/modules/camera/camera_ios.h
+++ b/modules/camera_iphone/camera_ios.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/camera/camera_ios.mm b/modules/camera_iphone/camera_ios.mm
index f01135f251..39568fbd6c 100644
--- a/modules/camera/camera_ios.mm
+++ b/modules/camera_iphone/camera_ios.mm
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -124,18 +124,12 @@
if (output) {
[self removeOutput:output];
[output setSampleBufferDelegate:nil queue:NULL];
- [output release];
output = nil;
}
[self commitConfiguration];
}
-- (void)dealloc {
- // bye bye
- [super dealloc];
-}
-
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
// This gets called every time our camera has a new image for us to process.
// May need to investigate in a way to throttle this if we get more images then we're rendering frames..
@@ -158,25 +152,31 @@
} else if (dataCbCr == NULL) {
print_line("Couldn't access CbCr pixel buffer data");
} else {
- UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
+ UIInterfaceOrientation orientation = UIInterfaceOrientationUnknown;
+
+ if (@available(iOS 13, *)) {
+ orientation = [UIApplication sharedApplication].delegate.window.windowScene.interfaceOrientation;
+#if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
+ } else {
+ orientation = [[UIApplication sharedApplication] statusBarOrientation];
+#endif
+ }
+
Ref<Image> img[2];
{
// do Y
- int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
- int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
- int _bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
+ size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
+ size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
if ((width[0] != new_width) || (height[0] != new_height)) {
- // printf("Camera Y plane %i, %i - %i\n", new_width, new_height, bytes_per_row);
-
width[0] = new_width;
height[0] = new_height;
img_data[0].resize(new_width * new_height);
}
uint8_t *w = img_data[0].ptrw();
- memcpy(w.ptr(), dataY, new_width * new_height);
+ memcpy(w, dataY, new_width * new_height);
img[0].instance();
img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
@@ -184,20 +184,17 @@
{
// do CbCr
- int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
- int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
- int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 1);
+ size_t new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
+ size_t new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
if ((width[1] != new_width) || (height[1] != new_height)) {
- // printf("Camera CbCr plane %i, %i - %i\n", new_width, new_height, bytes_per_row);
-
width[1] = new_width;
height[1] = new_height;
img_data[1].resize(2 * new_width * new_height);
}
uint8_t *w = img_data[1].ptrw();
- memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height);
+ memcpy(w, dataCbCr, 2 * new_width * new_height);
///TODO GLES2 doesn't support FORMAT_RG8, need to do some form of conversion
img[1].instance();
@@ -269,7 +266,6 @@ CameraFeedIOS::CameraFeedIOS() {
void CameraFeedIOS::set_device(AVCaptureDevice *p_device) {
device = p_device;
- [device retain];
// get some info
NSString *device_name = p_device.localizedName;
@@ -283,14 +279,12 @@ void CameraFeedIOS::set_device(AVCaptureDevice *p_device) {
};
CameraFeedIOS::~CameraFeedIOS() {
- if (capture_session != NULL) {
- [capture_session release];
- capture_session = NULL;
+ if (capture_session) {
+ capture_session = nil;
};
- if (device != NULL) {
- [device release];
- device = NULL;
+ if (device) {
+ device = nil;
};
};
@@ -309,8 +303,7 @@ void CameraFeedIOS::deactivate_feed() {
// end camera capture if we have one
if (capture_session) {
[capture_session cleanup];
- [capture_session release];
- capture_session = NULL;
+ capture_session = nil;
};
};
@@ -344,8 +337,6 @@ void CameraFeedIOS::deactivate_feed() {
// remove notifications
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil];
-
- [super dealloc];
}
@end
@@ -359,41 +350,59 @@ void CameraIOS::update_feeds() {
// this way of doing things is deprecated but still works,
// rewrite to using AVCaptureDeviceDiscoverySession
- AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:[NSArray arrayWithObjects:AVCaptureDeviceTypeBuiltInTelephotoCamera, AVCaptureDeviceTypeBuiltInDualCamera, AVCaptureDeviceTypeBuiltInTrueDepthCamera, AVCaptureDeviceTypeBuiltInWideAngleCamera, nil] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
+ NSMutableArray *deviceTypes = [NSMutableArray array];
- // remove devices that are gone..
- for (int i = feeds.size() - 1; i >= 0; i--) {
- Ref<CameraFeedIOS> feed(feeds[i]);
+ if (@available(iOS 10, *)) {
+ [deviceTypes addObject:AVCaptureDeviceTypeBuiltInWideAngleCamera];
+ [deviceTypes addObject:AVCaptureDeviceTypeBuiltInTelephotoCamera];
- if (feed.is_null()) {
- // feed not managed by us
- } else if (![session.devices containsObject:feed->get_device()]) {
- // remove it from our array, this will also destroy it ;)
- remove_feed(feed);
- };
- };
+ if (@available(iOS 10.2, *)) {
+ [deviceTypes addObject:AVCaptureDeviceTypeBuiltInDualCamera];
+ }
+
+ if (@available(iOS 11.1, *)) {
+ [deviceTypes addObject:AVCaptureDeviceTypeBuiltInTrueDepthCamera];
+ }
- // add new devices..
- for (AVCaptureDevice *device in session.devices) {
- bool found = false;
+ AVCaptureDeviceDiscoverySession *session = [AVCaptureDeviceDiscoverySession
+ discoverySessionWithDeviceTypes:deviceTypes
+ mediaType:AVMediaTypeVideo
+ position:AVCaptureDevicePositionUnspecified];
- for (int i = 0; i < feeds.size() && !found; i++) {
+ // remove devices that are gone..
+ for (int i = feeds.size() - 1; i >= 0; i--) {
Ref<CameraFeedIOS> feed(feeds[i]);
if (feed.is_null()) {
// feed not managed by us
- } else if (feed->get_device() == device) {
- found = true;
+ } else if (![session.devices containsObject:feed->get_device()]) {
+ // remove it from our array, this will also destroy it ;)
+ remove_feed(feed);
};
};
- if (!found) {
- Ref<CameraFeedIOS> newfeed;
- newfeed.instance();
- newfeed->set_device(device);
- add_feed(newfeed);
+ // add new devices..
+ for (AVCaptureDevice *device in session.devices) {
+ bool found = false;
+
+ for (int i = 0; i < feeds.size() && !found; i++) {
+ Ref<CameraFeedIOS> feed(feeds[i]);
+
+ if (feed.is_null()) {
+ // feed not managed by us
+ } else if (feed->get_device() == device) {
+ found = true;
+ };
+ };
+
+ if (!found) {
+ Ref<CameraFeedIOS> newfeed;
+ newfeed.instance();
+ newfeed->set_device(device);
+ add_feed(newfeed);
+ };
};
- };
+ }
};
CameraIOS::CameraIOS() {
@@ -432,5 +441,5 @@ CameraIOS::CameraIOS() {
};
CameraIOS::~CameraIOS() {
- [device_notifications release];
+ device_notifications = nil;
};
diff --git a/modules/camera_iphone/camera_module.cpp b/modules/camera_iphone/camera_module.cpp
new file mode 100644
index 0000000000..7ea035892e
--- /dev/null
+++ b/modules/camera_iphone/camera_module.cpp
@@ -0,0 +1,40 @@
+/*************************************************************************/
+/* camera_module.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_module.h"
+
+#include "camera_ios.h"
+
+void register_camera_types() {
+ CameraServer::make_default<CameraIOS>();
+}
+
+void unregister_camera_types() {
+}
diff --git a/modules/camera_iphone/camera_module.h b/modules/camera_iphone/camera_module.h
new file mode 100644
index 0000000000..5a94d8b529
--- /dev/null
+++ b/modules/camera_iphone/camera_module.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* camera_module.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+void register_camera_types();
+void unregister_camera_types();
diff --git a/modules/camera_iphone/config.py b/modules/camera_iphone/config.py
new file mode 100644
index 0000000000..e68603fc93
--- /dev/null
+++ b/modules/camera_iphone/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return platform == "iphone"
+
+
+def configure(env):
+ pass
diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp
index 6714db76bb..f0a2f17ba9 100644
--- a/modules/csg/csg.cpp
+++ b/modules/csg/csg.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,22 +30,21 @@
#include "csg.h"
-#include "core/math/geometry.h"
+#include "core/math/geometry_2d.h"
#include "core/math/math_funcs.h"
-#include "core/sort_array.h"
+#include "core/templates/sort_array.h"
// Static helper functions.
inline static bool is_snapable(const Vector3 &p_point1, const Vector3 &p_point2, real_t p_distance) {
-
return (p_point1 - p_point2).length_squared() < p_distance * p_distance;
}
inline static Vector2 interpolate_segment_uv(const Vector2 p_segement_points[2], const Vector2 p_uvs[2], const Vector2 &p_interpolation_point) {
-
float segment_length = (p_segement_points[1] - p_segement_points[0]).length();
- if (segment_length < CMP_EPSILON)
+ if (segment_length < CMP_EPSILON) {
return p_uvs[0];
+ }
float distance = (p_interpolation_point - p_segement_points[0]).length();
float fraction = distance / segment_length;
@@ -54,13 +53,15 @@ inline static Vector2 interpolate_segment_uv(const Vector2 p_segement_points[2],
}
inline static Vector2 interpolate_triangle_uv(const Vector2 p_vertices[3], const Vector2 p_uvs[3], const Vector2 &p_interpolation_point) {
-
- if (p_interpolation_point.distance_squared_to(p_vertices[0]) < CMP_EPSILON2)
+ if (p_interpolation_point.distance_squared_to(p_vertices[0]) < CMP_EPSILON2) {
return p_uvs[0];
- if (p_interpolation_point.distance_squared_to(p_vertices[1]) < CMP_EPSILON2)
+ }
+ if (p_interpolation_point.distance_squared_to(p_vertices[1]) < CMP_EPSILON2) {
return p_uvs[1];
- if (p_interpolation_point.distance_squared_to(p_vertices[2]) < CMP_EPSILON2)
+ }
+ if (p_interpolation_point.distance_squared_to(p_vertices[2]) < CMP_EPSILON2) {
return p_uvs[2];
+ }
Vector2 edge1 = p_vertices[1] - p_vertices[0];
Vector2 edge2 = p_vertices[2] - p_vertices[0];
@@ -72,8 +73,9 @@ inline static Vector2 interpolate_triangle_uv(const Vector2 p_vertices[3], const
float inter_on_edge1 = interpolation.dot(edge1);
float inter_on_edge2 = interpolation.dot(edge2);
float scale = (edge1_on_edge1 * edge2_on_edge2 - edge1_on_edge2 * edge1_on_edge2);
- if (scale == 0)
+ if (scale == 0) {
return p_uvs[0];
+ }
float v = (edge2_on_edge2 * inter_on_edge1 - edge1_on_edge2 * inter_on_edge2) / scale;
float w = (edge1_on_edge1 * inter_on_edge2 - edge1_on_edge2 * inter_on_edge1) / scale;
@@ -83,25 +85,27 @@ inline static Vector2 interpolate_triangle_uv(const Vector2 p_vertices[3], const
}
static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 p_vertices[3], float p_tolerance, Vector3 &r_intersection_point) {
-
Vector3 edge1 = p_vertices[1] - p_vertices[0];
Vector3 edge2 = p_vertices[2] - p_vertices[0];
Vector3 h = p_dir.cross(edge2);
real_t a = edge1.dot(h);
// Check if ray is parallel to triangle.
- if (Math::is_zero_approx(a))
+ if (Math::is_zero_approx(a)) {
return false;
+ }
real_t f = 1.0 / a;
Vector3 s = p_from - p_vertices[0];
real_t u = f * s.dot(h);
- if (u < 0.0 - p_tolerance || u > 1.0 + p_tolerance)
+ if (u < 0.0 - p_tolerance || u > 1.0 + p_tolerance) {
return false;
+ }
Vector3 q = s.cross(edge1);
real_t v = f * p_dir.dot(q);
- if (v < 0.0 - p_tolerance || u + v > 1.0 + p_tolerance)
+ if (v < 0.0 - p_tolerance || u + v > 1.0 + p_tolerance) {
return false;
+ }
// Ray intersects triangle.
// Calculate distance.
@@ -110,12 +114,12 @@ static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3
if (t >= p_tolerance) {
r_intersection_point = p_from + p_dir * t;
return true;
- } else
+ } else {
return false;
+ }
}
inline bool is_point_in_triangle(const Vector3 &p_point, const Vector3 p_vertices[3], int p_shifted = 0) {
-
real_t det = p_vertices[0].dot(p_vertices[1].cross(p_vertices[2]));
// If determinant is, zero try shift the triangle and the point.
@@ -138,24 +142,36 @@ inline bool is_point_in_triangle(const Vector3 &p_point, const Vector3 p_vertice
lambda[2] = p_vertices[0].cross(p_vertices[1]).dot(p_point) / det;
// Point is in the plane if all lambdas sum to 1.
- if (!Math::is_equal_approx(lambda[0] + lambda[1] + lambda[2], 1)) return false;
+ if (!Math::is_equal_approx(lambda[0] + lambda[1] + lambda[2], 1)) {
+ return false;
+ }
// Point is inside the triangle if all lambdas are positive.
- if (lambda[0] < 0 || lambda[1] < 0 || lambda[2] < 0) return false;
+ if (lambda[0] < 0 || lambda[1] < 0 || lambda[2] < 0) {
+ return false;
+ }
return true;
}
-inline static bool are_segements_parallel(const Vector2 p_segment1_points[2], const Vector2 p_segment2_points[2], float p_vertex_snap2) {
+inline static bool is_triangle_degenerate(const Vector2 p_vertices[3], real_t p_vertex_snap2) {
+ real_t det = p_vertices[0].x * p_vertices[1].y - p_vertices[0].x * p_vertices[2].y +
+ p_vertices[0].y * p_vertices[2].x - p_vertices[0].y * p_vertices[1].x +
+ p_vertices[1].x * p_vertices[2].y - p_vertices[1].y * p_vertices[2].x;
+ return det < p_vertex_snap2;
+}
+
+inline static bool are_segements_parallel(const Vector2 p_segment1_points[2], const Vector2 p_segment2_points[2], float p_vertex_snap2) {
Vector2 segment1 = p_segment1_points[1] - p_segment1_points[0];
Vector2 segment2 = p_segment2_points[1] - p_segment2_points[0];
real_t segment1_length2 = segment1.dot(segment1);
real_t segment2_length2 = segment2.dot(segment2);
real_t segment_onto_segment = segment2.dot(segment1);
- if (segment1_length2 < p_vertex_snap2 || segment2_length2 < p_vertex_snap2)
+ if (segment1_length2 < p_vertex_snap2 || segment2_length2 < p_vertex_snap2) {
return true;
+ }
real_t max_separation2;
if (segment1_length2 > segment2_length2) {
@@ -170,7 +186,6 @@ inline static bool are_segements_parallel(const Vector2 p_segment1_points[2], co
// CSGBrush
void CSGBrush::_regen_face_aabbs() {
-
for (int i = 0; i < faces.size(); i++) {
faces.write[i].aabb = AABB();
faces.write[i].aabb.position = faces[i].vertices[0];
@@ -180,7 +195,6 @@ void CSGBrush::_regen_face_aabbs() {
}
void CSGBrush::build_from_faces(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials, const Vector<bool> &p_invert_faces) {
-
faces.clear();
int vc = p_vertices.size();
@@ -202,7 +216,6 @@ void CSGBrush::build_from_faces(const Vector<Vector3> &p_vertices, const Vector<
faces.resize(p_vertices.size() / 3);
for (int i = 0; i < faces.size(); i++) {
-
Face &f = faces.write[i];
f.vertices[0] = rv[i * 3 + 0];
f.vertices[1] = rv[i * 3 + 1];
@@ -214,21 +227,21 @@ void CSGBrush::build_from_faces(const Vector<Vector3> &p_vertices, const Vector<
f.uvs[2] = ruv[i * 3 + 2];
}
- if (sc == vc / 3)
+ if (sc == vc / 3) {
f.smooth = rs[i];
- else
+ } else {
f.smooth = false;
+ }
- if (ic == vc / 3)
+ if (ic == vc / 3) {
f.invert = ri[i];
- else
+ } else {
f.invert = false;
+ }
if (mc == vc / 3) {
-
Ref<Material> mat = rm[i];
if (mat.is_valid()) {
-
const Map<Ref<Material>, int>::Element *E = material_map.find(mat);
if (E) {
@@ -253,7 +266,6 @@ void CSGBrush::build_from_faces(const Vector<Vector3> &p_vertices, const Vector<
}
void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform &p_xform) {
-
faces = p_brush.faces;
materials = p_brush.materials;
@@ -269,7 +281,6 @@ void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform &p_xform) {
// CSGBrushOperation
void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_brush_a, const CSGBrush &p_brush_b, CSGBrush &r_merged_brush, float p_vertex_snap) {
-
// Check for face collisions and add necessary faces.
Build2DFaceCollection build2DFaceCollection;
for (int i = 0; i < p_brush_a.faces.size(); i++) {
@@ -285,7 +296,6 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
mesh_merge.vertex_snap = p_vertex_snap;
for (int i = 0; i < p_brush_a.faces.size(); i++) {
-
Ref<Material> material;
if (p_brush_a.faces[i].material != -1) {
material = p_brush_a.materials[p_brush_a.faces[i].material];
@@ -305,7 +315,6 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
}
for (int i = 0; i < p_brush_b.faces.size(); i++) {
-
Ref<Material> material;
if (p_brush_b.faces[i].material != -1) {
material = p_brush_b.materials[p_brush_b.faces[i].material];
@@ -331,14 +340,13 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
r_merged_brush.faces.clear();
switch (p_operation) {
-
case OPERATION_UNION: {
-
int outside_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
- if (mesh_merge.faces[i].inside)
+ if (mesh_merge.faces[i].inside) {
continue;
+ }
outside_count++;
}
@@ -347,9 +355,9 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
outside_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
-
- if (mesh_merge.faces[i].inside)
+ if (mesh_merge.faces[i].inside) {
continue;
+ }
for (int j = 0; j < 3; j++) {
r_merged_brush.faces.write[outside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
@@ -367,12 +375,12 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
} break;
case OPERATION_INTERSECTION: {
-
int inside_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
- if (!mesh_merge.faces[i].inside)
+ if (!mesh_merge.faces[i].inside) {
continue;
+ }
inside_count++;
}
@@ -381,9 +389,9 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
inside_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
-
- if (!mesh_merge.faces[i].inside)
+ if (!mesh_merge.faces[i].inside) {
continue;
+ }
for (int j = 0; j < 3; j++) {
r_merged_brush.faces.write[inside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
@@ -401,14 +409,15 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
} break;
case OPERATION_SUBSTRACTION: {
-
int face_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
- if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside)
+ if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside) {
continue;
- if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside)
+ }
+ if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside) {
continue;
+ }
face_count++;
}
@@ -417,11 +426,12 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
face_count = 0;
for (int i = 0; i < mesh_merge.faces.size(); i++) {
-
- if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside)
+ if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside) {
continue;
- if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside)
+ }
+ if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside) {
continue;
+ }
for (int j = 0; j < 3; j++) {
r_merged_brush.faces.write[face_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
@@ -458,7 +468,6 @@ void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_b
#define BVH_LIMIT 8
int CSGBrushOperation::MeshMerge::_create_bvh(FaceBVH *facebvhptr, FaceBVH **facebvhptrptr, int p_from, int p_size, int p_depth, int &r_max_depth, int &r_max_alloc) {
-
if (p_depth > r_max_depth) {
r_max_depth = p_depth;
}
@@ -483,7 +492,6 @@ int CSGBrushOperation::MeshMerge::_create_bvh(FaceBVH *facebvhptr, FaceBVH **fac
int li = aabb.get_longest_axis_index();
switch (li) {
-
case Vector3::AXIS_X: {
SortArray<FaceBVH *, FaceBVHCmpX> sort_x;
sort_x.nth_element(0, p_size, p_size / 2, &facebvhptrptr[p_from]);
@@ -519,18 +527,19 @@ int CSGBrushOperation::MeshMerge::_create_bvh(FaceBVH *facebvhptr, FaceBVH **fac
}
void CSGBrushOperation::MeshMerge::_add_distance(List<real_t> &r_intersectionsA, List<real_t> &r_intersectionsB, bool p_from_B, real_t p_distance) const {
-
List<real_t> &intersections = p_from_B ? r_intersectionsB : r_intersectionsA;
// Check if distance exists.
- for (const List<real_t>::Element *E = intersections.front(); E; E = E->next())
- if (Math::abs(**E - p_distance) < vertex_snap) return;
+ for (const List<real_t>::Element *E = intersections.front(); E; E = E->next()) {
+ if (Math::is_equal_approx(**E, p_distance)) {
+ return;
+ }
+ }
intersections.push_back(p_distance);
}
bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_depth, int p_bvh_first, int p_face_idx) const {
-
Face face = faces[p_face_idx];
Vector3 face_points[3] = {
points[face.points[0]],
@@ -560,22 +569,16 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
stack[0] = pos;
while (true) {
-
uint32_t node = stack[level] & NODE_IDX_MASK;
const FaceBVH *current_facebvhptr = &(facebvhptr[node]);
bool done = false;
switch (stack[level] >> VISITED_BIT_SHIFT) {
-
case TEST_AABB_BIT: {
-
if (current_facebvhptr->face >= 0) {
-
while (current_facebvhptr) {
-
if (p_face_idx != current_facebvhptr->face &&
current_facebvhptr->aabb.intersects_ray(face_center, face_normal)) {
-
const Face &current_face = faces[current_facebvhptr->face];
Vector3 current_points[3] = {
points[current_face.points[0]],
@@ -588,9 +591,10 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
// Check if faces are co-planar.
if ((current_normal - face_normal).length_squared() < CMP_EPSILON2 &&
is_point_in_triangle(face_center, current_points)) {
- // Only add an intersection if checking a B face.
- if (face.from_b)
+ // Only add an intersection if not a B face.
+ if (!face.from_b) {
_add_distance(intersectionsA, intersectionsB, current_face.from_b, 0);
+ }
} else if (ray_intersects_triangle(face_center, face_normal, current_points, CMP_EPSILON, intersection_point)) {
real_t distance = (intersection_point - face_center).length();
_add_distance(intersectionsA, intersectionsB, current_face.from_b, distance);
@@ -607,7 +611,6 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
-
bool valid = current_facebvhptr->aabb.intersects_ray(face_center, face_normal);
if (!valid) {
@@ -620,7 +623,6 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
}
case VISIT_LEFT_BIT: {
-
stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
stack[level + 1] = current_facebvhptr->left | TEST_AABB_BIT;
level++;
@@ -628,7 +630,6 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
}
case VISIT_RIGHT_BIT: {
-
stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
stack[level + 1] = current_facebvhptr->right | TEST_AABB_BIT;
level++;
@@ -636,18 +637,19 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
}
case VISIT_DONE_BIT: {
-
if (level == 0) {
done = true;
break;
- } else
+ } else {
level--;
+ }
continue;
}
}
- if (done)
+ if (done) {
break;
+ }
}
// Inside if face normal intersects other faces an odd number of times.
@@ -655,7 +657,6 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de
}
void CSGBrushOperation::MeshMerge::mark_inside_faces() {
-
// Mark faces that are inside. This helps later do the boolean ops when merging.
// This approach is very brute force with a bunch of optimizations,
// such as BVH and pre AABB intersection test.
@@ -701,8 +702,9 @@ void CSGBrushOperation::MeshMerge::mark_inside_faces() {
AABB intersection_aabb = aabb_a.intersection(aabb_b);
// Check if shape AABBs intersect.
- if (intersection_aabb.size == Vector3())
+ if (intersection_aabb.size == Vector3()) {
return;
+ }
Vector<FaceBVH *> bvhtrvec;
bvhtrvec.resize(faces.size());
@@ -716,21 +718,20 @@ void CSGBrushOperation::MeshMerge::mark_inside_faces() {
_create_bvh(facebvh, bvhptr, 0, faces.size(), 1, max_depth, max_alloc);
for (int i = 0; i < faces.size(); i++) {
-
// Check if face AABB intersects the intersection AABB.
- if (!intersection_aabb.intersects_inclusive(facebvh[i].aabb))
+ if (!intersection_aabb.intersects_inclusive(facebvh[i].aabb)) {
continue;
+ }
- if (_bvh_inside(facebvh, max_depth, max_alloc - 1, i))
+ if (_bvh_inside(facebvh, max_depth, max_alloc - 1, i)) {
faces.write[i].inside = true;
+ }
}
}
void CSGBrushOperation::MeshMerge::add_face(const Vector3 p_points[], const Vector2 p_uvs[], bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
-
int indices[3];
for (int i = 0; i < 3; i++) {
-
VertexKey vk;
vk.x = int((double(p_points[i].x) + double(vertex_snap) * 0.31234) / double(vertex_snap));
vk.y = int((double(p_points[i].y) + double(vertex_snap) * 0.31234) / double(vertex_snap));
@@ -747,8 +748,9 @@ void CSGBrushOperation::MeshMerge::add_face(const Vector3 p_points[], const Vect
}
// Don't add degenerate faces.
- if (indices[0] == indices[2] || indices[0] == indices[1] || indices[1] == indices[2])
+ if (indices[0] == indices[2] || indices[0] == indices[1] || indices[1] == indices[2]) {
return;
+ }
MeshMerge::Face face;
face.from_b = p_from_b;
@@ -778,26 +780,26 @@ void CSGBrushOperation::MeshMerge::add_face(const Vector3 p_points[], const Vect
// CSGBrushOperation::Build2DFaces
int CSGBrushOperation::Build2DFaces::_get_point_idx(const Vector2 &p_point) {
-
for (int vertex_idx = 0; vertex_idx < vertices.size(); ++vertex_idx) {
- if ((p_point - vertices[vertex_idx].point).length_squared() < vertex_snap2)
+ if ((p_point - vertices[vertex_idx].point).length_squared() < vertex_snap2) {
return vertex_idx;
+ }
}
return -1;
}
int CSGBrushOperation::Build2DFaces::_add_vertex(const Vertex2D &p_vertex) {
-
// Check if vertex exists.
int vertex_id = _get_point_idx(p_vertex.point);
- if (vertex_id != -1) return vertex_id;
+ if (vertex_id != -1) {
+ return vertex_id;
+ }
vertices.push_back(p_vertex);
return vertices.size() - 1;
}
void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vertex_indices, int p_new_vertex_index) {
-
if (p_new_vertex_index >= 0 && r_vertex_indices.find(p_new_vertex_index) == -1) {
ERR_FAIL_COND_MSG(p_new_vertex_index >= vertices.size(), "Invalid vertex index.");
@@ -810,19 +812,21 @@ void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vert
// The second vertex.
if (r_vertex_indices.size() == 1) {
-
Vector2 first_point = vertices[r_vertex_indices[0]].point;
Vector2 new_point = vertices[p_new_vertex_index].point;
// Sort along the axis with the greatest difference.
int axis = 0;
- if (Math::abs(new_point.x - first_point.x) < Math::abs(new_point.y - first_point.y)) axis = 1;
+ if (Math::abs(new_point.x - first_point.x) < Math::abs(new_point.y - first_point.y)) {
+ axis = 1;
+ }
// Add it to the beginning or the end appropriately.
- if (new_point[axis] < first_point[axis])
+ if (new_point[axis] < first_point[axis]) {
r_vertex_indices.insert(0, p_new_vertex_index);
- else
+ } else {
r_vertex_indices.push_back(p_new_vertex_index);
+ }
return;
}
@@ -834,7 +838,9 @@ void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vert
// Determine axis being sorted against i.e. the axis with the greatest difference.
int axis = 0;
- if (Math::abs(last_point.x - first_point.x) < Math::abs(last_point.y - first_point.y)) axis = 1;
+ if (Math::abs(last_point.x - first_point.x) < Math::abs(last_point.y - first_point.y)) {
+ axis = 1;
+ }
// Insert the point at the appropriate index.
for (int insert_idx = 0; insert_idx < r_vertex_indices.size(); ++insert_idx) {
@@ -851,13 +857,13 @@ void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vert
}
void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_indices) {
-
int segments = p_segment_indices.size() - 1;
- if (segments < 2) return;
+ if (segments < 2) {
+ return;
+ }
// Faces around an inner vertex are merged by moving the inner vertex to the first vertex.
for (int sorted_idx = 1; sorted_idx < segments; ++sorted_idx) {
-
int closest_idx = 0;
int inner_idx = p_segment_indices[sorted_idx];
@@ -886,14 +892,15 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
// Create the new faces.
for (int merge_idx = 0; merge_idx < merge_faces.size(); ++merge_idx) {
-
int outer_edge_idx[2];
outer_edge_idx[0] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 1) % 3];
outer_edge_idx[1] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 2) % 3];
// Skip flattened faces.
if (outer_edge_idx[0] == p_segment_indices[closest_idx] ||
- outer_edge_idx[1] == p_segment_indices[closest_idx]) continue;
+ outer_edge_idx[1] == p_segment_indices[closest_idx]) {
+ continue;
+ }
//Don't create degenerate triangles.
Vector2 edge1[2] = {
@@ -905,8 +912,12 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
vertices[p_segment_indices[closest_idx]].point
};
if (are_segements_parallel(edge1, edge2, vertex_snap2)) {
- degenerate_points.push_back(outer_edge_idx[0]);
- degenerate_points.push_back(outer_edge_idx[1]);
+ if (!degenerate_points.find(outer_edge_idx[0])) {
+ degenerate_points.push_back(outer_edge_idx[0]);
+ }
+ if (!degenerate_points.find(outer_edge_idx[1])) {
+ degenerate_points.push_back(outer_edge_idx[1]);
+ }
continue;
}
@@ -921,14 +932,16 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
// Delete the old faces in reverse index order.
merge_faces_idx.sort();
merge_faces_idx.invert();
- for (int i = 0; i < merge_faces_idx.size(); ++i)
+ for (int i = 0; i < merge_faces_idx.size(); ++i) {
faces.remove(merge_faces_idx[i]);
+ }
- if (degenerate_points.size() == 0) continue;
+ if (degenerate_points.size() == 0) {
+ continue;
+ }
// Split faces using degenerate points.
for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
-
Face2D face = faces[face_idx];
Vertex2D face_vertices[3] = {
vertices[face.vertex_idx[0]],
@@ -942,7 +955,6 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
};
for (int point_idx = 0; point_idx < degenerate_points.size(); ++point_idx) {
-
int degenerate_idx = degenerate_points[point_idx];
Vector2 point_2D = vertices[degenerate_idx].point;
@@ -954,19 +966,19 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
break;
}
}
- if (existing) continue;
+ if (existing) {
+ continue;
+ }
// Check if point is on an each edge.
for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
-
Vector2 edge_points[2] = {
face_points[face_edge_idx],
face_points[(face_edge_idx + 1) % 3]
};
- Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(point_2D, edge_points);
+ Vector2 closest_point = Geometry2D::get_closest_point_to_segment(point_2D, edge_points);
if ((closest_point - point_2D).length_squared() < vertex_snap2) {
-
int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
// If new vertex snaps to degenerate vertex, just delete this face.
@@ -1004,10 +1016,8 @@ void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_
}
void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_segment_points[2], Vector<int> &r_segment_indices) {
-
// For each face.
for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
-
Face2D face = faces[face_idx];
Vertex2D face_vertices[3] = {
vertices[face.vertex_idx[0]],
@@ -1017,7 +1027,6 @@ void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_s
// Check each edge.
for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
-
Vector2 edge_points[2] = {
face_vertices[face_edge_idx].point,
face_vertices[(face_edge_idx + 1) % 3].point
@@ -1031,7 +1040,7 @@ void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_s
// First check if the ends of the segment are on the edge.
bool on_edge = false;
for (int edge_point_idx = 0; edge_point_idx < 2; ++edge_point_idx) {
- intersection_point = Geometry::get_closest_point_to_segment_2d(p_segment_points[edge_point_idx], edge_points);
+ intersection_point = Geometry2D::get_closest_point_to_segment(p_segment_points[edge_point_idx], edge_points);
if ((intersection_point - p_segment_points[edge_point_idx]).length_squared() < vertex_snap2) {
on_edge = true;
break;
@@ -1039,14 +1048,17 @@ void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_s
}
// Else check if the segment intersects the edge.
- if (on_edge || Geometry::segment_intersects_segment_2d(p_segment_points[0], p_segment_points[1], edge_points[0], edge_points[1], &intersection_point)) {
-
+ if (on_edge || Geometry2D::segment_intersects_segment(p_segment_points[0], p_segment_points[1], edge_points[0], edge_points[1], &intersection_point)) {
// Check if intersection point is an edge point.
if ((intersection_point - edge_points[0]).length_squared() < vertex_snap2 ||
- (intersection_point - edge_points[1]).length_squared() < vertex_snap2) continue;
+ (intersection_point - edge_points[1]).length_squared() < vertex_snap2) {
+ continue;
+ }
// Check if edge exists, by checking if the intersecting segment is parallel to the edge.
- if (are_segements_parallel(p_segment_points, edge_points, vertex_snap2)) continue;
+ if (are_segements_parallel(p_segment_points, edge_points, vertex_snap2)) {
+ continue;
+ }
// Add the intersection point as a new vertex.
Vertex2D new_vertex;
@@ -1064,19 +1076,11 @@ void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_s
break;
}
- // Don't create degenerate triangles.
- Vector2 split_edge1[2] = { vertices[new_vertex_idx].point, edge_points[0] };
- Vector2 split_edge2[2] = { vertices[new_vertex_idx].point, edge_points[1] };
- Vector2 new_edge[2] = { vertices[new_vertex_idx].point, vertices[opposite_vertex_idx].point };
- if (are_segements_parallel(split_edge1, new_edge, vertex_snap2) &&
- are_segements_parallel(split_edge2, new_edge, vertex_snap2)) {
- break;
- }
-
// If opposite point is on the segemnt, add its index to segment indices too.
- Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(vertices[opposite_vertex_idx].point, p_segment_points);
- if ((closest_point - vertices[opposite_vertex_idx].point).length_squared() < vertex_snap2)
+ Vector2 closest_point = Geometry2D::get_closest_point_to_segment(vertices[opposite_vertex_idx].point, p_segment_points);
+ if ((closest_point - vertices[opposite_vertex_idx].point).length_squared() < vertex_snap2) {
_add_vertex_idx_sorted(r_segment_indices, opposite_vertex_idx);
+ }
// Create two new faces around the new edge and remove this face.
// The new edge is the last edge.
@@ -1101,11 +1105,9 @@ void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_s
}
int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
-
int new_vertex_idx = -1;
for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
-
Face2D face = faces[face_idx];
Vertex2D face_vertices[3] = {
vertices[face.vertex_idx[0]],
@@ -1123,16 +1125,21 @@ int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
face_vertices[2].uv
};
+ // Skip degenerate triangles.
+ if (is_triangle_degenerate(points, vertex_snap2)) {
+ continue;
+ }
+
// Check if point is existing face vertex.
for (int i = 0; i < 3; ++i) {
- if ((p_point - face_vertices[i].point).length_squared() < vertex_snap2)
+ if ((p_point - face_vertices[i].point).length_squared() < vertex_snap2) {
return face.vertex_idx[i];
+ }
}
// Check if point is on an each edge.
bool on_edge = false;
for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
-
Vector2 edge_points[2] = {
points[face_edge_idx],
points[(face_edge_idx + 1) % 3]
@@ -1142,7 +1149,7 @@ int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
uvs[(face_edge_idx + 1) % 3]
};
- Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(p_point, edge_points);
+ Vector2 closest_point = Geometry2D::get_closest_point_to_segment(p_point, edge_points);
if ((closest_point - p_point).length_squared() < vertex_snap2) {
on_edge = true;
@@ -1193,8 +1200,7 @@ int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
}
// If not on an edge, check if the point is inside the face.
- if (!on_edge && Geometry::is_point_in_triangle(p_point, face_vertices[0].point, face_vertices[1].point, face_vertices[2].point)) {
-
+ if (!on_edge && Geometry2D::is_point_in_triangle(p_point, face_vertices[0].point, face_vertices[1].point, face_vertices[2].point)) {
// Add the point as a new vertex.
Vertex2D new_vertex;
new_vertex.point = p_point;
@@ -1204,13 +1210,9 @@ int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
// Create three new faces around this point and remove this face.
// The new vertex is the last vertex.
for (int i = 0; i < 3; ++i) {
-
// Don't create degenerate triangles.
- Vector2 edge[2] = { points[i], points[(i + 1) % 3] };
- Vector2 new_edge1[2] = { vertices[new_vertex_idx].point, points[i] };
- Vector2 new_edge2[2] = { vertices[new_vertex_idx].point, points[(i + 1) % 3] };
- if (are_segements_parallel(edge, new_edge1, vertex_snap2) &&
- are_segements_parallel(edge, new_edge2, vertex_snap2)) {
+ Vector2 new_points[3] = { points[i], points[(i + 1) % 3], vertices[new_vertex_idx].point };
+ if (is_triangle_degenerate(new_points, vertex_snap2)) {
continue;
}
@@ -1231,7 +1233,6 @@ int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
}
void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face_idx) {
-
// Find edge points that cross the plane and face points that are in the plane.
// Map those points to 2D.
// Create new faces from those points.
@@ -1240,7 +1241,6 @@ void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face
int points_count = 0;
for (int i = 0; i < 3; i++) {
-
Vector3 point_3D = p_brush.faces[p_face_idx].vertices[i];
if (plane.has_point(point_3D)) {
@@ -1250,13 +1250,14 @@ void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face
points_2D[points_count++] = Vector2(point_2D.x, point_2D.y);
} else {
-
Vector3 next_point_3D = p_brush.faces[p_face_idx].vertices[(i + 1) % 3];
- if (plane.has_point(next_point_3D))
+ if (plane.has_point(next_point_3D)) {
continue; // Next point is in plane, it will be added separately.
- if (plane.is_point_over(point_3D) == plane.is_point_over(next_point_3D))
+ }
+ if (plane.is_point_over(point_3D) == plane.is_point_over(next_point_3D)) {
continue; // Both points on the same side of the plane, ignore.
+ }
// Edge crosses the plane, find and add the intersection point.
Vector3 point_2D;
@@ -1303,7 +1304,6 @@ void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face
}
void CSGBrushOperation::Build2DFaces::addFacesToMesh(MeshMerge &r_mesh_merge, bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
-
for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
Face2D face = faces[face_idx];
Vertex2D fv[3] = {
@@ -1327,7 +1327,6 @@ void CSGBrushOperation::Build2DFaces::addFacesToMesh(MeshMerge &r_mesh_merge, bo
CSGBrushOperation::Build2DFaces::Build2DFaces(const CSGBrush &p_brush, int p_face_idx, float p_vertex_snap2) :
vertex_snap2(p_vertex_snap2 * p_vertex_snap2) {
-
// Convert 3D vertex points to 2D.
Vector3 points_3D[3] = {
p_brush.faces[p_face_idx].vertices[0],
@@ -1356,7 +1355,6 @@ CSGBrushOperation::Build2DFaces::Build2DFaces(const CSGBrush &p_brush, int p_fac
}
void CSGBrushOperation::update_faces(const CSGBrush &p_brush_a, const int p_face_idx_a, const CSGBrush &p_brush_b, const int p_face_idx_b, Build2DFaceCollection &p_collection, float p_vertex_snap) {
-
Vector3 vertices_a[3] = {
p_brush_a.faces[p_face_idx_a].vertices[0],
p_brush_a.faces[p_face_idx_a].vertices[1],
@@ -1384,7 +1382,9 @@ void CSGBrushOperation::update_faces(const CSGBrush &p_brush_a, const int p_face
p_collection.build2DFacesB[p_face_idx_b] = Build2DFaces();
has_degenerate = true;
}
- if (has_degenerate) return;
+ if (has_degenerate) {
+ return;
+ }
// Ensure B has points either side of or in the plane of A.
int in_plane_count = 0, over_count = 0, under_count = 0;
@@ -1392,15 +1392,18 @@ void CSGBrushOperation::update_faces(const CSGBrush &p_brush_a, const int p_face
ERR_FAIL_COND_MSG(plane_a.normal == Vector3(), "Couldn't form plane from Brush A face.");
for (int i = 0; i < 3; i++) {
- if (plane_a.has_point(vertices_b[i]))
+ if (plane_a.has_point(vertices_b[i])) {
in_plane_count++;
- else if (plane_a.is_point_over(vertices_b[i]))
+ } else if (plane_a.is_point_over(vertices_b[i])) {
over_count++;
- else
+ } else {
under_count++;
+ }
}
// If all points under or over the plane, there is no intesection.
- if (over_count == 3 || under_count == 3) return;
+ if (over_count == 3 || under_count == 3) {
+ return;
+ }
// Ensure A has points either side of or in the plane of B.
in_plane_count = 0;
@@ -1410,31 +1413,32 @@ void CSGBrushOperation::update_faces(const CSGBrush &p_brush_a, const int p_face
ERR_FAIL_COND_MSG(plane_b.normal == Vector3(), "Couldn't form plane from Brush B face.");
for (int i = 0; i < 3; i++) {
- if (plane_b.has_point(vertices_a[i]))
+ if (plane_b.has_point(vertices_a[i])) {
in_plane_count++;
- else if (plane_b.is_point_over(vertices_a[i]))
+ } else if (plane_b.is_point_over(vertices_a[i])) {
over_count++;
- else
+ } else {
under_count++;
+ }
}
// If all points under or over the plane, there is no intesection.
- if (over_count == 3 || under_count == 3) return;
+ if (over_count == 3 || under_count == 3) {
+ return;
+ }
// Check for intersection using the SAT theorem.
{
-
// Edge pair cross product combinations.
for (int i = 0; i < 3; i++) {
-
Vector3 axis_a = (vertices_a[i] - vertices_a[(i + 1) % 3]).normalized();
for (int j = 0; j < 3; j++) {
-
Vector3 axis_b = (vertices_b[j] - vertices_b[(j + 1) % 3]).normalized();
Vector3 sep_axis = axis_a.cross(axis_b);
- if (sep_axis == Vector3())
+ if (sep_axis == Vector3()) {
continue; //colineal
+ }
sep_axis.normalize();
real_t min_a = 1e20, max_a = -1e20;
diff --git a/modules/csg/csg.h b/modules/csg/csg.h
index d389cbc283..1612c16a32 100644
--- a/modules/csg/csg.h
+++ b/modules/csg/csg.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,20 +31,19 @@
#ifndef CSG_H
#define CSG_H
-#include "core/list.h"
-#include "core/map.h"
#include "core/math/aabb.h"
#include "core/math/plane.h"
#include "core/math/transform.h"
#include "core/math/vector2.h"
#include "core/math/vector3.h"
-#include "core/oa_hash_map.h"
-#include "core/reference.h"
-#include "core/vector.h"
+#include "core/object/reference.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/templates/oa_hash_map.h"
+#include "core/templates/vector.h"
#include "scene/resources/material.h"
struct CSGBrush {
-
struct Face {
Vector3 vertices[3];
Vector2 uvs[3];
@@ -65,7 +64,6 @@ struct CSGBrush {
};
struct CSGBrushOperation {
-
enum Operation {
OPERATION_UNION,
OPERATION_INTERSECTION,
@@ -75,7 +73,6 @@ struct CSGBrushOperation {
void merge_brushes(Operation p_operation, const CSGBrush &p_brush_a, const CSGBrush &p_brush_b, CSGBrush &r_merged_brush, float p_vertex_snap);
struct MeshMerge {
-
struct Face {
bool from_b;
bool inside;
@@ -156,7 +153,6 @@ struct CSGBrushOperation {
};
struct Build2DFaces {
-
struct Vertex2D {
Vector2 point;
Vector2 uv;
diff --git a/modules/csg/csg_gizmos.cpp b/modules/csg/csg_gizmos.cpp
index fa176cb94e..e23442ef99 100644
--- a/modules/csg/csg_gizmos.cpp
+++ b/modules/csg/csg_gizmos.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
///////////
CSGShape3DGizmoPlugin::CSGShape3DGizmoPlugin() {
-
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);
@@ -50,68 +49,54 @@ CSGShape3DGizmoPlugin::CSGShape3DGizmoPlugin() {
}
String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_idx) const {
-
CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node());
if (Object::cast_to<CSGSphere3D>(cs)) {
-
return "Radius";
}
if (Object::cast_to<CSGBox3D>(cs)) {
-
- static const char *hname[3] = { "Width", "Height", "Depth" };
- return hname[p_idx];
+ return "Size";
}
if (Object::cast_to<CSGCylinder3D>(cs)) {
-
return p_idx == 0 ? "Radius" : "Height";
}
if (Object::cast_to<CSGTorus3D>(cs)) {
-
return p_idx == 0 ? "InnerRadius" : "OuterRadius";
}
return "";
}
-Variant CSGShape3DGizmoPlugin::get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const {
+Variant CSGShape3DGizmoPlugin::get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const {
CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node());
if (Object::cast_to<CSGSphere3D>(cs)) {
-
CSGSphere3D *s = Object::cast_to<CSGSphere3D>(cs);
return s->get_radius();
}
if (Object::cast_to<CSGBox3D>(cs)) {
-
CSGBox3D *s = Object::cast_to<CSGBox3D>(cs);
- switch (p_idx) {
- case 0: return s->get_width();
- case 1: return s->get_height();
- case 2: return s->get_depth();
- }
+ return s->get_size();
}
if (Object::cast_to<CSGCylinder3D>(cs)) {
-
CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs);
return p_idx == 0 ? s->get_radius() : s->get_height();
}
if (Object::cast_to<CSGTorus3D>(cs)) {
-
CSGTorus3D *s = Object::cast_to<CSGTorus3D>(cs);
return p_idx == 0 ? s->get_inner_radius() : s->get_outer_radius();
}
return Variant();
}
-void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point) {
+void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point) {
CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node());
Transform gt = cs->get_global_transform();
@@ -124,91 +109,91 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca
Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 16384) };
if (Object::cast_to<CSGSphere3D>(cs)) {
-
CSGSphere3D *s = Object::cast_to<CSGSphere3D>(cs);
Vector3 ra, rb;
- Geometry::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb);
+ Geometry3D::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb);
float d = ra.x;
if (Node3DEditor::get_singleton()->is_snap_enabled()) {
- d = Math::stepify(d, Node3DEditor::get_singleton()->get_translate_snap());
+ d = Math::snapped(d, Node3DEditor::get_singleton()->get_translate_snap());
}
- if (d < 0.001)
+ if (d < 0.001) {
d = 0.001;
+ }
s->set_radius(d);
}
if (Object::cast_to<CSGBox3D>(cs)) {
-
CSGBox3D *s = Object::cast_to<CSGBox3D>(cs);
Vector3 axis;
axis[p_idx] = 1.0;
Vector3 ra, rb;
- Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
+ Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
if (Node3DEditor::get_singleton()->is_snap_enabled()) {
- d = Math::stepify(d, Node3DEditor::get_singleton()->get_translate_snap());
+ d = Math::snapped(d, Node3DEditor::get_singleton()->get_translate_snap());
}
- if (d < 0.001)
+ if (d < 0.001) {
d = 0.001;
-
- switch (p_idx) {
- case 0: s->set_width(d * 2); break;
- case 1: s->set_height(d * 2); break;
- case 2: s->set_depth(d * 2); break;
}
+
+ Vector3 h = s->get_size();
+ h[p_idx] = d * 2;
+ s->set_size(h);
}
if (Object::cast_to<CSGCylinder3D>(cs)) {
-
CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs);
Vector3 axis;
axis[p_idx == 0 ? 0 : 1] = 1.0;
Vector3 ra, rb;
- Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
+ Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = axis.dot(ra);
if (Node3DEditor::get_singleton()->is_snap_enabled()) {
- d = Math::stepify(d, Node3DEditor::get_singleton()->get_translate_snap());
+ d = Math::snapped(d, Node3DEditor::get_singleton()->get_translate_snap());
}
- if (d < 0.001)
+ if (d < 0.001) {
d = 0.001;
+ }
- if (p_idx == 0)
+ if (p_idx == 0) {
s->set_radius(d);
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
s->set_height(d * 2.0);
+ }
}
if (Object::cast_to<CSGTorus3D>(cs)) {
-
CSGTorus3D *s = Object::cast_to<CSGTorus3D>(cs);
Vector3 axis;
axis[0] = 1.0;
Vector3 ra, rb;
- Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
+ Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = axis.dot(ra);
if (Node3DEditor::get_singleton()->is_snap_enabled()) {
- d = Math::stepify(d, Node3DEditor::get_singleton()->get_translate_snap());
+ d = Math::snapped(d, Node3DEditor::get_singleton()->get_translate_snap());
}
- if (d < 0.001)
+ if (d < 0.001) {
d = 0.001;
+ }
- if (p_idx == 0)
+ if (p_idx == 0) {
s->set_inner_radius(d);
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
s->set_outer_radius(d);
+ }
}
}
-void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
+void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) {
CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node());
if (Object::cast_to<CSGSphere3D>(cs)) {
@@ -228,36 +213,25 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx,
if (Object::cast_to<CSGBox3D>(cs)) {
CSGBox3D *s = Object::cast_to<CSGBox3D>(cs);
if (p_cancel) {
- switch (p_idx) {
- case 0: s->set_width(p_restore); break;
- case 1: s->set_height(p_restore); break;
- case 2: s->set_depth(p_restore); break;
- }
+ s->set_size(p_restore);
return;
}
UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo();
- ur->create_action(TTR("Change Box Shape Extents"));
- static const char *method[3] = { "set_width", "set_height", "set_depth" };
- float current = 0;
- switch (p_idx) {
- case 0: current = s->get_width(); break;
- case 1: current = s->get_height(); break;
- case 2: current = s->get_depth(); break;
- }
-
- ur->add_do_method(s, method[p_idx], current);
- ur->add_undo_method(s, method[p_idx], p_restore);
+ ur->create_action(TTR("Change Box Shape Size"));
+ ur->add_do_method(s, "set_size", s->get_size());
+ ur->add_undo_method(s, "set_size", p_restore);
ur->commit_action();
}
if (Object::cast_to<CSGCylinder3D>(cs)) {
CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs);
if (p_cancel) {
- if (p_idx == 0)
+ if (p_idx == 0) {
s->set_radius(p_restore);
- else
+ } else {
s->set_height(p_restore);
+ }
return;
}
@@ -278,10 +252,11 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx,
if (Object::cast_to<CSGTorus3D>(cs)) {
CSGTorus3D *s = Object::cast_to<CSGTorus3D>(cs);
if (p_cancel) {
- if (p_idx == 0)
+ if (p_idx == 0) {
s->set_inner_radius(p_restore);
- else
+ } else {
s->set_outer_radius(p_restore);
+ }
return;
}
@@ -299,11 +274,12 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx,
ur->commit_action();
}
}
+
bool CSGShape3DGizmoPlugin::has_gizmo(Node3D *p_spatial) {
return Object::cast_to<CSGSphere3D>(p_spatial) || Object::cast_to<CSGBox3D>(p_spatial) || Object::cast_to<CSGCylinder3D>(p_spatial) || Object::cast_to<CSGTorus3D>(p_spatial) || Object::cast_to<CSGMesh3D>(p_spatial) || Object::cast_to<CSGPolygon3D>(p_spatial);
}
-String CSGShape3DGizmoPlugin::get_name() const {
+String CSGShape3DGizmoPlugin::get_gizmo_name() const {
return "CSGShape3D";
}
@@ -316,7 +292,6 @@ bool CSGShape3DGizmoPlugin::is_selectable_when_hidden() const {
}
void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
-
CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node());
p_gizmo->clear();
@@ -393,9 +368,13 @@ void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
CSGBox3D *s = Object::cast_to<CSGBox3D>(cs);
Vector<Vector3> handles;
- handles.push_back(Vector3(s->get_width() * 0.5, 0, 0));
- handles.push_back(Vector3(0, s->get_height() * 0.5, 0));
- handles.push_back(Vector3(0, 0, s->get_depth() * 0.5));
+
+ for (int i = 0; i < 3; i++) {
+ Vector3 h;
+ h[i] = s->get_size()[i] / 2;
+ handles.push_back(h);
+ }
+
p_gizmo->add_handles(handles, handles_material);
}
diff --git a/modules/csg/csg_gizmos.h b/modules/csg/csg_gizmos.h
index 7763989b2a..8f7da35de3 100644
--- a/modules/csg/csg_gizmos.h
+++ b/modules/csg/csg_gizmos.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,20 +36,19 @@
#include "editor/node_3d_editor_gizmos.h"
class CSGShape3DGizmoPlugin : public EditorNode3DGizmoPlugin {
-
GDCLASS(CSGShape3DGizmoPlugin, EditorNode3DGizmoPlugin);
public:
- bool has_gizmo(Node3D *p_spatial);
- String get_name() const;
- int get_priority() const;
- bool is_selectable_when_hidden() const;
- void redraw(EditorNode3DGizmo *p_gizmo);
-
- String get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_idx) const;
- Variant get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const;
- void set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point);
- void commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel);
+ bool has_gizmo(Node3D *p_spatial) override;
+ String get_gizmo_name() const override;
+ int get_priority() const override;
+ bool is_selectable_when_hidden() const override;
+ void redraw(EditorNode3DGizmo *p_gizmo) override;
+
+ String get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_idx) const override;
+ Variant get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const override;
+ void set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point) override;
+ void commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) override;
CSGShape3DGizmoPlugin();
};
diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp
index 550a919d0d..042c3aaca7 100644
--- a/modules/csg/csg_shape.cpp
+++ b/modules/csg/csg_shape.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,17 +29,19 @@
/*************************************************************************/
#include "csg_shape.h"
+#include "core/math/geometry_2d.h"
#include "scene/3d/path_3d.h"
void CSGShape3D::set_use_collision(bool p_enable) {
-
- if (use_collision == p_enable)
+ if (use_collision == p_enable) {
return;
+ }
use_collision = p_enable;
- if (!is_inside_tree() || !is_root_shape())
+ if (!is_inside_tree() || !is_root_shape()) {
return;
+ }
if (use_collision) {
root_collision_shape.instance();
@@ -71,12 +73,10 @@ void CSGShape3D::set_collision_layer(uint32_t p_layer) {
}
uint32_t CSGShape3D::get_collision_layer() const {
-
return collision_layer;
}
void CSGShape3D::set_collision_mask(uint32_t p_mask) {
-
collision_mask = p_mask;
if (root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->body_set_collision_mask(root_collision_instance, p_mask);
@@ -84,42 +84,38 @@ void CSGShape3D::set_collision_mask(uint32_t p_mask) {
}
uint32_t CSGShape3D::get_collision_mask() const {
-
return collision_mask;
}
void CSGShape3D::set_collision_mask_bit(int p_bit, bool p_value) {
-
uint32_t mask = get_collision_mask();
- if (p_value)
+ if (p_value) {
mask |= 1 << p_bit;
- else
+ } else {
mask &= ~(1 << p_bit);
+ }
set_collision_mask(mask);
}
bool CSGShape3D::get_collision_mask_bit(int p_bit) const {
-
return get_collision_mask() & (1 << p_bit);
}
void CSGShape3D::set_collision_layer_bit(int p_bit, bool p_value) {
-
uint32_t mask = get_collision_layer();
- if (p_value)
+ if (p_value) {
mask |= 1 << p_bit;
- else
+ } else {
mask &= ~(1 << p_bit);
+ }
set_collision_layer(mask);
}
bool CSGShape3D::get_collision_layer_bit(int p_bit) const {
-
return get_collision_layer() & (1 << p_bit);
}
bool CSGShape3D::is_root_shape() const {
-
return !parent;
}
@@ -132,26 +128,20 @@ float CSGShape3D::get_snap() const {
}
void CSGShape3D::_make_dirty() {
-
- if (!is_inside_tree())
- return;
-
- if (dirty) {
+ if (!is_inside_tree()) {
return;
}
- dirty = true;
-
if (parent) {
parent->_make_dirty();
- } else {
- //only parent will do
+ } else if (!dirty) {
call_deferred("_update_shape");
}
+
+ dirty = true;
}
CSGBrush *CSGShape3D::_get_brush() {
-
if (dirty) {
if (brush) {
memdelete(brush);
@@ -161,23 +151,24 @@ CSGBrush *CSGShape3D::_get_brush() {
CSGBrush *n = _build_brush();
for (int i = 0; i < get_child_count(); i++) {
-
CSGShape3D *child = Object::cast_to<CSGShape3D>(get_child(i));
- if (!child)
+ if (!child) {
continue;
- if (!child->is_visible_in_tree())
+ }
+ if (!child->is_visible_in_tree()) {
continue;
+ }
CSGBrush *n2 = child->_get_brush();
- if (!n2)
+ if (!n2) {
continue;
+ }
if (!n) {
n = memnew(CSGBrush);
n->copy_from(*n2, child->get_transform());
} else {
-
CSGBrush *nn = memnew(CSGBrush);
CSGBrush *nn2 = memnew(CSGBrush);
nn2->copy_from(*n2, child->get_transform());
@@ -185,9 +176,15 @@ CSGBrush *CSGShape3D::_get_brush() {
CSGBrushOperation bop;
switch (child->get_operation()) {
- case CSGShape3D::OPERATION_UNION: bop.merge_brushes(CSGBrushOperation::OPERATION_UNION, *n, *nn2, *nn, snap); break;
- case CSGShape3D::OPERATION_INTERSECTION: bop.merge_brushes(CSGBrushOperation::OPERATION_INTERSECTION, *n, *nn2, *nn, snap); break;
- case CSGShape3D::OPERATION_SUBTRACTION: bop.merge_brushes(CSGBrushOperation::OPERATION_SUBSTRACTION, *n, *nn2, *nn, snap); break;
+ case CSGShape3D::OPERATION_UNION:
+ bop.merge_brushes(CSGBrushOperation::OPERATION_UNION, *n, *nn2, *nn, snap);
+ break;
+ case CSGShape3D::OPERATION_INTERSECTION:
+ bop.merge_brushes(CSGBrushOperation::OPERATION_INTERSECTION, *n, *nn2, *nn, snap);
+ break;
+ case CSGShape3D::OPERATION_SUBTRACTION:
+ bop.merge_brushes(CSGBrushOperation::OPERATION_SUBSTRACTION, *n, *nn2, *nn, snap);
+ break;
}
memdelete(n);
memdelete(nn2);
@@ -199,10 +196,11 @@ CSGBrush *CSGShape3D::_get_brush() {
AABB aabb;
for (int i = 0; i < n->faces.size(); i++) {
for (int j = 0; j < 3; j++) {
- if (i == 0 && j == 0)
+ if (i == 0 && j == 0) {
aabb.position = n->faces[i].vertices[j];
- else
+ } else {
aabb.expand_to(n->faces[i].vertices[j]);
+ }
}
}
node_aabb = aabb;
@@ -257,7 +255,6 @@ void CSGShape3D::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTe
void CSGShape3D::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT,
const tbool bIsOrientationPreserving, const int iFace, const int iVert) {
-
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
int i = iFace * 3 + iVert;
@@ -274,9 +271,9 @@ void CSGShape3D::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const
}
void CSGShape3D::_update_shape() {
-
- if (parent)
+ if (parent) {
return;
+ }
set_base(RID());
root_mesh.unref(); //byebye root mesh
@@ -319,7 +316,6 @@ void CSGShape3D::_update_shape() {
//create arrays
for (int i = 0; i < surfaces.size(); i++) {
-
surfaces.write[i].vertices.resize(face_count[i] * 3);
surfaces.write[i].normals.resize(face_count[i] * 3);
surfaces.write[i].uvs.resize(face_count[i] * 3);
@@ -340,35 +336,36 @@ void CSGShape3D::_update_shape() {
}
}
- //fill arrays
- Vector<Vector3> physics_faces;
- bool fill_physics_faces = false;
+ // Update collision faces.
if (root_collision_shape.is_valid()) {
+ Vector<Vector3> physics_faces;
physics_faces.resize(n->faces.size() * 3);
- fill_physics_faces = true;
- }
+ Vector3 *physicsw = physics_faces.ptrw();
- {
- Vector3 *physicsw;
+ for (int i = 0; i < n->faces.size(); i++) {
+ int order[3] = { 0, 1, 2 };
- if (fill_physics_faces) {
- physicsw = physics_faces.ptrw();
+ if (n->faces[i].invert) {
+ SWAP(order[1], order[2]);
+ }
+
+ physicsw[i * 3 + 0] = n->faces[i].vertices[order[0]];
+ physicsw[i * 3 + 1] = n->faces[i].vertices[order[1]];
+ physicsw[i * 3 + 2] = n->faces[i].vertices[order[2]];
}
- for (int i = 0; i < n->faces.size(); i++) {
+ root_collision_shape->set_faces(physics_faces);
+ }
+ //fill arrays
+ {
+ for (int i = 0; i < n->faces.size(); i++) {
int order[3] = { 0, 1, 2 };
if (n->faces[i].invert) {
SWAP(order[1], order[2]);
}
- if (fill_physics_faces) {
- physicsw[i * 3 + 0] = n->faces[i].vertices[order[0]];
- physicsw[i * 3 + 1] = n->faces[i].vertices[order[1]];
- physicsw[i * 3 + 2] = n->faces[i].vertices[order[2]];
- }
-
int mat = n->faces[i].material;
ERR_CONTINUE(mat < -1 || mat >= face_count.size());
int idx = mat == -1 ? face_count.size() - 1 : mat;
@@ -378,7 +375,6 @@ void CSGShape3D::_update_shape() {
Plane p(n->faces[i].vertices[0], n->faces[i].vertices[1], n->faces[i].vertices[2]);
for (int j = 0; j < 3; j++) {
-
Vector3 v = n->faces[i].vertices[j];
Vector3 normal = p.normal;
@@ -388,7 +384,6 @@ void CSGShape3D::_update_shape() {
}
if (n->faces[i].invert) {
-
normal = -normal;
}
@@ -433,8 +428,9 @@ void CSGShape3D::_update_shape() {
have_tangents = genTangSpaceDefault(&msc);
}
- if (surfaces[i].last_added == 0)
+ if (surfaces[i].last_added == 0) {
continue;
+ }
// and convert to surface array
Array array;
@@ -452,12 +448,9 @@ void CSGShape3D::_update_shape() {
root_mesh->surface_set_material(idx, surfaces[i].material);
}
- if (root_collision_shape.is_valid()) {
- root_collision_shape->set_faces(physics_faces);
- }
-
set_base(root_mesh->get_rid());
}
+
AABB CSGShape3D::get_aabb() const {
return node_aabb;
}
@@ -485,14 +478,11 @@ Vector<Vector3> CSGShape3D::get_brush_faces() {
}
Vector<Face3> CSGShape3D::get_faces(uint32_t p_usage_flags) const {
-
return Vector<Face3>();
}
void CSGShape3D::_notification(int p_what) {
-
if (p_what == NOTIFICATION_ENTER_TREE) {
-
Node *parentn = get_parent();
if (parentn) {
parent = Object::cast_to<CSGShape3D>(parentn);
@@ -516,24 +506,28 @@ void CSGShape3D::_notification(int p_what) {
_make_dirty();
}
- if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
+ if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
+ if (use_collision && is_root_shape() && root_collision_instance.is_valid()) {
+ PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
+ }
+ }
+ if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
if (parent) {
parent->_make_dirty();
}
}
if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
-
if (parent) {
parent->_make_dirty();
}
}
if (p_what == NOTIFICATION_EXIT_TREE) {
-
- if (parent)
+ if (parent) {
parent->_make_dirty();
+ }
parent = nullptr;
if (use_collision && is_root_shape() && root_collision_instance.is_valid()) {
@@ -546,7 +540,6 @@ void CSGShape3D::_notification(int p_what) {
}
void CSGShape3D::set_operation(Operation p_operation) {
-
operation = p_operation;
_make_dirty();
update_gizmo();
@@ -576,7 +569,6 @@ void CSGShape3D::_validate_property(PropertyInfo &property) const {
}
Array CSGShape3D::get_meshes() const {
-
if (root_mesh.is_valid()) {
Array arr;
arr.resize(2);
@@ -587,8 +579,8 @@ Array CSGShape3D::get_meshes() const {
return Array();
}
-void CSGShape3D::_bind_methods() {
+void CSGShape3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("_update_shape"), &CSGShape3D::_update_shape);
ClassDB::bind_method(D_METHOD("is_root_shape"), &CSGShape3D::is_root_shape);
@@ -651,11 +643,11 @@ CSGShape3D::~CSGShape3D() {
brush = nullptr;
}
}
+
//////////////////////////////////
CSGBrush *CSGCombiner3D::_build_brush() {
-
- return nullptr; //does not build anything
+ return memnew(CSGBrush); //does not build anything
}
CSGCombiner3D::CSGCombiner3D() {
@@ -664,7 +656,6 @@ CSGCombiner3D::CSGCombiner3D() {
/////////////////////
CSGBrush *CSGPrimitive3D::_create_brush_from_arrays(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uv, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials) {
-
CSGBrush *brush = memnew(CSGBrush);
Vector<bool> invert;
@@ -682,7 +673,6 @@ CSGBrush *CSGPrimitive3D::_create_brush_from_arrays(const Vector<Vector3> &p_ver
}
void CSGPrimitive3D::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_invert_faces", "invert_faces"), &CSGPrimitive3D::set_invert_faces);
ClassDB::bind_method(D_METHOD("is_inverting_faces"), &CSGPrimitive3D::is_inverting_faces);
@@ -690,8 +680,9 @@ void CSGPrimitive3D::_bind_methods() {
}
void CSGPrimitive3D::set_invert_faces(bool p_invert) {
- if (invert_faces == p_invert)
+ if (invert_faces == p_invert) {
return;
+ }
invert_faces = p_invert;
@@ -709,9 +700,9 @@ CSGPrimitive3D::CSGPrimitive3D() {
/////////////////////
CSGBrush *CSGMesh3D::_build_brush() {
-
- if (!mesh.is_valid())
- return nullptr;
+ if (!mesh.is_valid()) {
+ return memnew(CSGBrush);
+ }
Vector<Vector3> vertices;
Vector<bool> smooth;
@@ -720,7 +711,6 @@ CSGBrush *CSGMesh3D::_build_brush() {
Ref<Material> material = get_material();
for (int i = 0; i < mesh->get_surface_count(); i++) {
-
if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue;
}
@@ -729,12 +719,13 @@ CSGBrush *CSGMesh3D::_build_brush() {
if (arrays.size() == 0) {
_make_dirty();
- ERR_FAIL_COND_V(arrays.size() == 0, nullptr);
+ ERR_FAIL_COND_V(arrays.size() == 0, memnew(CSGBrush));
}
Vector<Vector3> avertices = arrays[Mesh::ARRAY_VERTEX];
- if (avertices.size() == 0)
+ if (avertices.size() == 0) {
continue;
+ }
const Vector3 *vr = avertices.ptr();
@@ -775,7 +766,6 @@ CSGBrush *CSGMesh3D::_build_brush() {
const int *ir = aindices.ptr();
for (int j = 0; j < is; j += 3) {
-
Vector3 vertex[3];
Vector3 normal[3];
Vector2 uv[3];
@@ -819,7 +809,6 @@ CSGBrush *CSGMesh3D::_build_brush() {
Ref<Material> *mw = materials.ptrw();
for (int j = 0; j < is; j += 3) {
-
Vector3 vertex[3];
Vector3 normal[3];
Vector2 uv[3];
@@ -850,8 +839,9 @@ CSGBrush *CSGMesh3D::_build_brush() {
}
}
- if (vertices.size() == 0)
- return nullptr;
+ if (vertices.size() == 0) {
+ return memnew(CSGBrush);
+ }
return _create_brush_from_arrays(vertices, uvs, smooth, materials);
}
@@ -862,19 +852,18 @@ void CSGMesh3D::_mesh_changed() {
}
void CSGMesh3D::set_material(const Ref<Material> &p_material) {
- if (material == p_material)
+ if (material == p_material) {
return;
+ }
material = p_material;
_make_dirty();
}
Ref<Material> CSGMesh3D::get_material() const {
-
return material;
}
void CSGMesh3D::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &CSGMesh3D::set_mesh);
ClassDB::bind_method(D_METHOD("get_mesh"), &CSGMesh3D::get_mesh);
@@ -886,9 +875,9 @@ void CSGMesh3D::_bind_methods() {
}
void CSGMesh3D::set_mesh(const Ref<Mesh> &p_mesh) {
-
- if (mesh == p_mesh)
+ if (mesh == p_mesh) {
return;
+ }
if (mesh.is_valid()) {
mesh->disconnect("changed", callable_mp(this, &CSGMesh3D::_mesh_changed));
}
@@ -908,7 +897,6 @@ Ref<Mesh> CSGMesh3D::get_mesh() {
////////////////////////////////
CSGBrush *CSGSphere3D::_build_brush() {
-
// set our bounding box
CSGBrush *brush = memnew(CSGBrush);
@@ -932,7 +920,6 @@ CSGBrush *CSGSphere3D::_build_brush() {
invert.resize(face_count);
{
-
Vector3 *facesw = faces.ptrw();
Vector2 *uvsw = uvs.ptrw();
bool *smoothw = smooth.ptrw();
@@ -953,7 +940,6 @@ CSGBrush *CSGSphere3D::_build_brush() {
double u1 = double(i) / rings;
for (int j = radial_segments; j >= 1; j--) {
-
double lng0 = 2 * Math_PI * (double)(j - 1) / radial_segments;
double x0 = Math::cos(lng0);
double y0 = Math::sin(lng0);
@@ -980,7 +966,6 @@ CSGBrush *CSGSphere3D::_build_brush() {
};
if (i < rings) {
-
//face 1
facesw[face * 3 + 0] = v[0];
facesw[face * 3 + 1] = v[1];
@@ -1090,13 +1075,11 @@ bool CSGSphere3D::get_smooth_faces() const {
}
void CSGSphere3D::set_material(const Ref<Material> &p_material) {
-
material = p_material;
_make_dirty();
}
Ref<Material> CSGSphere3D::get_material() const {
-
return material;
}
@@ -1111,7 +1094,6 @@ CSGSphere3D::CSGSphere3D() {
///////////////
CSGBrush *CSGBox3D::_build_brush() {
-
// set our bounding box
CSGBrush *brush = memnew(CSGBrush);
@@ -1135,7 +1117,6 @@ CSGBrush *CSGBox3D::_build_brush() {
invert.resize(face_count);
{
-
Vector3 *facesw = faces.ptrw();
Vector2 *uvsw = uvs.ptrw();
bool *smoothw = smooth.ptrw();
@@ -1144,28 +1125,25 @@ CSGBrush *CSGBox3D::_build_brush() {
int face = 0;
- Vector3 vertex_mul(width * 0.5, height * 0.5, depth * 0.5);
+ Vector3 vertex_mul = size / 2;
{
-
for (int i = 0; i < 6; i++) {
-
Vector3 face_points[4];
float uv_points[8] = { 0, 0, 0, 1, 1, 1, 1, 0 };
for (int j = 0; j < 4; j++) {
-
float v[3];
v[0] = 1.0;
v[1] = 1 - 2 * ((j >> 1) & 1);
v[2] = v[1] * (1 - 2 * (j & 1));
for (int k = 0; k < 3; k++) {
-
- if (i < 3)
+ if (i < 3) {
face_points[j][(i + k) % 3] = v[k];
- else
+ } else {
face_points[3 - j][(i + k) % 3] = -v[k];
+ }
}
}
@@ -1216,80 +1194,40 @@ CSGBrush *CSGBox3D::_build_brush() {
}
void CSGBox3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_width", "width"), &CSGBox3D::set_width);
- ClassDB::bind_method(D_METHOD("get_width"), &CSGBox3D::get_width);
-
- ClassDB::bind_method(D_METHOD("set_height", "height"), &CSGBox3D::set_height);
- ClassDB::bind_method(D_METHOD("get_height"), &CSGBox3D::get_height);
-
- ClassDB::bind_method(D_METHOD("set_depth", "depth"), &CSGBox3D::set_depth);
- ClassDB::bind_method(D_METHOD("get_depth"), &CSGBox3D::get_depth);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &CSGBox3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &CSGBox3D::get_size);
ClassDB::bind_method(D_METHOD("set_material", "material"), &CSGBox3D::set_material);
ClassDB::bind_method(D_METHOD("get_material"), &CSGBox3D::get_material);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "width", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_width", "get_width");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "height", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_height", "get_height");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_depth", "get_depth");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material");
}
-void CSGBox3D::set_width(const float p_width) {
- width = p_width;
- _make_dirty();
- update_gizmo();
- _change_notify("width");
-}
-
-float CSGBox3D::get_width() const {
- return width;
-}
-
-void CSGBox3D::set_height(const float p_height) {
- height = p_height;
- _make_dirty();
- update_gizmo();
- _change_notify("height");
-}
-
-float CSGBox3D::get_height() const {
- return height;
-}
-
-void CSGBox3D::set_depth(const float p_depth) {
- depth = p_depth;
+void CSGBox3D::set_size(const Vector3 &p_size) {
+ size = p_size;
_make_dirty();
update_gizmo();
- _change_notify("depth");
+ _change_notify("size");
}
-float CSGBox3D::get_depth() const {
- return depth;
+Vector3 CSGBox3D::get_size() const {
+ return size;
}
void CSGBox3D::set_material(const Ref<Material> &p_material) {
-
material = p_material;
_make_dirty();
update_gizmo();
}
Ref<Material> CSGBox3D::get_material() const {
-
return material;
}
-CSGBox3D::CSGBox3D() {
- // defaults
- width = 2.0;
- height = 2.0;
- depth = 2.0;
-}
-
///////////////
CSGBrush *CSGCylinder3D::_build_brush() {
-
// set our bounding box
CSGBrush *brush = memnew(CSGBrush);
@@ -1313,7 +1251,6 @@ CSGBrush *CSGCylinder3D::_build_brush() {
invert.resize(face_count);
{
-
Vector3 *facesw = faces.ptrw();
Vector2 *uvsw = uvs.ptrw();
bool *smoothw = smooth.ptrw();
@@ -1325,9 +1262,7 @@ CSGBrush *CSGCylinder3D::_build_brush() {
Vector3 vertex_mul(radius, height * 0.5, radius);
{
-
for (int i = 0; i < sides; i++) {
-
float inc = float(i) / sides;
float inc_n = float((i + 1)) / sides;
@@ -1504,13 +1439,11 @@ bool CSGCylinder3D::get_smooth_faces() const {
}
void CSGCylinder3D::set_material(const Ref<Material> &p_material) {
-
material = p_material;
_make_dirty();
}
Ref<Material> CSGCylinder3D::get_material() const {
-
return material;
}
@@ -1526,14 +1459,14 @@ CSGCylinder3D::CSGCylinder3D() {
///////////////
CSGBrush *CSGTorus3D::_build_brush() {
-
// set our bounding box
float min_radius = inner_radius;
float max_radius = outer_radius;
- if (min_radius == max_radius)
- return nullptr; //sorry, can't
+ if (min_radius == max_radius) {
+ return memnew(CSGBrush); //sorry, can't
+ }
if (min_radius > max_radius) {
SWAP(min_radius, max_radius);
@@ -1562,7 +1495,6 @@ CSGBrush *CSGTorus3D::_build_brush() {
invert.resize(face_count);
{
-
Vector3 *facesw = faces.ptrw();
Vector2 *uvsw = uvs.ptrw();
bool *smoothw = smooth.ptrw();
@@ -1572,9 +1504,7 @@ CSGBrush *CSGTorus3D::_build_brush() {
int face = 0;
{
-
for (int i = 0; i < sides; i++) {
-
float inci = float(i) / sides;
float inci_n = float((i + 1)) / sides;
@@ -1585,7 +1515,6 @@ CSGBrush *CSGTorus3D::_build_brush() {
Vector3 normali_n = Vector3(Math::cos(angi_n), 0, Math::sin(angi_n));
for (int j = 0; j < ring_sides; j++) {
-
float incj = float(j) / ring_sides;
float incj_n = float((j + 1)) / ring_sides;
@@ -1732,13 +1661,11 @@ bool CSGTorus3D::get_smooth_faces() const {
}
void CSGTorus3D::set_material(const Ref<Material> &p_material) {
-
material = p_material;
_make_dirty();
}
Ref<Material> CSGTorus3D::get_material() const {
-
return material;
}
@@ -1754,11 +1681,11 @@ CSGTorus3D::CSGTorus3D() {
///////////////
CSGBrush *CSGPolygon3D::_build_brush() {
-
// set our bounding box
- if (polygon.size() < 3)
- return nullptr;
+ if (polygon.size() < 3) {
+ return memnew(CSGBrush);
+ }
Vector<Point2> final_polygon = polygon;
@@ -1766,10 +1693,11 @@ CSGBrush *CSGPolygon3D::_build_brush() {
final_polygon.invert();
}
- Vector<int> triangles = Geometry::triangulate_polygon(final_polygon);
+ Vector<int> triangles = Geometry2D::triangulate_polygon(final_polygon);
- if (triangles.size() < 3)
- return nullptr;
+ if (triangles.size() < 3) {
+ return memnew(CSGBrush);
+ }
Path3D *path = nullptr;
Ref<Curve3D> curve;
@@ -1783,24 +1711,35 @@ CSGBrush *CSGPolygon3D::_build_brush() {
final_polygon_min = p;
final_polygon_max = final_polygon_min;
} else {
- if (p.x < final_polygon_min.x) final_polygon_min.x = p.x;
- if (p.y < final_polygon_min.y) final_polygon_min.y = p.y;
+ if (p.x < final_polygon_min.x) {
+ final_polygon_min.x = p.x;
+ }
+ if (p.y < final_polygon_min.y) {
+ final_polygon_min.y = p.y;
+ }
- if (p.x > final_polygon_max.x) final_polygon_max.x = p.x;
- if (p.y > final_polygon_max.y) final_polygon_max.y = p.y;
+ if (p.x > final_polygon_max.x) {
+ final_polygon_max.x = p.x;
+ }
+ if (p.y > final_polygon_max.y) {
+ final_polygon_max.y = p.y;
+ }
}
}
Vector2 final_polygon_size = final_polygon_max - final_polygon_min;
if (mode == MODE_PATH) {
- if (!has_node(path_node))
- return nullptr;
+ if (!has_node(path_node)) {
+ return memnew(CSGBrush);
+ }
Node *n = get_node(path_node);
- if (!n)
- return nullptr;
+ if (!n) {
+ return memnew(CSGBrush);
+ }
path = Object::cast_to<Path3D>(n);
- if (!path)
- return nullptr;
+ if (!path) {
+ return memnew(CSGBrush);
+ }
if (path != path_cache) {
if (path_cache) {
@@ -1816,18 +1755,24 @@ CSGBrush *CSGPolygon3D::_build_brush() {
path_cache = nullptr;
}
curve = path->get_curve();
- if (curve.is_null())
- return nullptr;
- if (curve->get_baked_length() <= 0)
- return nullptr;
+ if (curve.is_null()) {
+ return memnew(CSGBrush);
+ }
+ if (curve->get_baked_length() <= 0) {
+ return memnew(CSGBrush);
+ }
}
CSGBrush *brush = memnew(CSGBrush);
int face_count = 0;
switch (mode) {
- case MODE_DEPTH: face_count = triangles.size() * 2 / 3 + (final_polygon.size()) * 2; break;
- case MODE_SPIN: face_count = (spin_degrees < 360 ? triangles.size() * 2 / 3 : 0) + (final_polygon.size()) * 2 * spin_sides; break;
+ case MODE_DEPTH:
+ face_count = triangles.size() * 2 / 3 + (final_polygon.size()) * 2;
+ break;
+ case MODE_SPIN:
+ face_count = (spin_degrees < 360 ? triangles.size() * 2 / 3 : 0) + (final_polygon.size()) * 2 * spin_sides;
+ break;
case MODE_PATH: {
float bl = curve->get_baked_length();
int splits = MAX(2, Math::ceil(bl / path_interval));
@@ -1857,7 +1802,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
AABB aabb; //must be computed
{
-
Vector3 *facesw = faces.ptrw();
Vector2 *uvsw = uvs.ptrw();
bool *smoothw = smooth.ptrw();
@@ -1868,10 +1812,8 @@ CSGBrush *CSGPolygon3D::_build_brush() {
switch (mode) {
case MODE_DEPTH: {
-
//add triangles, front and back
for (int i = 0; i < 2; i++) {
-
for (int j = 0; j < triangles.size(); j += 3) {
for (int k = 0; k < 3; k++) {
int src[3] = { 0, i == 0 ? 1 : 2, i == 0 ? 2 : 1 };
@@ -1896,7 +1838,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
//add triangles for depth
for (int i = 0; i < final_polygon.size(); i++) {
-
int i_n = (i + 1) % final_polygon.size();
Vector3 v[4] = {
@@ -1946,9 +1887,7 @@ CSGBrush *CSGPolygon3D::_build_brush() {
} break;
case MODE_SPIN: {
-
for (int i = 0; i < spin_sides; i++) {
-
float inci = float(i) / spin_sides;
float inci_n = float((i + 1)) / spin_sides;
@@ -1960,7 +1899,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
//add triangles for depth
for (int j = 0; j < final_polygon.size(); j++) {
-
int j_n = (j + 1) % final_polygon.size();
Vector3 v[4] = {
@@ -2009,7 +1947,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
if (i == 0 && spin_degrees < 360) {
-
for (int j = 0; j < triangles.size(); j += 3) {
for (int k = 0; k < 3; k++) {
int src[3] = { 0, 2, 1 };
@@ -2027,7 +1964,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
if (i == spin_sides - 1 && spin_degrees < 360) {
-
for (int j = 0; j < triangles.size(); j += 3) {
for (int k = 0; k < 3; k++) {
int src[3] = { 0, 1, 2 };
@@ -2047,7 +1983,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
} break;
case MODE_PATH: {
-
float bl = curve->get_baked_length();
int splits = MAX(2, Math::ceil(bl / path_interval));
float u1 = 0.0;
@@ -2073,7 +2008,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
for (int i = 0; i <= splits; i++) {
-
float ofs = i * path_interval;
if (ofs > bl) {
ofs = bl;
@@ -2113,7 +2047,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
//put triangles where they belong
//add triangles for depth
for (int j = 0; j < final_polygon.size(); j++) {
-
int j_n = (j + 1) % final_polygon.size();
Vector3 v[4] = {
@@ -2163,7 +2096,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
if (i == 0 && !path_joined) {
-
for (int j = 0; j < triangles.size(); j += 3) {
for (int k = 0; k < 3; k++) {
int src[3] = { 0, 1, 2 };
@@ -2181,7 +2113,6 @@ CSGBrush *CSGPolygon3D::_build_brush() {
}
if (i == splits && !path_joined) {
-
for (int j = 0; j < triangles.size(); j += 3) {
for (int k = 0; k < 3; k++) {
int src[3] = { 0, 2, 1 };
@@ -2403,6 +2334,7 @@ void CSGPolygon3D::set_path_interval(float p_interval) {
_make_dirty();
update_gizmo();
}
+
float CSGPolygon3D::get_path_interval() const {
return path_interval;
}
@@ -2447,13 +2379,11 @@ bool CSGPolygon3D::get_smooth_faces() const {
}
void CSGPolygon3D::set_material(const Ref<Material> &p_material) {
-
material = p_material;
_make_dirty();
}
Ref<Material> CSGPolygon3D::get_material() const {
-
return material;
}
diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h
index abab1ded20..7dff8b6d3b 100644
--- a/modules/csg/csg_shape.h
+++ b/modules/csg/csg_shape.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -114,7 +114,7 @@ protected:
friend class CSGCombiner3D;
CSGBrush *_get_brush();
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
Array get_meshes() const;
@@ -124,8 +124,8 @@ public:
virtual Vector<Vector3> get_brush_faces();
- virtual AABB get_aabb() const;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const;
+ virtual AABB get_aabb() const override;
+ virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
void set_use_collision(bool p_enable);
bool is_using_collision() const;
@@ -159,7 +159,7 @@ class CSGCombiner3D : public CSGShape3D {
GDCLASS(CSGCombiner3D, CSGShape3D);
private:
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
public:
CSGCombiner3D();
@@ -185,7 +185,7 @@ public:
class CSGMesh3D : public CSGPrimitive3D {
GDCLASS(CSGMesh3D, CSGPrimitive3D);
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Ref<Mesh> mesh;
Ref<Material> material;
@@ -204,9 +204,8 @@ public:
};
class CSGSphere3D : public CSGPrimitive3D {
-
GDCLASS(CSGSphere3D, CSGPrimitive3D);
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Ref<Material> material;
bool smooth_faces;
@@ -237,38 +236,28 @@ public:
};
class CSGBox3D : public CSGPrimitive3D {
-
GDCLASS(CSGBox3D, CSGPrimitive3D);
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Ref<Material> material;
- float width;
- float height;
- float depth;
+ Vector3 size = Vector3(2, 2, 2);
protected:
static void _bind_methods();
public:
- void set_width(const float p_width);
- float get_width() const;
-
- void set_height(const float p_height);
- float get_height() const;
-
- void set_depth(const float p_depth);
- float get_depth() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_material(const Ref<Material> &p_material);
Ref<Material> get_material() const;
- CSGBox3D();
+ CSGBox3D() {}
};
class CSGCylinder3D : public CSGPrimitive3D {
-
GDCLASS(CSGCylinder3D, CSGPrimitive3D);
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Ref<Material> material;
float radius;
@@ -303,9 +292,8 @@ public:
};
class CSGTorus3D : public CSGPrimitive3D {
-
GDCLASS(CSGTorus3D, CSGPrimitive3D);
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Ref<Material> material;
float inner_radius;
@@ -340,7 +328,6 @@ public:
};
class CSGPolygon3D : public CSGPrimitive3D {
-
GDCLASS(CSGPolygon3D, CSGPrimitive3D);
public:
@@ -357,7 +344,7 @@ public:
};
private:
- virtual CSGBrush *_build_brush();
+ virtual CSGBrush *_build_brush() override;
Vector<Vector2> polygon;
Ref<Material> material;
@@ -388,7 +375,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
void _notification(int p_what);
public:
diff --git a/modules/csg/doc_classes/CSGBox3D.xml b/modules/csg/doc_classes/CSGBox3D.xml
index 492bf68c44..b1d0454b76 100644
--- a/modules/csg/doc_classes/CSGBox3D.xml
+++ b/modules/csg/doc_classes/CSGBox3D.xml
@@ -11,17 +11,11 @@
<methods>
</methods>
<members>
- <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" 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" default="2.0">
- Width of the box measured from the center of the box.
+ <member name="size" type="Vector3" setter="set_size" getter="get_size" default="Vector3( 2, 2, 2 )">
+ The box's width, height and depth.
</member>
</members>
<constants>
diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml
index 43ce988c30..dac556c7f1 100644
--- a/modules/csg/doc_classes/CSGShape3D.xml
+++ b/modules/csg/doc_classes/CSGShape3D.xml
@@ -71,10 +71,10 @@
<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.
+ 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. See [url=https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
<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.
+ The physics layers this CSG shape scans for collisions. See [url=https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</member>
<member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape3D.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.
diff --git a/modules/csg/icons/CSGBox3D.svg b/modules/csg/icons/CSGBox3D.svg
index 67e34df444..ceef9196a7 100644
--- a/modules/csg/icons/CSGBox3D.svg
+++ b/modules/csg/icons/CSGBox3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/><path d="m8 .94531-7 3.5v7.2227l7 3.5.29492-.14844c-.18282-.30101-.29492-.64737-.29492-1.0195v-2c0-.72651.40824-1.3664 1-1.7168v-1.6699l4-2v1.3867h1c.36419 0 .70336.10754 1 .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"/></svg>
diff --git a/modules/csg/icons/CSGCapsule3D.svg b/modules/csg/icons/CSGCapsule3D.svg
index 92a7b5a870..14e582ee84 100644
--- a/modules/csg/icons/CSGCapsule3D.svg
+++ b/modules/csg/icons/CSGCapsule3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-2.7527 0-5 2.2418-5 4.9902v4.0176c0 2.7484 2.2473 4.9922 5 4.9922.092943 0 .18367-.008623.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72887.41095-1.3691 1.0059-1.7188v-.28125c.34771-.034464.68259-.10691 1.0156-.19922.10394-.99856.95603-1.8008 1.9785-1.8008h1v-2.0098c0-2.7484-2.2473-4.9902-5-4.9902zm-1.0059 2.127v4.8574c-.66556-.1047-1.2974-.37231-1.9941-.66211v-1.3223c0-1.3474.79841-2.4642 1.9941-2.873zm2.0117 0c1.1957.4088 1.9941 1.5256 1.9941 2.873v1.3457c-.68406.3054-1.3142.57292-1.9941.66602v-4.8848zm-4.0059 6.334c.67836.2231 1.3126.44599 1.9941.52539v2.8848c-1.1957-.4092-1.9941-1.5237-1.9941-2.8711v-.53906z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/icons/CSGCombiner3D.svg b/modules/csg/icons/CSGCombiner3D.svg
index cce2902e24..50ce4179d9 100644
--- a/modules/csg/icons/CSGCombiner3D.svg
+++ b/modules/csg/icons/CSGCombiner3D.svg
@@ -1,8 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/><path d="m3 1c-1.1046 0-2 .89543-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.1046-.89543-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm0 4c0 1.1046.89543 2 2 2v-2zm4 0v2h2v-2z" fill="#fc9c9c"/></svg>
diff --git a/modules/csg/icons/CSGCylinder3D.svg b/modules/csg/icons/CSGCylinder3D.svg
index 645a74c79b..c84594928a 100644
--- a/modules/csg/icons/CSGCylinder3D.svg
+++ b/modules/csg/icons/CSGCylinder3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 14.999999 14.999999" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-1.7469 0-3.328.22648-4.5586.63672-.61528.20512-1.1471.45187-1.5898.80078-.44272.34891-.85156.88101-.85156 1.5625v8c0 .68149.40884 1.2155.85156 1.5645.44272.34891.97457.59577 1.5898.80078 1.2306.41024 2.8117.63477 4.5586.63477.095648 0 .18467-.008426.2793-.009766-.1722-.29446-.2793-.62995-.2793-.99023v-1c-1.5668 0-2.9867-.2195-3.9277-.5332-.46329-.15435-.90474-.33752-1.0723-.4668v-5.8125c.1468.058667.2835.12515.44141.17773 1.2306.41024 2.8117.63477 4.5586.63477s3.328-.22453 4.5586-.63477c.15791-.052267.29461-.11864.44141-.17773v1.8125h1c.36396 0 .70348.10774 1 .2832v-4.2832c0-.68149-.40884-1.2136-.85156-1.5625-.44272-.34891-.97457-.59566-1.5898-.80078-1.2306-.41024-2.8117-.63672-4.5586-.63672zm0 2c1.5668 0 2.9867.22145 3.9277.53516.46368.15456.80138.33741.96875.4668-.16752.12928-.50546.3105-.96875.46484-.94102.31371-2.361.5332-3.9277.5332s-2.9867-.2195-3.9277-.5332c-.46329-.15435-.80123-.33556-.96875-.46484.16737-.12939.50507-.31224.96875-.4668.94102-.31371 2.361-.53516 3.9277-.53516z" fill="#fc9c9c" stroke-width="1.0667" transform="scale(.9375)"/><path d="m11.25 8.4375c-.51938 0-.9375.41812-.9375.9375v.9375h1.875v1.875h.9375c.51938 0 .9375-.41812.9375-.9375v-1.875c0-.51938-.41812-.9375-.9375-.9375zm.9375 3.75h-1.875v-1.875h-.9375c-.51938 0-.9375.41812-.9375.9375v1.875c0 .51938.41812.9375.9375.9375h1.875c.51938 0 .9375-.41812.9375-.9375z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/icons/CSGMesh3D.svg b/modules/csg/icons/CSGMesh3D.svg
index 6e940a4aa5..962e71f6ae 100644
--- a/modules/csg/icons/CSGMesh3D.svg
+++ b/modules/csg/icons/CSGMesh3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m3 1c-1.1046 0-2 .89543-2 2 .0005649.71397.38169 1.3735 1 1.7305v6.541c-.61771.35663-.99874 1.0152-1 1.7285 0 1.1046.89543 2 2 2 .71397-.000565 1.3735-.38169 1.7305-1h3.2695v-2h-3.2715c-.17478-.30301-.42598-.55488-.72852-.73047v-5.8555l4.916 4.916c.31428-.20669.68609-.33008 1.084-.33008 0-.3979.12338-.76971.33008-1.084l-4.916-4.916h5.8574c.17478.30301.42598.55488.72852.73047v3.2695h2v-3.2715c.61771-.35663.99874-1.0152 1-1.7285 0-1.1046-.89543-2-2-2-.71397.0005648-1.3735.38169-1.7305 1h-6.541c-.35663-.61771-1.0152-.99874-1.7285-1z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/icons/CSGPolygon3D.svg b/modules/csg/icons/CSGPolygon3D.svg
index 71b03cb8e6..1d496e5fd9 100644
--- a/modules/csg/icons/CSGPolygon3D.svg
+++ b/modules/csg/icons/CSGPolygon3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.9629 1.002c-.14254.00487-.28238.04016-.41016.10352l-6 3c-.33878.16944-.55276.51574-.55273.89453v5.832c-.105.61631.37487 1.1768 1 1.168h5v2c.0000216.67546.64487 1.1297 1.2617.95898-.16118-.28721-.26172-.61135-.26172-.95898v-2c0-.72673.40794-1.3664 1-1.7168v-1.666l4-2v1.3828h1c.36397 0 .70348.10774 1 .2832v-3.2773c.000006-.00195.000006-.0039094 0-.0058594.000026-.37879-.21395-.72509-.55273-.89453l-6-3c-.15022-.074574-.31679-.11017-.48438-.10352zm.037109 2.1172 3.7637 1.8809-2.7637 1.3809v-1.3809c-.0000552-.55226-.44774-.99994-1-1h-1.7617l1.7617-.88086zm-5 2.8809h4v4h-4z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/icons/CSGSphere3D.svg b/modules/csg/icons/CSGSphere3D.svg
index f81b566993..639e38f49f 100644
--- a/modules/csg/icons/CSGSphere3D.svg
+++ b/modules/csg/icons/CSGSphere3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-3.8541 0-7 3.1459-7 7 0 3.8542 3.1459 7 7 7 .093042 0 .18321-.01004.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72673.40794-1.3664 1-1.7168v-.33398c.34074-.019259.67728-.069097 1.0156-.10547.083091-1.0187.94713-1.8438 1.9844-1.8438h2c.35841 0 .69292.10484.98633.27539.003633-.092184.013672-.18235.013672-.27539 0-3.8541-3.1459-7-7-7zm-1 2.0977v4.8711c-1.2931-.071342-2.6061-.29819-3.9434-.69141.30081-2.0978 1.8852-3.7665 3.9434-4.1797zm2 0c2.0549.41253 3.637 2.0767 3.9414 4.1699-1.3046.36677-2.6158.60259-3.9414.6875zm-5.7793 6.2988c1.2733.31892 2.5337.50215 3.7793.5625v2.9414c-1.8291-.36719-3.266-1.7339-3.7793-3.5039z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/icons/CSGTorus3D.svg b/modules/csg/icons/CSGTorus3D.svg
index 3d30aa47b2..eb8c0f37cb 100644
--- a/modules/csg/icons/CSGTorus3D.svg
+++ b/modules/csg/icons/CSGTorus3D.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 3c-1.8145 0-3.4691.41721-4.7461 1.1621-1.277.745-2.2539 1.9082-2.2539 3.3379 0 1.4298.9769 2.5949 2.2539 3.3398s2.9316 1.1602 4.7461 1.1602c0-1.0907.90931-2 2-2 0-.080836.013744-.15778.023438-.23633-.61769.14673-1.3008.23633-2.0234.23633-1.4992 0-2.8437-.36687-3.7383-.88867-.89456-.5219-1.2617-1.108-1.2617-1.6113 0-.5032.36716-1.0876 1.2617-1.6094.89456-.5219 2.2391-.89062 3.7383-.89062s2.8437.36872 3.7383.89062c.89456.5218 1.2617 1.1062 1.2617 1.6094 0 .15978-.053679.32822-.13281.5h1.1328c.32481 0 .62893.088408.90234.23047.057552-.23582.097656-.47718.097656-.73047 0-1.4297-.9769-2.5929-2.2539-3.3379-1.277-.7449-2.9316-1.1621-4.7461-1.1621z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg>
diff --git a/modules/csg/register_types.cpp b/modules/csg/register_types.cpp
index 40eef84b1b..e28f44d1eb 100644
--- a/modules/csg/register_types.cpp
+++ b/modules/csg/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "csg_shape.h"
void register_csg_types() {
-
#ifndef _3D_DISABLED
ClassDB::register_virtual_class<CSGShape3D>();
diff --git a/modules/csg/register_types.h b/modules/csg/register_types.h
index 926e598561..8747b3fade 100644
--- a/modules/csg/register_types.h
+++ b/modules/csg/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/cvtt/SCsub b/modules/cvtt/SCsub
index 5438f7ebac..e56177d6e9 100644
--- a/modules/cvtt/SCsub
+++ b/modules/cvtt/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_cvtt = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
thirdparty_dir = "#thirdparty/cvtt/"
thirdparty_sources = [
"ConvectionKernels.cpp",
@@ -17,7 +20,15 @@ env_cvtt.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_cvtt.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
# Godot source files
-env_cvtt.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_cvtt.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/cvtt/image_compress_cvtt.cpp b/modules/cvtt/image_compress_cvtt.cpp
index 9dbaa88202..6661dbbb0b 100644
--- a/modules/cvtt/image_compress_cvtt.cpp
+++ b/modules/cvtt/image_compress_cvtt.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#include "core/os/os.h"
#include "core/os/thread.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include <ConvectionKernels.h>
@@ -137,9 +137,9 @@ static void _digest_job_queue(void *p_job_queue) {
}
void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChannels p_channels) {
-
- if (p_image->get_format() >= Image::FORMAT_BPTC_RGBA)
+ if (p_image->get_format() >= Image::FORMAT_BPTC_RGBA) {
return; //do not compress, already compressed
+ }
int w = p_image->get_width();
int h = p_image->get_height();
@@ -154,22 +154,24 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChann
cvtt::Options options;
uint32_t flags = cvtt::Flags::Fastest;
- if (p_lossy_quality > 0.85)
+ if (p_lossy_quality > 0.85) {
flags = cvtt::Flags::Ultra;
- else if (p_lossy_quality > 0.75)
+ } else if (p_lossy_quality > 0.75) {
flags = cvtt::Flags::Better;
- else if (p_lossy_quality > 0.55)
+ } else if (p_lossy_quality > 0.55) {
flags = cvtt::Flags::Default;
- else if (p_lossy_quality > 0.35)
+ } else if (p_lossy_quality > 0.35) {
flags = cvtt::Flags::Fast;
- else if (p_lossy_quality > 0.15)
+ } else if (p_lossy_quality > 0.15) {
flags = cvtt::Flags::Faster;
+ }
flags |= cvtt::Flags::BC7_RespectPunchThrough;
- if (p_channels == Image::USED_CHANNELS_RG) { //guessing this is a normalmap
+ if (p_channels == Image::USED_CHANNELS_RG) { //guessing this is a normal map
flags |= cvtt::Flags::Uniform;
}
+ options.flags = flags;
Image::Format target_format = Image::FORMAT_BPTC_RGBA;
@@ -222,7 +224,6 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChann
Vector<CVTTCompressionRowTask> tasks;
for (int i = 0; i <= mm_count; i++) {
-
int bw = w % 4 != 0 ? w + (4 - w % 4) : w;
int bh = h % 4 != 0 ? h + (4 - h % 4) : h;
@@ -280,7 +281,6 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChann
}
void image_decompress_cvtt(Image *p_image) {
-
Image::Format target_format;
bool is_signed = false;
bool is_hdr = false;
@@ -318,7 +318,6 @@ void image_decompress_cvtt(Image *p_image) {
int dst_ofs = 0;
for (int i = 0; i <= mm_count; i++) {
-
int src_ofs = p_image->get_mipmap_offset(i);
const uint8_t *in_bytes = &rb[src_ofs];
diff --git a/modules/cvtt/image_compress_cvtt.h b/modules/cvtt/image_compress_cvtt.h
index c1772199af..bef5653fa9 100644
--- a/modules/cvtt/image_compress_cvtt.h
+++ b/modules/cvtt/image_compress_cvtt.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef IMAGE_COMPRESS_CVTT_H
#define IMAGE_COMPRESS_CVTT_H
-#include "core/image.h"
+#include "core/io/image.h"
void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::UsedChannels p_channels);
void image_decompress_cvtt(Image *p_image);
diff --git a/modules/cvtt/register_types.cpp b/modules/cvtt/register_types.cpp
index 38542a33b9..055b5dc6e3 100644
--- a/modules/cvtt/register_types.cpp
+++ b/modules/cvtt/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
#include "image_compress_cvtt.h"
void register_cvtt_types() {
-
Image::set_compress_bptc_func(image_compress_cvtt);
Image::_image_decompress_bptc = image_decompress_cvtt;
}
diff --git a/modules/cvtt/register_types.h b/modules/cvtt/register_types.h
index 8472980c6a..e62e8c0e9a 100644
--- a/modules/cvtt/register_types.h
+++ b/modules/cvtt/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,14 +28,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifdef TOOLS_ENABLED
-
#ifndef CVTT_REGISTER_TYPES_H
#define CVTT_REGISTER_TYPES_H
+#ifdef TOOLS_ENABLED
+
void register_cvtt_types();
void unregister_cvtt_types();
-#endif // CVTT_REGISTER_TYPES_H
-
#endif // TOOLS_ENABLED
+
+#endif // CVTT_REGISTER_TYPES_H
diff --git a/modules/dds/register_types.cpp b/modules/dds/register_types.cpp
index c6281ff01b..1444d33171 100644
--- a/modules/dds/register_types.cpp
+++ b/modules/dds/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,13 +35,11 @@
static Ref<ResourceFormatDDS> resource_loader_dds;
void register_dds_types() {
-
resource_loader_dds.instance();
ResourceLoader::add_resource_format_loader(resource_loader_dds);
}
void unregister_dds_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_dds);
resource_loader_dds.unref();
}
diff --git a/modules/dds/register_types.h b/modules/dds/register_types.h
index 3cb7b5c2a6..b84bcd06c8 100644
--- a/modules/dds/register_types.h
+++ b/modules/dds/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp
index 294d594135..2865b3c9ae 100644
--- a/modules/dds/texture_loader_dds.cpp
+++ b/modules/dds/texture_loader_dds.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,14 +29,15 @@
/*************************************************************************/
#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])))
+// Reference: https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dds-header
+
enum {
DDS_MAGIC = 0x20534444,
- DDSD_CAPS = 0x00000001,
- DDSD_PIXELFORMAT = 0x00001000,
DDSD_PITCH = 0x00000008,
DDSD_LINEARSIZE = 0x00080000,
DDSD_MIPMAPCOUNT = 0x00020000,
@@ -47,7 +48,6 @@ enum {
};
enum DDSFormat {
-
DDS_DXT1,
DDS_DXT3,
DDS_DXT5,
@@ -95,18 +95,20 @@ static const DDSFormatInfo dds_format_info[DDS_MAX] = {
};
RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
- if (r_error)
+ if (r_error) {
*r_error = ERR_CANT_OPEN;
+ }
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
- if (!f)
+ if (!f) {
return RES();
+ }
FileAccessRef fref(f);
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CORRUPT;
+ }
ERR_FAIL_COND_V_MSG(err != OK, RES(), "Unable to open DDS texture file '" + p_path + "'.");
@@ -120,13 +122,15 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
uint32_t mipmaps = f->get_32();
//skip 11
- for (int i = 0; i < 11; i++)
+ for (int i = 0; i < 11; i++) {
f->get_32();
+ }
//validate
- if (magic != DDS_MAGIC || hsize != 124 || !(flags & DDSD_PIXELFORMAT) || !(flags & DDSD_CAPS)) {
-
+ // We don't check DDSD_CAPS or DDSD_PIXELFORMAT, as they're mandatory when writing,
+ // but non-mandatory when reading (as some writers don't set them)...
+ if (magic != DDS_MAGIC || hsize != 124) {
ERR_FAIL_V_MSG(RES(), "Invalid or unsupported DDS texture file '" + p_path + "'.");
}
@@ -157,70 +161,55 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
*/
//must avoid this later
- while (f->get_position() < 128)
+ while (f->get_position() < 128) {
f->get_8();
+ }
DDSFormat dds_format;
if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT1")) {
-
dds_format = DDS_DXT1;
} else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT3")) {
-
dds_format = DDS_DXT3;
} else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT5")) {
-
dds_format = DDS_DXT5;
} else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("ATI1")) {
-
dds_format = DDS_ATI1;
} 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) {
-
dds_format = DDS_BGRA8;
} else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 24 && format_red_mask == 0xff0000 && format_green_mask == 0xff00 && format_blue_mask == 0xff) {
-
dds_format = DDS_BGR8;
} else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0xff && format_green_mask == 0xff00 && format_blue_mask == 0xff0000 && format_alpha_mask == 0xff000000) {
-
dds_format = DDS_RGBA8;
} else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 24 && format_red_mask == 0xff && format_green_mask == 0xff00 && format_blue_mask == 0xff0000) {
-
dds_format = DDS_RGB8;
} else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 16 && format_red_mask == 0x00007c00 && format_green_mask == 0x000003e0 && format_blue_mask == 0x0000001f && format_alpha_mask == 0x00008000) {
-
dds_format = DDS_BGR5A1;
} else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0x3ff00000 && format_green_mask == 0xffc00 && format_blue_mask == 0x3ff && format_alpha_mask == 0xc0000000) {
-
dds_format = DDS_BGR10A2;
} else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0x0000f800 && format_green_mask == 0x000007e0 && format_blue_mask == 0x0000001f) {
-
dds_format = DDS_BGR565;
} else if (!(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 8 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff) {
-
dds_format = DDS_LUMINANCE;
} else if ((format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff && format_alpha_mask == 0xff00) {
-
dds_format = DDS_LUMINANCE_ALPHA;
} else if (format_flags & DDPF_INDEXED && format_rgb_bits == 8) {
-
dds_format = DDS_BGR565;
} else {
-
printf("unrecognized fourcc %x format_flags: %x - rgbbits %i - red_mask %x green mask %x blue mask %x alpha mask %x\n", format_fourcc, format_flags, format_rgb_bits, format_red_mask, format_green_mask, format_blue_mask, format_alpha_mask);
ERR_FAIL_V_MSG(RES(), "Unrecognized or unsupported color layout in DDS '" + p_path + "'.");
}
- if (!(flags & DDSD_MIPMAPCOUNT))
+ if (!(flags & DDSD_MIPMAPCOUNT)) {
mipmaps = 1;
+ }
Vector<uint8_t> src_data;
@@ -236,7 +225,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
ERR_FAIL_COND_V(!(flags & DDSD_LINEARSIZE), RES());
for (uint32_t i = 1; i < mipmaps; i++) {
-
w = MAX(1, w >> 1);
h = MAX(1, h >> 1);
uint32_t bsize = MAX(info.divisor, w) / info.divisor * MAX(info.divisor, h) / info.divisor * info.block_size;
@@ -249,7 +237,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
f->get_buffer(wb, size);
} else if (info.palette) {
-
//indexed
ERR_FAIL_COND_V(!(flags & DDSD_PITCH), RES());
ERR_FAIL_COND_V(format_rgb_bits != 8, RES());
@@ -262,16 +249,15 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
int colsize = 3;
for (int i = 0; i < 256; i++) {
-
- if (palette[i * 4 + 3] < 255)
+ if (palette[i * 4 + 3] < 255) {
colsize = 4;
+ }
}
int w2 = width;
int h2 = height;
for (uint32_t i = 1; i < mipmaps; i++) {
-
w2 = (w2 + 1) >> 1;
h2 = (h2 + 1) >> 1;
size += w2 * h2 * info.block_size;
@@ -282,14 +268,14 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
f->get_buffer(wb, size);
for (int i = 0; i < 256; i++) {
-
int dst_ofs = size + i * colsize;
int src_ofs = i * 4;
wb[dst_ofs + 0] = palette[src_ofs + 2];
wb[dst_ofs + 1] = palette[src_ofs + 1];
wb[dst_ofs + 2] = palette[src_ofs + 0];
- if (colsize == 4)
+ if (colsize == 4) {
wb[dst_ofs + 3] = palette[src_ofs + 3];
+ }
}
} else {
//uncompressed generic...
@@ -297,30 +283,27 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
uint32_t size = width * height * info.block_size;
for (uint32_t i = 1; i < mipmaps; i++) {
-
w = (w + 1) >> 1;
h = (h + 1) >> 1;
size += w * h * info.block_size;
}
- if (dds_format == DDS_BGR565)
+ if (dds_format == DDS_BGR565) {
size = size * 3 / 2;
- else if (dds_format == DDS_BGR5A1)
+ } else if (dds_format == DDS_BGR5A1) {
size = size * 2;
+ }
src_data.resize(size);
uint8_t *wb = src_data.ptrw();
f->get_buffer(wb, size);
switch (dds_format) {
-
case DDS_BGR5A1: {
-
// TO RGBA
int colcount = size / 4;
for (int i = colcount - 1; i >= 0; i--) {
-
int src_ofs = i * 2;
int dst_ofs = i * 4;
@@ -335,11 +318,9 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
}
} break;
case DDS_BGR565: {
-
int colcount = size / 3;
for (int i = colcount - 1; i >= 0; i--) {
-
int src_ofs = i * 2;
int dst_ofs = i * 3;
@@ -353,12 +334,10 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
} break;
case DDS_BGR10A2: {
-
// TO RGBA
int colcount = size / 4;
for (int i = colcount - 1; i >= 0; i--) {
-
int ofs = i * 4;
uint32_t w32 = uint32_t(wb[ofs + 0]) | (uint32_t(wb[ofs + 1]) << 8) | (uint32_t(wb[ofs + 2]) << 16) | (uint32_t(wb[ofs + 3]) << 24);
@@ -375,31 +354,25 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
}
} break;
case DDS_BGRA8: {
-
int colcount = size / 4;
for (int i = 0; i < colcount; i++) {
-
SWAP(wb[i * 4 + 0], wb[i * 4 + 2]);
}
} break;
case DDS_BGR8: {
-
int colcount = size / 3;
for (int i = 0; i < colcount; i++) {
-
SWAP(wb[i * 3 + 0], wb[i * 3 + 2]);
}
} break;
case DDS_RGBA8: {
-
/* do nothing either
int colcount = size/4;
for(int i=0;i<colcount;i++) {
-
uint8_t r = wb[i*4+1];
uint8_t g = wb[i*4+2];
uint8_t b = wb[i*4+3];
@@ -413,23 +386,19 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
*/
} break;
case DDS_RGB8: {
-
// do nothing
/*
int colcount = size/3;
for(int i=0;i<colcount;i++) {
-
SWAP( wb[i*3+0],wb[i*3+2] );
}*/
} break;
case DDS_LUMINANCE: {
-
// do nothing i guess?
} break;
case DDS_LUMINANCE_ALPHA: {
-
// do nothing i guess?
} break;
@@ -444,25 +413,24 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
Ref<ImageTexture> texture = memnew(ImageTexture);
texture->create_from_image(img);
- if (r_error)
+ if (r_error) {
*r_error = OK;
+ }
return texture;
}
void ResourceFormatDDS::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("dds");
}
bool ResourceFormatDDS::handles_type(const String &p_type) const {
-
return ClassDB::is_parent_class(p_type, "Texture2D");
}
String ResourceFormatDDS::get_resource_type(const String &p_path) const {
-
- if (p_path.get_extension().to_lower() == "dds")
+ if (p_path.get_extension().to_lower() == "dds") {
return "ImageTexture";
+ }
return "";
}
diff --git a/modules/dds/texture_loader_dds.h b/modules/dds/texture_loader_dds.h
index ef08967df7..605e791969 100644
--- a/modules/dds/texture_loader_dds.h
+++ b/modules/dds/texture_loader_dds.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/denoise/SCsub b/modules/denoise/SCsub
new file mode 100644
index 0000000000..97feea2b44
--- /dev/null
+++ b/modules/denoise/SCsub
@@ -0,0 +1,129 @@
+#!/usr/bin/env python
+
+import resource_to_cpp
+
+Import("env")
+Import("env_modules")
+
+env_oidn = env_modules.Clone()
+
+# Thirdparty source files
+
+thirdparty_obj = []
+
+thirdparty_dir = "#thirdparty/oidn/"
+thirdparty_sources = [
+ "core/api.cpp",
+ "core/device.cpp",
+ "core/filter.cpp",
+ "core/network.cpp",
+ "core/autoencoder.cpp",
+ "core/transfer_function.cpp",
+ "weights/rtlightmap_hdr.gen.cpp",
+ "mkl-dnn/src/common/batch_normalization.cpp",
+ "mkl-dnn/src/common/concat.cpp",
+ "mkl-dnn/src/common/convolution.cpp",
+ "mkl-dnn/src/common/convolution_pd.cpp",
+ "mkl-dnn/src/common/deconvolution.cpp",
+ "mkl-dnn/src/common/eltwise.cpp",
+ "mkl-dnn/src/common/engine.cpp",
+ "mkl-dnn/src/common/inner_product.cpp",
+ "mkl-dnn/src/common/inner_product_pd.cpp",
+ "mkl-dnn/src/common/lrn.cpp",
+ "mkl-dnn/src/common/memory.cpp",
+ "mkl-dnn/src/common/memory_desc_wrapper.cpp",
+ "mkl-dnn/src/common/mkldnn_debug.cpp",
+ "mkl-dnn/src/common/mkldnn_debug_autogenerated.cpp",
+ "mkl-dnn/src/common/pooling.cpp",
+ "mkl-dnn/src/common/primitive.cpp",
+ "mkl-dnn/src/common/primitive_attr.cpp",
+ "mkl-dnn/src/common/primitive_desc.cpp",
+ "mkl-dnn/src/common/primitive_exec_types.cpp",
+ "mkl-dnn/src/common/primitive_iterator.cpp",
+ "mkl-dnn/src/common/query.cpp",
+ "mkl-dnn/src/common/reorder.cpp",
+ "mkl-dnn/src/common/rnn.cpp",
+ "mkl-dnn/src/common/scratchpad.cpp",
+ "mkl-dnn/src/common/shuffle.cpp",
+ "mkl-dnn/src/common/softmax.cpp",
+ "mkl-dnn/src/common/stream.cpp",
+ "mkl-dnn/src/common/sum.cpp",
+ "mkl-dnn/src/common/utils.cpp",
+ "mkl-dnn/src/common/verbose.cpp",
+ "mkl-dnn/src/cpu/cpu_barrier.cpp",
+ "mkl-dnn/src/cpu/cpu_concat.cpp",
+ "mkl-dnn/src/cpu/cpu_engine.cpp",
+ "mkl-dnn/src/cpu/cpu_memory.cpp",
+ "mkl-dnn/src/cpu/cpu_reducer.cpp",
+ "mkl-dnn/src/cpu/cpu_reorder.cpp",
+ "mkl-dnn/src/cpu/cpu_sum.cpp",
+ "mkl-dnn/src/cpu/jit_avx2_conv_kernel_f32.cpp",
+ "mkl-dnn/src/cpu/jit_avx2_convolution.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_common_conv_kernel.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_common_conv_winograd_kernel_f32.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_common_convolution.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_common_convolution_winograd.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_core_fp32_wino_conv_2x3.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_core_fp32_wino_conv_4x3.cpp",
+ "mkl-dnn/src/cpu/jit_avx512_core_fp32_wino_conv_4x3_kernel.cpp",
+ "mkl-dnn/src/cpu/jit_sse42_conv_kernel_f32.cpp",
+ "mkl-dnn/src/cpu/jit_sse42_convolution.cpp",
+ "mkl-dnn/src/cpu/jit_transpose_src_utils.cpp",
+ "mkl-dnn/src/cpu/jit_uni_eltwise.cpp",
+ "mkl-dnn/src/cpu/jit_uni_pool_kernel_f32.cpp",
+ "mkl-dnn/src/cpu/jit_uni_pooling.cpp",
+ "mkl-dnn/src/cpu/jit_uni_reorder.cpp",
+ "mkl-dnn/src/cpu/jit_uni_reorder_utils.cpp",
+ "mkl-dnn/src/cpu/jit_utils/jit_utils.cpp",
+ "mkl-dnn/src/cpu/jit_utils/jitprofiling/jitprofiling.c",
+ "common/platform.cpp",
+ "common/thread.cpp",
+ "common/tensor.cpp",
+]
+thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+thirdparty_include_dirs = [
+ "",
+ "include",
+ "mkl-dnn/include",
+ "mkl-dnn/src",
+ "mkl-dnn/src/common",
+ "mkl-dnn/src/cpu/xbyak",
+ "mkl-dnn/src/cpu",
+]
+thirdparty_include_dirs = [thirdparty_dir + file for file in thirdparty_include_dirs]
+
+
+env_oidn.Prepend(CPPPATH=thirdparty_include_dirs)
+env_oidn.Append(
+ CPPDEFINES=[
+ "MKLDNN_THR=MKLDNN_THR_SEQ",
+ "OIDN_STATIC_LIB",
+ "__STDC_CONSTANT_MACROS",
+ "__STDC_LIMIT_MACROS",
+ "DISABLE_VERBOSE",
+ "MKLDNN_ENABLE_CONCURRENT_EXEC",
+ "NDEBUG",
+ ]
+)
+
+env_thirdparty = env_oidn.Clone()
+env_thirdparty.disable_warnings()
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+weights_in_path = thirdparty_dir + "weights/rtlightmap_hdr.tza"
+weights_out_path = thirdparty_dir + "weights/rtlightmap_hdr.gen.cpp"
+
+env_thirdparty.Depends(weights_out_path, weights_in_path)
+env_thirdparty.CommandNoCache(weights_out_path, weights_in_path, resource_to_cpp.tza_to_cpp)
+
+# Godot source files
+
+module_obj = []
+
+env_oidn.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/denoise/config.py b/modules/denoise/config.py
new file mode 100644
index 0000000000..49a1f036ed
--- /dev/null
+++ b/modules/denoise/config.py
@@ -0,0 +1,12 @@
+def can_build(env, platform):
+ # Thirdparty dependency OpenImage Denoise includes oneDNN library
+ # which only supports 64-bit architectures.
+ # It's also only relevant for tools build and desktop platforms,
+ # as doing lightmap generation and denoising on Android or HTML5
+ # would be a bit far-fetched.
+ desktop_platforms = ["linuxbsd", "osx", "windows"]
+ return env["tools"] and platform in desktop_platforms and env["bits"] == "64" and env["arch"] != "arm64"
+
+
+def configure(env):
+ pass
diff --git a/modules/denoise/denoise_wrapper.cpp b/modules/denoise/denoise_wrapper.cpp
new file mode 100644
index 0000000000..e71fce5958
--- /dev/null
+++ b/modules/denoise/denoise_wrapper.cpp
@@ -0,0 +1,64 @@
+/*************************************************************************/
+/* denoise_wrapper.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "denoise_wrapper.h"
+#include "thirdparty/oidn/include/OpenImageDenoise/oidn.h"
+#include <stdio.h>
+
+void *oidn_denoiser_init() {
+ OIDNDeviceImpl *device = oidnNewDevice(OIDN_DEVICE_TYPE_CPU);
+ oidnCommitDevice(device);
+ return device;
+}
+
+bool oidn_denoise(void *deviceptr, float *p_floats, int p_width, int p_height) {
+ OIDNDeviceImpl *device = (OIDNDeviceImpl *)deviceptr;
+ OIDNFilter filter = oidnNewFilter(device, "RTLightmap");
+ oidnSetSharedFilterImage(filter, "color", (void *)p_floats, OIDN_FORMAT_FLOAT3, p_width, p_height, 0, 0, 0);
+ oidnSetSharedFilterImage(filter, "output", (void *)p_floats, OIDN_FORMAT_FLOAT3, p_width, p_height, 0, 0, 0);
+ oidnSetFilter1b(filter, "hdr", true);
+ //oidnSetFilter1f(filter, "hdrScale", 1.0f);
+ oidnCommitFilter(filter);
+ oidnExecuteFilter(filter);
+
+ const char *msg;
+ bool success = true;
+ if (oidnGetDeviceError(device, &msg) != OIDN_ERROR_NONE) {
+ printf("LightmapDenoiser: %s\n", msg);
+ success = false;
+ }
+
+ oidnReleaseFilter(filter);
+ return success;
+}
+
+void oidn_denoiser_finish(void *device) {
+ oidnReleaseDevice((OIDNDeviceImpl *)device);
+}
diff --git a/modules/denoise/denoise_wrapper.h b/modules/denoise/denoise_wrapper.h
new file mode 100644
index 0000000000..25e342bc93
--- /dev/null
+++ b/modules/denoise/denoise_wrapper.h
@@ -0,0 +1,38 @@
+/*************************************************************************/
+/* denoise_wrapper.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 DENOISE_WRAPPER_H
+#define DENOISE_WRAPPER_H
+
+void *oidn_denoiser_init();
+bool oidn_denoise(void *device, float *p_floats, int p_width, int p_height);
+void oidn_denoiser_finish(void *device);
+
+#endif // DENOISE_WRAPPER_H
diff --git a/modules/denoise/lightmap_denoiser.cpp b/modules/denoise/lightmap_denoiser.cpp
new file mode 100644
index 0000000000..003bc832b0
--- /dev/null
+++ b/modules/denoise/lightmap_denoiser.cpp
@@ -0,0 +1,62 @@
+/*************************************************************************/
+/* lightmap_denoiser.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "lightmap_denoiser.h"
+#include "denoise_wrapper.h"
+
+LightmapDenoiser *LightmapDenoiserOIDN::create_oidn_denoiser() {
+ return memnew(LightmapDenoiserOIDN);
+}
+
+void LightmapDenoiserOIDN::make_default_denoiser() {
+ create_function = create_oidn_denoiser;
+}
+
+Ref<Image> LightmapDenoiserOIDN::denoise_image(const Ref<Image> &p_image) {
+ Ref<Image> img = p_image->duplicate();
+
+ img->convert(Image::FORMAT_RGBF);
+
+ Vector<uint8_t> data = img->get_data();
+ if (!oidn_denoise(device, (float *)data.ptrw(), img->get_width(), img->get_height())) {
+ return p_image;
+ }
+
+ img->create(img->get_width(), img->get_height(), false, img->get_format(), data);
+ return img;
+}
+
+LightmapDenoiserOIDN::LightmapDenoiserOIDN() {
+ device = oidn_denoiser_init();
+}
+
+LightmapDenoiserOIDN::~LightmapDenoiserOIDN() {
+ oidn_denoiser_finish(device);
+}
diff --git a/modules/mono/glue/string_name_glue.h b/modules/denoise/lightmap_denoiser.h
index 88354ddd84..f1992a1733 100644
--- a/modules/mono/glue/string_name_glue.h
+++ b/modules/denoise/lightmap_denoiser.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* string_name_glue.h */
+/* lightmap_denoiser.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,27 +28,29 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef STRING_NAME_GLUE_H
-#define STRING_NAME_GLUE_H
+#ifndef LIGHTMAP_DENOISER_H
+#define LIGHTMAP_DENOISER_H
-#ifdef MONO_GLUE_ENABLED
+#include "core/object/class_db.h"
+#include "scene/3d/lightmapper.h"
-#include "core/string_name.h"
+struct OIDNDeviceImpl;
-#include "../mono_gd/gd_mono_marshal.h"
+class LightmapDenoiserOIDN : public LightmapDenoiser {
+ GDCLASS(LightmapDenoiserOIDN, LightmapDenoiser);
-StringName *godot_icall_StringName_Ctor(MonoString *p_path);
+protected:
+ void *device = nullptr;
-void godot_icall_StringName_Dtor(StringName *p_ptr);
+public:
+ static LightmapDenoiser *create_oidn_denoiser();
-MonoString *godot_icall_StringName_operator_String(StringName *p_np);
+ Ref<Image> denoise_image(const Ref<Image> &p_image) override;
-MonoBoolean godot_icall_StringName_is_empty(StringName *p_ptr);
+ static void make_default_denoiser();
-// Register internal calls
+ LightmapDenoiserOIDN();
+ ~LightmapDenoiserOIDN();
+};
-void godot_register_string_name_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // STRING_NAME_GLUE_H
+#endif // LIGHTMAP_DENOISER_H
diff --git a/modules/denoise/register_types.cpp b/modules/denoise/register_types.cpp
new file mode 100644
index 0000000000..936e5f604d
--- /dev/null
+++ b/modules/denoise/register_types.cpp
@@ -0,0 +1,40 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+#include "core/config/engine.h"
+#include "lightmap_denoiser.h"
+
+void register_denoise_types() {
+ LightmapDenoiserOIDN::make_default_denoiser();
+}
+
+void unregister_denoise_types() {
+}
diff --git a/modules/denoise/register_types.h b/modules/denoise/register_types.h
new file mode 100644
index 0000000000..516a91b134
--- /dev/null
+++ b/modules/denoise/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 DENOISE_REGISTER_TYPES_H
+#define DENOISE_REGISTER_TYPES_H
+
+void register_denoise_types();
+void unregister_denoise_types();
+
+#endif // DENOISE_REGISTER_TYPES_H
diff --git a/modules/denoise/resource_to_cpp.py b/modules/denoise/resource_to_cpp.py
new file mode 100644
index 0000000000..6c83277355
--- /dev/null
+++ b/modules/denoise/resource_to_cpp.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+
+## ======================================================================== ##
+## Copyright 2009-2019 Intel Corporation ##
+## ##
+## Licensed under the Apache License, Version 2.0 (the "License"); ##
+## you may not use this file except in compliance with the License. ##
+## You may obtain a copy of the License at ##
+## ##
+## http://www.apache.org/licenses/LICENSE-2.0 ##
+## ##
+## Unless required by applicable law or agreed to in writing, software ##
+## distributed under the License is distributed on an "AS IS" BASIS, ##
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ##
+## See the License for the specific language governing permissions and ##
+## limitations under the License. ##
+## ======================================================================== ##
+
+import os
+from array import array
+
+# Generates a C++ file from the specified binary resource file
+def generate(in_path, out_path):
+
+ namespace = "oidn::weights"
+ scopes = namespace.split("::")
+
+ file_name = os.path.basename(in_path)
+ var_name = os.path.splitext(file_name)[0]
+
+ with open(in_path, "rb") as in_file, open(out_path, "w") as out_file:
+ # Header
+ out_file.write("// Generated from: %s\n" % file_name)
+ out_file.write("#include <cstddef>\n\n")
+
+ # Open the namespaces
+ for s in scopes:
+ out_file.write("namespace %s {\n" % s)
+ if scopes:
+ out_file.write("\n")
+
+ # Read the file
+ in_data = array("B", in_file.read())
+
+ # Write the size
+ out_file.write("//const size_t %s_size = %d;\n\n" % (var_name, len(in_data)))
+
+ # Write the data
+ out_file.write("unsigned char %s[] = {" % var_name)
+ for i in range(len(in_data)):
+ c = in_data[i]
+ if i > 0:
+ out_file.write(",")
+ if (i + 1) % 20 == 1:
+ out_file.write("\n")
+ out_file.write("%d" % c)
+ out_file.write("\n};\n")
+
+ # Close the namespaces
+ if scopes:
+ out_file.write("\n")
+ for scope in reversed(scopes):
+ out_file.write("} // namespace %s\n" % scope)
+
+
+def tza_to_cpp(target, source, env):
+ for x in zip(source, target):
+ generate(str(x[0]), str(x[1]))
diff --git a/modules/enet/SCsub b/modules/enet/SCsub
index c8f4b3885e..580e5a3eb0 100644
--- a/modules/enet/SCsub
+++ b/modules/enet/SCsub
@@ -7,6 +7,8 @@ env_enet = env_modules.Clone()
# Thirdparty source files
+thirdparty_obj = []
+
if env["builtin_enet"]:
thirdparty_dir = "#thirdparty/enet/"
thirdparty_sources = [
@@ -26,6 +28,16 @@ if env["builtin_enet"]:
env_thirdparty = env_enet.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_enet.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-env_enet.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
index 860da32a22..6c713fa1ce 100644
--- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
+++ b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
@@ -5,10 +5,12 @@
</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.
+ ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol).
+ [b]Note:[/b] ENet only uses UDP, not TCP. When forwarding the server port to make your server accessible on the public Internet, you only need to forward the server port in UDP. You can use the [UPNP] class to try to forward the server port automatically when starting the server.
</description>
<tutorials>
- <link>https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html</link>
- <link>http://enet.bespin.org/usergroup0.html</link>
+ <link title="High-level multiplayer">https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html</link>
+ <link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link>
</tutorials>
<methods>
<method name="close_connection">
@@ -128,7 +130,7 @@
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" 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.
+ 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. This is done to combat latency and reduces ordering restrictions on packets. The delivery status of a packet in one channel won't stall the delivery of other packets in another channel.
</member>
<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.
@@ -141,7 +143,7 @@
Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server.
</member>
<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.
+ 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 packets, and one for unreliable packets. The 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. See [member channel_count] for more information about ENet channels.
</member>
<member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" />
<member name="use_dtls" type="bool" setter="set_dtls_enabled" getter="is_dtls_enabled" default="false">
diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp
index 444ffae713..66db9ab84e 100644
--- a/modules/enet/networked_multiplayer_enet.cpp
+++ b/modules/enet/networked_multiplayer_enet.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,21 +34,18 @@
#include "core/os/os.h"
void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
-
transfer_mode = p_mode;
}
-NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {
+NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {
return transfer_mode;
}
void NetworkedMultiplayerENet::set_target_peer(int p_peer) {
-
target_peer = p_peer;
}
int NetworkedMultiplayerENet::get_packet_peer() const {
-
ERR_FAIL_COND_V_MSG(!active, 1, "The multiplayer instance isn't currently active.");
ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
@@ -56,7 +53,6 @@ int NetworkedMultiplayerENet::get_packet_peer() const {
}
int NetworkedMultiplayerENet::get_packet_channel() const {
-
ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active.");
ERR_FAIL_COND_V(incoming_packets.size() == 0, -1);
@@ -64,7 +60,6 @@ int NetworkedMultiplayerENet::get_packet_channel() const {
}
int NetworkedMultiplayerENet::get_last_packet_channel() const {
-
ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active.");
ERR_FAIL_COND_V(!current_packet.packet, -1);
@@ -72,7 +67,6 @@ int NetworkedMultiplayerENet::get_last_packet_channel() const {
}
Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {
-
ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The port number must be set between 0 and 65535 (inclusive).");
ERR_FAIL_COND_V_MSG(p_max_clients < 1 || p_max_clients > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive).");
@@ -110,6 +104,7 @@ Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int
if (dtls_enabled) {
enet_host_dtls_server_setup(host, dtls_key.ptr(), dtls_cert.ptr());
}
+ enet_host_refuse_new_connections(host, refuse_connections);
#endif
_setup_compressor();
@@ -120,8 +115,8 @@ Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int
connection_status = CONNECTION_CONNECTED;
return OK;
}
-Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) {
+Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) {
ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The server port number must be set between 0 and 65535 (inclusive).");
ERR_FAIL_COND_V_MSG(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER, "The client port number must be set between 0 and 65535 (inclusive).");
@@ -166,6 +161,7 @@ Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_por
if (dtls_enabled) {
enet_host_dtls_client_setup(host, dtls_cert.ptr(), dtls_verify, p_address.utf8().get_data());
}
+ enet_host_refuse_new_connections(host, refuse_connections);
#endif
_setup_compressor();
@@ -213,7 +209,6 @@ Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_por
}
void NetworkedMultiplayerENet::poll() {
-
ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active.");
_pop_current_packet();
@@ -221,9 +216,9 @@ void NetworkedMultiplayerENet::poll() {
ENetEvent event;
/* Keep servicing until there are no available events left in queue. */
while (true) {
-
- if (!host || !active) // Might have been disconnected while emitting a notification
+ if (!host || !active) { // Might have been disconnected while emitting a notification
return;
+ }
int ret = enet_host_service(host, &event, 0);
@@ -267,14 +262,15 @@ void NetworkedMultiplayerENet::poll() {
if (server) {
// Do not notify other peers when server_relay is disabled.
- if (!server_relay)
+ if (!server_relay) {
break;
+ }
// Someone connected, notify all the peers available
for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
-
- if (E->key() == *new_id)
+ if (E->key() == *new_id) {
continue;
+ }
// Send existing peers to new peer
ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
@@ -287,13 +283,11 @@ void NetworkedMultiplayerENet::poll() {
enet_peer_send(E->get(), SYSCH_CONFIG, packet);
}
} else {
-
emit_signal("connection_succeeded");
}
} break;
case ENET_EVENT_TYPE_DISCONNECT: {
-
// Reset the peer's client information.
int *id = (int *)event.peer->data;
@@ -307,18 +301,16 @@ void NetworkedMultiplayerENet::poll() {
}
if (!server) {
-
// Client just disconnected from server.
emit_signal("server_disconnected");
close_connection();
return;
} else if (server_relay) {
-
// Server just received a client disconnect and is in relay mode, notify everyone else.
for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
-
- if (E->key() == *id)
+ if (E->key() == *id) {
continue;
+ }
ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
@@ -332,7 +324,6 @@ void NetworkedMultiplayerENet::poll() {
memdelete(id);
} break;
case ENET_EVENT_TYPE_RECEIVE: {
-
if (event.channelID == SYSCH_CONFIG) {
// Some config message
ERR_CONTINUE(event.packet->dataLength < 8);
@@ -345,13 +336,11 @@ void NetworkedMultiplayerENet::poll() {
switch (msg) {
case SYSMSG_ADD_PEER: {
-
peer_map[id] = nullptr;
emit_signal("peer_connected", id);
} break;
case SYSMSG_REMOVE_PEER: {
-
peer_map.erase(id);
emit_signal("peer_disconnected", id);
} break;
@@ -359,7 +348,6 @@ void NetworkedMultiplayerENet::poll() {
enet_packet_destroy(event.packet);
} else if (event.channelID < channel_count) {
-
Packet packet;
packet.packet = event.packet;
@@ -391,9 +379,9 @@ void NetworkedMultiplayerENet::poll() {
incoming_packets.push_back(packet);
// And make copies for sending
for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
-
- if (uint32_t(E->key()) == source) // Do not resend to self
+ if (uint32_t(E->key()) == source) { // Do not resend to self
continue;
+ }
ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags);
@@ -405,9 +393,9 @@ void NetworkedMultiplayerENet::poll() {
// And make copies for sending
for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
-
- if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded
+ if (uint32_t(E->key()) == source || E->key() == -target) { // Do not resend to self, also do not send to excluded
continue;
+ }
ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags);
@@ -428,7 +416,6 @@ void NetworkedMultiplayerENet::poll() {
enet_peer_send(peer_map[target], event.channelID, packet.packet);
}
} else {
-
incoming_packets.push_back(packet);
}
@@ -452,7 +439,6 @@ bool NetworkedMultiplayerENet::is_server() const {
}
void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {
-
ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active.");
_pop_current_packet();
@@ -484,7 +470,6 @@ void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {
}
void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
-
ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active.");
ERR_FAIL_COND_MSG(!is_server(), "Can't disconnect a peer when not acting as a server.");
ERR_FAIL_COND_MSG(!peer_map.has(p_peer), vformat("Peer ID %d not found in the list of peers.", p_peer));
@@ -497,7 +482,6 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
// notify everyone else, send disconnect signal & remove from peer_map like in poll()
if (server_relay) {
for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
-
if (E->key() == p_peer) {
continue;
}
@@ -509,8 +493,9 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
}
}
- if (id)
+ if (id) {
memdelete(id);
+ }
emit_signal("peer_disconnected", p_peer);
peer_map.erase(p_peer);
@@ -520,12 +505,10 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
}
int NetworkedMultiplayerENet::get_available_packet_count() const {
-
return incoming_packets.size();
}
Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
-
ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available.");
_pop_current_packet();
@@ -540,7 +523,6 @@ Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buff
}
Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
-
ERR_FAIL_COND_V_MSG(!active, ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
@@ -549,10 +531,11 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
switch (transfer_mode) {
case TRANSFER_MODE_UNRELIABLE: {
- if (always_ordered)
+ if (always_ordered) {
packet_flags = 0;
- else
+ } else {
packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
+ }
channel = SYSCH_UNRELIABLE;
} break;
case TRANSFER_MODE_UNRELIABLE_ORDERED: {
@@ -565,13 +548,13 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
} break;
}
- if (transfer_channel > SYSCH_CONFIG)
+ if (transfer_channel > SYSCH_CONFIG) {
channel = transfer_channel;
+ }
Map<int, ENetPeer *>::Element *E = nullptr;
if (target_peer != 0) {
-
E = peer_map.find(ABS(target_peer));
ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
}
@@ -582,7 +565,6 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
copymem(&packet->data[8], p_buffer, p_buffer_size);
if (server) {
-
if (target_peer == 0) {
enet_host_broadcast(host, channel, packet);
} else if (target_peer < 0) {
@@ -592,9 +574,9 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
int exclude = -target_peer;
for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {
-
- if (F->key() == exclude) // Exclude packet
+ if (F->key() == exclude) { // Exclude packet
continue;
+ }
ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
@@ -606,7 +588,6 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
enet_peer_send(E->get(), channel, packet);
}
} else {
-
ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast
}
@@ -617,12 +598,10 @@ Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer
}
int NetworkedMultiplayerENet::get_max_packet_size() const {
-
return 1 << 24; // Anything is good
}
void NetworkedMultiplayerENet::_pop_current_packet() {
-
if (current_packet.packet) {
enet_packet_destroy(current_packet.packet);
current_packet.packet = nullptr;
@@ -632,16 +611,13 @@ void NetworkedMultiplayerENet::_pop_current_packet() {
}
NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
-
return connection_status;
}
uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
-
uint32_t hash = 0;
while (hash == 0 || hash == 1) {
-
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_ticks_usec());
hash = hash_djb2_one_32(
@@ -660,33 +636,32 @@ uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
}
int NetworkedMultiplayerENet::get_unique_id() const {
-
ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active.");
return unique_id;
}
void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
-
refuse_connections = p_enable;
+#ifdef GODOT_ENET
+ if (active) {
+ enet_host_refuse_new_connections(host, p_enable);
+ }
+#endif
}
bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
-
return refuse_connections;
}
void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
-
compression_mode = p_mode;
}
NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {
-
return compression_mode;
}
size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
-
NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
if (size_t(enet->src_compressor_mem.size()) < inLimit) {
@@ -727,11 +702,13 @@ size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *
}
int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);
- if (ret < 0)
+ if (ret < 0) {
return 0;
+ }
- if (ret > int(outLimit))
+ if (ret > int(outLimit)) {
return 0; // Do not bother
+ }
copymem(outData, enet->dst_compressor_mem.ptr(), ret);
@@ -739,20 +716,16 @@ size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *
}
size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
-
NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
int ret = -1;
switch (enet->compression_mode) {
case COMPRESS_FASTLZ: {
-
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
} break;
case COMPRESS_ZLIB: {
-
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
} break;
case COMPRESS_ZSTD: {
-
ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
} break;
default: {
@@ -766,11 +739,8 @@ size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8
}
void NetworkedMultiplayerENet::_setup_compressor() {
-
switch (compression_mode) {
-
case COMPRESS_NONE: {
-
enet_host_compress(host, nullptr);
} break;
case COMPRESS_RANGE_CODER: {
@@ -779,19 +749,16 @@ void NetworkedMultiplayerENet::_setup_compressor() {
case COMPRESS_FASTLZ:
case COMPRESS_ZLIB:
case COMPRESS_ZSTD: {
-
enet_host_compress(host, &enet_compressor);
} break;
}
}
void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
-
// Nothing to do
}
IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
-
ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), IP_Address(), vformat("Peer ID %d not found in the list of peers.", p_peer_id));
ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, IP_Address(), "Can't get the address of peers other than the server (ID -1) when acting as a client.");
ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, IP_Address(), vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id));
@@ -807,7 +774,6 @@ IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
}
int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
-
ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), 0, vformat("Peer ID %d not found in the list of peers.", p_peer_id));
ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, 0, "Can't get the address of peers other than the server (ID -1) when acting as a client.");
ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, 0, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id));
@@ -819,7 +785,6 @@ int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
}
void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) {
-
ERR_FAIL_COND_MSG(p_channel < -1 || p_channel >= channel_count, vformat("The transfer channel must be set between 0 and %d, inclusive (got %d).", channel_count - 1, p_channel));
ERR_FAIL_COND_MSG(p_channel == SYSCH_CONFIG, vformat("The channel %d is reserved.", SYSCH_CONFIG));
transfer_channel = p_channel;
@@ -830,7 +795,6 @@ int NetworkedMultiplayerENet::get_transfer_channel() const {
}
void NetworkedMultiplayerENet::set_channel_count(int p_channel) {
-
ERR_FAIL_COND_MSG(active, "The channel count can't be set while the multiplayer instance is active.");
ERR_FAIL_COND_MSG(p_channel < SYSCH_MAX, vformat("The channel count must be greater than or equal to %d to account for reserved channels (got %d).", SYSCH_MAX, p_channel));
channel_count = p_channel;
@@ -859,7 +823,6 @@ bool NetworkedMultiplayerENet::is_server_relay_enabled() const {
}
void NetworkedMultiplayerENet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0));
ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100));
@@ -903,7 +866,6 @@ void NetworkedMultiplayerENet::_bind_methods() {
}
NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
-
active = false;
server = false;
refuse_connections = false;
@@ -929,7 +891,6 @@ NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
}
NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
-
if (active) {
close_connection();
}
diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h
index ff436ce2c0..4baa48be5e 100644
--- a/modules/enet/networked_multiplayer_enet.h
+++ b/modules/enet/networked_multiplayer_enet.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -38,7 +38,6 @@
#include <enet/enet.h>
class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer {
-
GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer);
public:
@@ -86,7 +85,6 @@ private:
Map<int, ENetPeer *> peer_map;
struct Packet {
-
ENetPacket *packet;
int from;
int channel;
@@ -121,11 +119,11 @@ protected:
static void _bind_methods();
public:
- virtual void set_transfer_mode(TransferMode p_mode);
- virtual TransferMode get_transfer_mode() const;
- virtual void set_target_peer(int p_peer);
+ virtual void set_transfer_mode(TransferMode p_mode) override;
+ virtual TransferMode get_transfer_mode() const override;
+ virtual void set_target_peer(int p_peer) override;
- virtual int get_packet_peer() const;
+ virtual int get_packet_peer() const override;
virtual IP_Address get_peer_address(int p_peer_id) const;
virtual int get_peer_port(int p_peer_id) const;
@@ -137,22 +135,22 @@ public:
void disconnect_peer(int p_peer, bool now = false);
- virtual void poll();
+ virtual void poll() override;
- virtual bool is_server() const;
+ virtual bool is_server() const override;
- virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
- virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+ virtual int get_available_packet_count() const override;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- virtual int get_max_packet_size() const;
+ virtual int get_max_packet_size() const override;
- virtual ConnectionStatus get_connection_status() const;
+ virtual ConnectionStatus get_connection_status() const override;
- virtual void set_refuse_new_connections(bool p_enable);
- virtual bool is_refusing_new_connections() const;
+ virtual void set_refuse_new_connections(bool p_enable) override;
+ virtual bool is_refusing_new_connections() const override;
- virtual int get_unique_id() const;
+ virtual int get_unique_id() const override;
void set_compression_mode(CompressionMode p_mode);
CompressionMode get_compression_mode() const;
diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp
index 27f27196d6..8da2d17e13 100644
--- a/modules/enet/register_types.cpp
+++ b/modules/enet/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,13 +29,12 @@
/*************************************************************************/
#include "register_types.h"
-#include "core/error_macros.h"
+#include "core/error/error_macros.h"
#include "networked_multiplayer_enet.h"
static bool enet_ok = false;
void register_enet_types() {
-
if (enet_initialize() != 0) {
ERR_PRINT("ENet initialization failure");
} else {
@@ -46,7 +45,7 @@ void register_enet_types() {
}
void unregister_enet_types() {
-
- if (enet_ok)
+ if (enet_ok) {
enet_deinitialize();
+ }
}
diff --git a/modules/enet/register_types.h b/modules/enet/register_types.h
index cac0a4f7ee..75f4cba61b 100644
--- a/modules/enet/register_types.h
+++ b/modules/enet/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/etc/SCsub b/modules/etc/SCsub
index 383bbf83c3..9b46f17916 100644
--- a/modules/etc/SCsub
+++ b/modules/etc/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_etc = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
# Not unbundled so far since not widespread as shared library
thirdparty_dir = "#thirdparty/etc2comp/"
thirdparty_sources = [
@@ -31,7 +34,15 @@ env_etc.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_etc.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
# Godot source files
-env_etc.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_etc.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/etc/image_etc.cpp b/modules/etc/image_compress_etc.cpp
index 223830f445..41cbbe3f54 100644
--- a/modules/etc/image_etc.cpp
+++ b/modules/etc/image_compress_etc.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* image_etc.cpp */
+/* image_compress_etc.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,13 +28,15 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "image_etc.h"
-#include "Etc.h"
-#include "EtcFilter.h"
-#include "core/image.h"
+#include "image_compress_etc.h"
+
+#include "core/io/image.h"
#include "core/os/copymem.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
+
+#include <Etc.h>
+#include <EtcFilter.h>
static Image::Format _get_etc2_mode(Image::UsedChannels format) {
switch (format) {
@@ -106,7 +108,6 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f
// If VRAM compression is using ETC, but image has alpha, convert to RGBA4444 or LA8
// This saves space while maintaining the alpha channel
if (detected_channels == Image::USED_CHANNELS_RGBA) {
-
if (p_img->has_mipmaps()) {
// Image doesn't support mipmaps with RGBA4444 textures
p_img->clear_mipmaps();
@@ -114,7 +115,6 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f
p_img->convert(Image::FORMAT_RGBA4444);
return;
} else if (detected_channels == Image::USE_CHANNELS_LA) {
-
p_img->convert(Image::FORMAT_LA8);
return;
}
@@ -127,8 +127,9 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f
Ref<Image> img = p_img->duplicate();
- if (img->get_format() != Image::FORMAT_RGBA8)
+ if (img->get_format() != Image::FORMAT_RGBA8) {
img->convert(Image::FORMAT_RGBA8); //still uses RGBA to convert
+ }
if (img->has_mipmaps()) {
if (next_power_of_2(imgw) != imgw || next_power_of_2(imgh) != imgh) {
@@ -165,12 +166,13 @@ static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_f
int encoding_time = 0;
float effort = 0.0; //default, reasonable time
- if (p_lossy_quality > 0.75)
- effort = 0.4;
- else if (p_lossy_quality > 0.85)
- effort = 0.6;
- else if (p_lossy_quality > 0.95)
- effort = 0.8;
+ if (p_lossy_quality > 0.95) {
+ effort = 80;
+ } else if (p_lossy_quality > 0.85) {
+ effort = 60;
+ } else if (p_lossy_quality > 0.75) {
+ effort = 40;
+ }
Etc::ErrorMetric error_metric = Etc::ErrorMetric::RGBX; // NOTE: we can experiment with other error metrics
Etc::Image::Format etc2comp_etc_format = _image_format_to_etc2comp_format(etc_format);
@@ -219,7 +221,6 @@ static void _compress_etc2(Image *p_img, float p_lossy_quality, Image::UsedChann
}
void _register_etc_compress_func() {
-
Image::_image_compress_etc1_func = _compress_etc1;
Image::_image_compress_etc2_func = _compress_etc2;
}
diff --git a/modules/etc/image_etc.h b/modules/etc/image_compress_etc.h
index 7b4f26e127..44a06194e9 100644
--- a/modules/etc/image_etc.h
+++ b/modules/etc/image_compress_etc.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* image_etc.h */
+/* image_compress_etc.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,9 +28,9 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef IMAGE_ETC1_H
-#define IMAGE_ETC1_H
+#ifndef IMAGE_COMPRESS_ETC_H
+#define IMAGE_COMPRESS_ETC_H
void _register_etc_compress_func();
-#endif // IMAGE_ETC_H
+#endif // IMAGE_COMPRESS_ETC_H
diff --git a/modules/etc/register_types.cpp b/modules/etc/register_types.cpp
index 26809e0de9..b165bccb3e 100644
--- a/modules/etc/register_types.cpp
+++ b/modules/etc/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "register_types.h"
-#include "image_etc.h"
+#include "image_compress_etc.h"
#include "texture_loader_pkm.h"
static Ref<ResourceFormatPKM> resource_loader_pkm;
void register_etc_types() {
-
resource_loader_pkm.instance();
ResourceLoader::add_resource_format_loader(resource_loader_pkm);
@@ -44,7 +43,6 @@ void register_etc_types() {
}
void unregister_etc_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_pkm);
resource_loader_pkm.unref();
}
diff --git a/modules/etc/register_types.h b/modules/etc/register_types.h
index 247c7213af..e8cbb635ae 100644
--- a/modules/etc/register_types.h
+++ b/modules/etc/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/etc/texture_loader_pkm.cpp b/modules/etc/texture_loader_pkm.cpp
index bfb2098dff..b0ea109f76 100644
--- a/modules/etc/texture_loader_pkm.cpp
+++ b/modules/etc/texture_loader_pkm.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -43,18 +43,20 @@ struct ETC1Header {
};
RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
- if (r_error)
+ if (r_error) {
*r_error = ERR_CANT_OPEN;
+ }
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
- if (!f)
+ if (!f) {
return RES();
+ }
FileAccessRef fref(f);
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CORRUPT;
+ }
ERR_FAIL_COND_V_MSG(err != OK, RES(), "Unable to open PKM texture file '" + p_path + "'.");
@@ -87,8 +89,9 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path,
Ref<ImageTexture> texture = memnew(ImageTexture);
texture->create_from_image(img);
- if (r_error)
+ if (r_error) {
*r_error = OK;
+ }
f->close();
memdelete(f);
@@ -96,18 +99,16 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path,
}
void ResourceFormatPKM::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("pkm");
}
bool ResourceFormatPKM::handles_type(const String &p_type) const {
-
return ClassDB::is_parent_class(p_type, "Texture2D");
}
String ResourceFormatPKM::get_resource_type(const String &p_path) const {
-
- if (p_path.get_extension().to_lower() == "pkm")
+ if (p_path.get_extension().to_lower() == "pkm") {
return "ImageTexture";
+ }
return "";
}
diff --git a/modules/etc/texture_loader_pkm.h b/modules/etc/texture_loader_pkm.h
index 6507e0bdec..67fbee3a7e 100644
--- a/modules/etc/texture_loader_pkm.h
+++ b/modules/etc/texture_loader_pkm.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/fbx/README.md b/modules/fbx/README.md
new file mode 100644
index 0000000000..2a2f186463
--- /dev/null
+++ b/modules/fbx/README.md
@@ -0,0 +1,196 @@
+# Open Source FBX Specification for the Importer
+
+The goal of this document is to make everything in FBX clearly stated, any errors will be corrected over time this
+is a first draft.
+
+## fbx parser - originally from assimp
+
+- Folder: /modules/fbx/fbx_parser
+- Upstream: assimp
+- Original Version: git (308db73d0b3c2d1870cd3e465eaa283692a4cf23, 2019)
+- License: BSD-3-Clause
+
+This can never be updated from upstream, we have heavily modified the parser to provide memory safety and add some
+functionality. If anything we should give this parser back to assimp at some point as it has a lot of new features.
+
+# Updating assimp fbx parser
+
+Don't. it's not possible the code is rewritten in many areas to remove thirdparty deps and various bugs are fixed.
+
+Many days were put into rewriting the parser to use safe code and safe memory accessors.
+
+# File Headers
+
+FBX Binaries start with the header "Kaydara FBX Binary"
+
+FBX ASCII documents contain a larger header, sometimes with copyright information for a file.
+
+Detecting these is pretty simple.
+
+# What is an OP link?
+It's an object to property link. It lists the properties for that object in some cases. Source and destination based by
+ID.
+
+# What is a OO link?
+Its an object to object link, it contains the ID source and destination ID.
+
+# FBX Node connections
+
+Nodes in FBX are connected using OO links, This means Object to Object.
+
+FBX has a single other kind of link which is Object Property, this is used for Object to Property Links, this can be
+ extra attributes, defaults, or even some simple settings.
+
+# Bones / Joints / Locators
+
+Bones in FBX are nodes, they initially have the Model:: Type, then have links to SubDeformer the sub deformer
+is part of the skin there is also an explicit Skin link, which then links to the geometry using OO links in the
+document.
+
+# Rotation Order in FBX compared to Godot
+
+**Godot uses the rotation order:** YXZ
+
+**FBX has dynamic rotation order to prevent gimbal lock with complex animations**
+
+```cpp
+enum RotOrder {
+ RotOrder_EulerXYZ = 0
+ RotOrder_EulerXZY,
+ RotOrder_EulerYZX,
+ RotOrder_EulerYXZ,
+ RotOrder_EulerZXY,
+ RotOrder_EulerZYX,
+ RotOrder_SphericXYZ // nobody uses this - as far as we can tell
+};
+```
+
+
+# Pivot transforms
+
+### Pivot description:
+- Maya and 3DS max consider everything to be in node space (bones joints, skins, lights, cameras, etc)
+- Everything is a node, this means essentially nodes are auto or variants
+- They are local to the node in the tree.
+- They are used to calculate where a node is in space
+```c++
+// For a better reference you can check editor_scene_importer_fbx.h
+// references: GenFBXTransform / read the data in
+// references: ComputePivotTransform / run the calculation
+// This is the local pivot transform for the node, not the global transforms
+Transform ComputePivotTransform(
+ Transform chain[TransformationComp_MAXIMUM],
+ Transform &geometric_transform) {
+ // Maya pivots
+ Transform T = chain[TransformationComp_Translation];
+ Transform Roff = chain[TransformationComp_RotationOffset];
+ Transform Rp = chain[TransformationComp_RotationPivot];
+ Transform Rpre = chain[TransformationComp_PreRotation];
+ Transform R = chain[TransformationComp_Rotation];
+ Transform Rpost = chain[TransformationComp_PostRotation];
+ Transform Soff = chain[TransformationComp_ScalingOffset];
+ Transform Sp = chain[TransformationComp_ScalingPivot];
+ Transform S = chain[TransformationComp_Scaling];
+
+ // 3DS Max Pivots
+ Transform OT = chain[TransformationComp_GeometricTranslation];
+ Transform OR = chain[TransformationComp_GeometricRotation];
+ Transform OS = chain[TransformationComp_GeometricScaling];
+
+ // Calculate 3DS max pivot transform - use geometric space (e.g doesn't effect children nodes only the current node)
+ geometric_transform = OT * OR * OS;
+ // Calculate standard maya pivots
+ return T * Roff * Rp * Rpre * R * Rpost.inverse() * Rp.inverse() * Soff * Sp * S * Sp.inverse();
+}
+```
+
+# Transform inheritance for FBX Nodes
+
+The goal of below is to explain why they implement this in the first place.
+
+The use case is to make nodes have an option to override their local scaling or to make scaling influenced by orientation, which i would imagine would be useful for when you need to rotate a node and the child to scale based on the orientation rather than setting on the rotation matrix planes.
+```cpp
+// not modified the formatting here since this code must remain clear
+enum TransformInheritance {
+ Transform_RrSs = 0,
+ // Parent Rotation * Local Rotation * Parent Scale * Local Scale -- Parent Rotation Offset * Parent ScalingOffset (Local scaling is offset by rotation of parent node)
+ Transform_RSrs = 1, // Parent Rotation * Parent Scale * Local Rotation * Local Scale -- Parent * Local (normal mode)
+ Transform_Rrs = 2, // Parent Rotation * Local Rotation * Local Scale -- Node transform scale is the only relevant component
+ TransformInheritance_MAX // end-of-enum sentinel
+};
+
+enum TransformInheritance {
+ Transform_RrSs = 0,
+ // Local scaling is offset by rotation of parent node
+ Transform_RSrs = 1,
+ // Parent * Local (normal mode)
+ Transform_Rrs = 2,
+ // Node transform scale is the only relevant component
+ TransformInheritance_MAX // end-of-enum sentinel
+};
+```
+
+# Axis in FBX
+
+Godot has one format for the declared axis
+
+AXIS X, AXIS Y, -AXIS Z
+
+FBX supports any format you can think of. As it has to support Maya and 3DS Max.
+
+#### FBX File Header
+```json
+GlobalSettings: {
+ Version: 1000
+ Properties70: {
+ P: "UpAxis", "int", "Integer", "",1
+ P: "UpAxisSign", "int", "Integer", "",1
+ P: "FrontAxis", "int", "Integer", "",2
+ P: "FrontAxisSign", "int", "Integer", "",1
+ P: "CoordAxis", "int", "Integer", "",0
+ P: "CoordAxisSign", "int", "Integer", "",1
+ P: "OriginalUpAxis", "int", "Integer", "",1
+ P: "OriginalUpAxisSign", "int", "Integer", "",1
+ P: "UnitScaleFactor", "double", "Number", "",1
+ P: "OriginalUnitScaleFactor", "double", "Number", "",1
+ P: "AmbientColor", "ColorRGB", "Color", "",0,0,0
+ P: "DefaultCamera", "KString", "", "", "Producer Perspective"
+ P: "TimeMode", "enum", "", "",6
+ P: "TimeProtocol", "enum", "", "",2
+ P: "SnapOnFrameMode", "enum", "", "",0
+ P: "TimeSpanStart", "KTime", "Time", "",0
+ P: "TimeSpanStop", "KTime", "Time", "",92372316000
+ P: "CustomFrameRate", "double", "Number", "",-1
+ P: "TimeMarker", "Compound", "", ""
+ P: "CurrentTimeMarker", "int", "Integer", "",-1
+ }
+}
+```
+
+#### FBX FILE declares axis dynamically using FBX header
+Coord is X
+Up is Y
+Front is Z
+
+#### GODOT - constant reference point
+Coord is X positive,
+Y is up positive,
+Front is -Z negative
+
+### Explaining MeshGeometry indexing
+
+Reference type declared:
+- Direct (directly related to the mapping information type)
+- IndexToDirect (Map with key value, meaning depends on the MappingInformationType)
+
+ControlPoint is a vertex
+* None The mapping is undetermined.
+* ByVertex There will be one mapping coordinate for each surface control point/vertex.
+ * If you have direct reference type vertices [x]
+ * If you have IndexToDirect reference type the UV
+* ByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part. (Sorted by polygon, referencing vertex)
+* ByPolygon There can be only one mapping coordinate for the whole polygon.
+ * One mapping per polygon polygon x has this normal x
+ * For each vertex of the polygon then set the normal to x
+* ByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements. (Mapping is referencing the edge id)
+* AllSame There can be only one mapping coordinate for the whole surface.
diff --git a/modules/fbx/SCsub b/modules/fbx/SCsub
new file mode 100644
index 0000000000..84220a66fa
--- /dev/null
+++ b/modules/fbx/SCsub
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_fbx = env_modules.Clone()
+
+# Make includes relative to the folder path specified here so our includes are clean
+env_fbx.Prepend(CPPPATH=["#modules/fbx/"])
+
+# Godot's own source files
+env_fbx.add_source_files(env.modules_sources, "tools/*.cpp")
+env_fbx.add_source_files(env.modules_sources, "data/*.cpp")
+env_fbx.add_source_files(env.modules_sources, "fbx_parser/*.cpp")
+env_fbx.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/fbx/config.py b/modules/fbx/config.py
new file mode 100644
index 0000000000..78929800b3
--- /dev/null
+++ b/modules/fbx/config.py
@@ -0,0 +1,16 @@
+def can_build(env, platform):
+ return env["tools"]
+
+
+def configure(env):
+ pass
+
+
+def get_doc_classes():
+ return [
+ "EditorSceneImporterFBX",
+ ]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/fbx/data/fbx_anim_container.h b/modules/fbx/data/fbx_anim_container.h
new file mode 100644
index 0000000000..8c25d65871
--- /dev/null
+++ b/modules/fbx/data/fbx_anim_container.h
@@ -0,0 +1,46 @@
+/*************************************************************************/
+/* fbx_anim_container.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_ANIM_CONTAINER_H
+#define FBX_ANIM_CONTAINER_H
+
+#include "core/math/vector3.h"
+
+// Generic keyframes 99.99 percent of files will be vector3, except if quat interp is used, or visibility tracks
+// FBXTrack is used in a map in the implementation in fbx/editor_scene_importer_fbx.cpp
+// to avoid having to rewrite the entire logic I refactored this into the code instead.
+// once it works I can rewrite so we can add the fun misc features / small features
+struct FBXTrack {
+ bool has_default = false;
+ Vector3 default_value;
+ std::map<int64_t, Vector3> keyframes;
+};
+
+#endif //MODEL_ABSTRACTION_ANIM_CONTAINER_H
diff --git a/modules/fbx/data/fbx_bone.cpp b/modules/fbx/data/fbx_bone.cpp
new file mode 100644
index 0000000000..38dada33af
--- /dev/null
+++ b/modules/fbx/data/fbx_bone.cpp
@@ -0,0 +1,56 @@
+/*************************************************************************/
+/* fbx_bone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "fbx_bone.h"
+
+#include "fbx_node.h"
+#include "import_state.h"
+
+Ref<FBXNode> FBXSkinDeformer::get_link(const ImportState &state) const {
+ print_verbose("bone name: " + bone->bone_name);
+
+ // safe for when deformers must be polyfilled when skin has different count of binds to bones in the scene ;)
+ if (!cluster) {
+ return nullptr;
+ }
+
+ ERR_FAIL_COND_V_MSG(cluster->TargetNode() == nullptr, nullptr, "bone has invalid target node");
+
+ Ref<FBXNode> link_node;
+ uint64_t id = cluster->TargetNode()->ID();
+ if (state.fbx_target_map.has(id)) {
+ link_node = state.fbx_target_map[id];
+ } else {
+ print_error("link node not found for " + itos(id));
+ }
+
+ // the node in space this is for, like if it's FOR a target.
+ return link_node;
+}
diff --git a/modules/mono/glue/base_object_glue.h b/modules/fbx/data/fbx_bone.h
index 67769f3061..efba147b89 100644
--- a/modules/mono/glue/base_object_glue.h
+++ b/modules/fbx/data/fbx_bone.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* base_object_glue.h */
+/* fbx_bone.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,46 +28,63 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef BASE_OBJECT_GLUE_H
-#define BASE_OBJECT_GLUE_H
+#ifndef FBX_BONE_H
+#define FBX_BONE_H
-#ifdef MONO_GLUE_ENABLED
+#include "fbx_node.h"
+#include "import_state.h"
-#include "core/class_db.h"
-#include "core/object.h"
+#include "fbx_parser/FBXDocument.h"
-#include "../mono_gd/gd_mono_marshal.h"
+struct PivotTransform;
-Object *godot_icall_Object_Ctor(MonoObject *p_obj);
+struct FBXBone : public Reference {
+ uint64_t parent_bone_id = 0;
+ uint64_t bone_id = 0;
-void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr);
+ bool valid_parent = false; // if the parent bone id is set up.
+ String bone_name = String(); // bone name
-void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer);
+ bool is_root_bone() const {
+ return !valid_parent;
+ }
-void godot_icall_Object_ConnectEventSignals(Object *p_ptr);
+ // Godot specific data
+ int godot_bone_id = -2; // godot internal bone id assigned after import
-MethodBind *godot_icall_Object_ClassDB_get_method(StringName *p_type, MonoString *p_method);
+ // if a bone / armature is the root then FBX skeleton will contain the bone not any other skeleton.
+ // this is to support joints by themselves in scenes
+ bool valid_armature_id = false;
+ uint64_t armature_id = 0;
-MonoObject *godot_icall_Object_weakref(Object *p_ptr);
+ /* link node is the parent bone */
+ mutable const FBXDocParser::Geometry *geometry = nullptr;
+ mutable const FBXDocParser::ModelLimbNode *limb_node = nullptr;
-Error godot_icall_SignalAwaiter_connect(Object *p_source, StringName *p_signal, Object *p_target, MonoObject *p_awaiter);
+ void set_node(Ref<FBXNode> p_node) {
+ node = p_node;
+ }
-// DynamicGodotObject
+ // Stores the pivot xform for this bone
-MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr);
+ Ref<FBXNode> node = nullptr;
+ Ref<FBXBone> parent_bone = nullptr;
+ Ref<FBXSkeleton> fbx_skeleton = nullptr;
+};
-MonoBoolean godot_icall_DynamicGodotObject_InvokeMember(Object *p_ptr, MonoString *p_name, MonoArray *p_args, MonoObject **r_result);
+struct FBXSkinDeformer {
+ FBXSkinDeformer(Ref<FBXBone> p_bone, const FBXDocParser::Cluster *p_cluster) :
+ cluster(p_cluster), bone(p_bone) {}
+ ~FBXSkinDeformer() {}
+ const FBXDocParser::Cluster *cluster;
+ Ref<FBXBone> bone;
-MonoBoolean godot_icall_DynamicGodotObject_GetMember(Object *p_ptr, MonoString *p_name, MonoObject **r_result);
+ /* get associate model - the model can be invalid sometimes */
+ Ref<FBXBone> get_associate_model() const {
+ return bone->parent_bone;
+ }
-MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *p_name, MonoObject *p_value);
+ Ref<FBXNode> get_link(const ImportState &state) const;
+};
-MonoString *godot_icall_Object_ToString(Object *p_ptr);
-
-// Register internal calls
-
-void godot_register_object_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // BASE_OBJECT_GLUE_H
+#endif // FBX_BONE_H
diff --git a/modules/fbx/data/fbx_material.cpp b/modules/fbx/data/fbx_material.cpp
new file mode 100644
index 0000000000..5995097b2f
--- /dev/null
+++ b/modules/fbx/data/fbx_material.cpp
@@ -0,0 +1,464 @@
+/*************************************************************************/
+/* fbx_material.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "fbx_material.h"
+#include "scene/resources/material.h"
+#include "scene/resources/texture.h"
+#include "tools/validation_tools.h"
+
+String FBXMaterial::get_material_name() const {
+ return material_name;
+}
+
+void FBXMaterial::set_imported_material(FBXDocParser::Material *p_material) {
+ material = p_material;
+}
+
+void FBXMaterial::add_search_string(String p_filename, String p_current_directory, String search_directory, Vector<String> &texture_search_paths) {
+ if (search_directory.is_empty()) {
+ texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(p_filename));
+ } else {
+ texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(search_directory + "/" + p_filename));
+ texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file("../" + search_directory + "/" + p_filename));
+ }
+}
+
+String find_file(const String &p_base, const String &p_file_to_find) {
+ _Directory dir;
+ dir.open(p_base);
+
+ dir.list_dir_begin();
+ String n = dir.get_next();
+ while (n != String()) {
+ if (n == "." || n == "..") {
+ n = dir.get_next();
+ continue;
+ }
+ if (dir.current_is_dir()) {
+ // Don't use `path_to` or the returned path will be wrong.
+ const String f = find_file(p_base + "/" + n, p_file_to_find);
+ if (f != "") {
+ return f;
+ }
+ } else if (n == p_file_to_find) {
+ return p_base + "/" + n;
+ }
+ n = dir.get_next();
+ }
+ dir.list_dir_end();
+
+ return String();
+}
+
+// fbx will not give us good path information and let's not regex them to fix them
+// no relative paths are in fbx generally they have a rel field but it's populated incorrectly by the SDK.
+String FBXMaterial::find_texture_path_by_filename(const String p_filename, const String p_current_directory) {
+ _Directory dir;
+ Vector<String> paths;
+ add_search_string(p_filename, p_current_directory, "", paths);
+ add_search_string(p_filename, p_current_directory, "texture", paths);
+ add_search_string(p_filename, p_current_directory, "textures", paths);
+ add_search_string(p_filename, p_current_directory, "Textures", paths);
+ add_search_string(p_filename, p_current_directory, "materials", paths);
+ add_search_string(p_filename, p_current_directory, "mats", paths);
+ add_search_string(p_filename, p_current_directory, "pictures", paths);
+ add_search_string(p_filename, p_current_directory, "images", paths);
+
+ for (int i = 0; i < paths.size(); i++) {
+ if (dir.file_exists(paths[i])) {
+ return paths[i];
+ }
+ }
+
+ // We were not able to find the texture in the common locations,
+ // try to find it into the project globally.
+ // The common textures can be stored into one of those folders:
+ // res://asset
+ // res://texture
+ // res://material
+ // res://mat
+ // res://image
+ // res://picture
+ //
+ // Note the folders can also be called with custom names, like:
+ // res://my_assets
+ // since the keyword `asset` is into the directory name the textures will be
+ // searched there too.
+
+ dir.open("res://");
+ dir.list_dir_begin();
+ String n = dir.get_next();
+ while (n != String()) {
+ if (n == "." || n == "..") {
+ n = dir.get_next();
+ continue;
+ }
+ if (dir.current_is_dir()) {
+ const String lower_n = n.to_lower();
+ if (
+ // Don't need to use plural.
+ lower_n.find("asset") >= 0 ||
+ lower_n.find("texture") >= 0 ||
+ lower_n.find("material") >= 0 ||
+ lower_n.find("mat") >= 0 ||
+ lower_n.find("image") >= 0 ||
+ lower_n.find("picture") >= 0) {
+ // Don't use `path_to` or the returned path will be wrong.
+ const String f = find_file(String("res://") + n, p_filename);
+ if (f != "") {
+ return f;
+ }
+ }
+ }
+ n = dir.get_next();
+ }
+ dir.list_dir_end();
+
+ return "";
+}
+
+template <class T>
+T extract_from_prop(FBXDocParser::PropertyPtr prop, const T &p_default, const std::string &p_name, const String &p_type) {
+ ERR_FAIL_COND_V_MSG(prop == nullptr, p_default, "invalid property passed to extractor");
+ const FBXDocParser::TypedProperty<T> *val = dynamic_cast<const FBXDocParser::TypedProperty<T> *>(prop);
+
+ ERR_FAIL_COND_V_MSG(val == nullptr, p_default, "The FBX is corrupted, the property `" + String(p_name.c_str()) + "` is a `" + String(typeid(*prop).name()) + "` but should be a " + p_type);
+ // Make sure to not lost any eventual opacity.
+ return val->Value();
+}
+
+Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) {
+ ERR_FAIL_COND_V(material == nullptr, nullptr);
+
+ const String p_fbx_current_directory = state.path;
+
+ Ref<StandardMaterial3D> spatial_material;
+ spatial_material.instance();
+
+ // read the material file
+ // is material two sided
+ // read material name
+ print_verbose("[material] material name: " + ImportUtils::FBXNodeToName(material->Name()));
+
+ material_name = ImportUtils::FBXNodeToName(material->Name());
+
+ for (const std::pair<std::string, const FBXDocParser::Texture *> iter : material->Textures()) {
+ const uint64_t texture_id = iter.second->ID();
+ const std::string &fbx_mapping_name = iter.first;
+ const FBXDocParser::Texture *fbx_texture_data = iter.second;
+ const String absolute_texture_path = iter.second->FileName().c_str();
+ const String texture_name = absolute_texture_path.get_file();
+ const String file_extension = absolute_texture_path.get_extension().to_upper();
+
+ const String debug_string = "texture id: " + itos(texture_id) + " texture name: " + String(iter.second->Name().c_str()) + " mapping name: " + String(fbx_mapping_name.c_str());
+ // remember errors STILL need this string at the end for when you aren't in verbose debug mode :) they need context for when you're not verbose-ing.
+ print_verbose(debug_string);
+
+ const String file_extension_uppercase = file_extension.to_upper();
+
+ if (fbx_transparency_flags.count(fbx_mapping_name) > 0) {
+ // just enable it later let's make this fine-tuned.
+ spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
+ }
+
+ ERR_CONTINUE_MSG(file_extension.is_empty(), "your texture has no file extension so we had to ignore it, let us know if you think this is wrong file an issue on github! " + debug_string);
+ ERR_CONTINUE_MSG(fbx_texture_map.count(fbx_mapping_name) <= 0, "This material has a texture with mapping name: " + String(fbx_mapping_name.c_str()) + " which is not yet supported by this importer. Consider opening an issue so we can support it.");
+ ERR_CONTINUE_MSG(
+ file_extension_uppercase != "PNG" &&
+ file_extension_uppercase != "JPEG" &&
+ file_extension_uppercase != "JPG" &&
+ file_extension_uppercase != "TGA" &&
+ file_extension_uppercase != "WEBP" &&
+ file_extension_uppercase != "DDS",
+ "The FBX file contains a texture with an unrecognized extension: " + file_extension_uppercase);
+
+ print_verbose("Getting FBX mapping mode for " + String(fbx_mapping_name.c_str()));
+ // get the texture map type
+ const StandardMaterial3D::TextureParam mapping_mode = fbx_texture_map.at(fbx_mapping_name);
+ print_verbose("Set FBX mapping mode to " + get_texture_param_name(mapping_mode));
+
+ Ref<Texture> texture;
+ print_verbose("texture mapping name: " + texture_name);
+
+ if (state.cached_image_searches.has(texture_name)) {
+ texture = state.cached_image_searches[texture_name];
+ } else {
+ String path = find_texture_path_by_filename(texture_name, p_fbx_current_directory);
+ if (!path.is_empty()) {
+ Ref<Texture2D> image_texture = ResourceLoader::load(path);
+
+ ERR_CONTINUE(image_texture.is_null());
+
+ texture = image_texture;
+ state.cached_image_searches.insert(texture_name, texture);
+ print_verbose("Created texture from loaded image file.");
+
+ } else if (fbx_texture_data != nullptr && fbx_texture_data->Media() != nullptr && fbx_texture_data->Media()->IsEmbedded()) {
+ // This is an embedded texture. Extract it.
+ Ref<Image> image;
+ //image.instance(); // oooo double instance bug? why make Image::_png_blah call
+
+ const String extension = texture_name.get_extension().to_upper();
+ if (extension == "PNG") {
+ // The stored file is a PNG.
+ image = Image::_png_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
+ ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded PNG image load fail.");
+
+ } else if (
+ extension == "JPEG" ||
+ extension == "JPG") {
+ // The stored file is a JPEG.
+ image = Image::_jpg_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
+ ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded JPEG image load fail.");
+
+ } else if (extension == "TGA") {
+ // The stored file is a TGA.
+ image = Image::_tga_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
+ ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded TGA image load fail.");
+
+ } else if (extension == "WEBP") {
+ // The stored file is a WEBP.
+ image = Image::_webp_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
+ ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded WEBP image load fail.");
+
+ // } else if (extension == "DDS") {
+ // // In this moment is not possible to extract a DDS from a buffer, TODO consider add it to godot. See `textureloader_dds.cpp::load().
+ // // The stored file is a DDS.
+ } else {
+ ERR_CONTINUE_MSG(true, "The embedded image with extension: " + extension + " is not yet supported. Open an issue please.");
+ }
+
+ Ref<ImageTexture> image_texture;
+ image_texture.instance();
+ image_texture->create_from_image(image);
+
+ texture = image_texture;
+
+ // TODO: this is potentially making something with the same name have a match incorrectly USE FBX ID as Hash. #fuck it later.
+ state.cached_image_searches[texture_name] = texture;
+ print_verbose("Created texture from embedded image.");
+ } else {
+ ERR_CONTINUE_MSG(true, "The FBX texture, with name: `" + texture_name + "`, is not found into the project nor is stored as embedded file. Make sure to insert the texture as embedded file or into the project, then reimport.");
+ }
+ }
+
+ spatial_material->set_texture(mapping_mode, texture);
+ }
+
+ if (spatial_material.is_valid()) {
+ spatial_material->set_name(material_name);
+ }
+
+ /// ALL below is related to properties
+ for (FBXDocParser::LazyPropertyMap::value_type iter : material->Props()->GetLazyProperties()) {
+ const std::string name = iter.first;
+
+ if (name.empty()) {
+ continue;
+ }
+
+ PropertyDesc desc = PROPERTY_DESC_NOT_FOUND;
+ if (fbx_properties_desc.count(name) > 0) {
+ desc = fbx_properties_desc.at(name);
+ }
+
+ // check if we can ignore this it will be done at the next phase
+ if (desc == PROPERTY_DESC_NOT_FOUND || desc == PROPERTY_DESC_IGNORE) {
+ // count the texture mapping references. Skip this one if it's found and we can't look up a property value.
+ if (fbx_texture_map.count(name) > 0) {
+ continue; // safe to ignore it's a texture mapping.
+ }
+ }
+
+ if (desc == PROPERTY_DESC_IGNORE) {
+ //WARN_PRINT("[Ignored] The FBX material parameter: `" + String(name.c_str()) + "` is ignored.");
+ continue;
+ } else {
+ print_verbose("FBX Material parameter: " + String(name.c_str()));
+
+ // Check for Diffuse material system / lambert materials / legacy basically
+ if (name == "Diffuse" && !warning_non_pbr_material) {
+ ValidationTracker::get_singleton()->add_validation_error(state.path, "Invalid material settings change to Ai Standard Surface shader, mat name: " + material_name.c_escape());
+ warning_non_pbr_material = true;
+ }
+ }
+
+ // DISABLE when adding support for all weird and wonderful material formats
+ if (desc == PROPERTY_DESC_NOT_FOUND) {
+ continue;
+ }
+
+ ERR_CONTINUE_MSG(desc == PROPERTY_DESC_NOT_FOUND, "The FBX material parameter: `" + String(name.c_str()) + "` was not recognized. Please open an issue so we can add the support to it.");
+
+ const FBXDocParser::PropertyTable *tbl = material->Props();
+ FBXDocParser::PropertyPtr prop = tbl->Get(name);
+
+ ERR_CONTINUE_MSG(prop == nullptr, "This file may be corrupted because is not possible to extract the material parameter: " + String(name.c_str()));
+
+ if (spatial_material.is_null()) {
+ // Done here so if no data no material is created.
+ spatial_material.instance();
+ }
+
+ const FBXDocParser::TypedProperty<real_t> *real_value = dynamic_cast<const FBXDocParser::TypedProperty<real_t> *>(prop);
+ const FBXDocParser::TypedProperty<Vector3> *vector_value = dynamic_cast<const FBXDocParser::TypedProperty<Vector3> *>(prop);
+
+ if (!real_value && !vector_value) {
+ //WARN_PRINT("unsupported datatype in property: " + String(name.c_str()));
+ continue;
+ }
+
+ if (vector_value && !real_value) {
+ if (vector_value->Value() == Vector3(0, 0, 0) && !real_value) {
+ continue;
+ }
+ }
+
+ switch (desc) {
+ case PROPERTY_DESC_ALBEDO_COLOR: {
+ if (vector_value) {
+ const Vector3 &color = vector_value->Value();
+ // Make sure to not lost any eventual opacity.
+ if (color != Vector3(0, 0, 0)) {
+ Color c = Color();
+ c[0] = color[0];
+ c[1] = color[1];
+ c[2] = color[2];
+ spatial_material->set_albedo(c);
+ }
+
+ } else if (real_value) {
+ print_error("albedo is unsupported format?");
+ }
+ } break;
+ case PROPERTY_DESC_TRANSPARENT: {
+ if (real_value) {
+ const real_t opacity = real_value->Value();
+ if (opacity < (1.0 - CMP_EPSILON)) {
+ Color c = spatial_material->get_albedo();
+ c.a = opacity;
+ spatial_material->set_albedo(c);
+
+ spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
+ spatial_material->set_depth_draw_mode(BaseMaterial3D::DEPTH_DRAW_OPAQUE_ONLY);
+ }
+ } else if (vector_value) {
+ print_error("unsupported transparent desc type vector!");
+ }
+ } break;
+ case PROPERTY_DESC_SPECULAR: {
+ if (real_value) {
+ print_verbose("specular real value: " + rtos(real_value->Value()));
+ spatial_material->set_specular(MIN(1.0, real_value->Value()));
+ }
+
+ if (vector_value) {
+ print_error("unsupported specular vector value: " + vector_value->Value());
+ }
+ } break;
+
+ case PROPERTY_DESC_SPECULAR_COLOR: {
+ if (vector_value) {
+ print_error("unsupported specular color: " + vector_value->Value());
+ }
+ } break;
+ case PROPERTY_DESC_SHINYNESS: {
+ if (real_value) {
+ print_error("unsupported shinyness:" + rtos(real_value->Value()));
+ }
+ } break;
+ case PROPERTY_DESC_METALLIC: {
+ if (real_value) {
+ print_verbose("metallic real value: " + rtos(real_value->Value()));
+ spatial_material->set_metallic(MIN(1.0f, real_value->Value()));
+ } else {
+ print_error("unsupported value type for metallic");
+ }
+ } break;
+ case PROPERTY_DESC_ROUGHNESS: {
+ if (real_value) {
+ print_verbose("roughness real value: " + rtos(real_value->Value()));
+ spatial_material->set_roughness(MIN(1.0f, real_value->Value()));
+ } else {
+ print_error("unsupported value type for roughness");
+ }
+ } break;
+ case PROPERTY_DESC_COAT: {
+ if (real_value) {
+ print_verbose("clearcoat real value: " + rtos(real_value->Value()));
+ spatial_material->set_clearcoat(MIN(1.0f, real_value->Value()));
+ } else {
+ print_error("unsupported value type for clearcoat");
+ }
+ } break;
+ case PROPERTY_DESC_COAT_ROUGHNESS: {
+ // meaning is that approx equal to zero is disabled not actually zero. ;)
+ if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) {
+ print_verbose("clearcoat real value: " + rtos(real_value->Value()));
+ spatial_material->set_clearcoat_gloss(1.0 - real_value->Value());
+ } else {
+ print_error("unsupported value type for clearcoat gloss");
+ }
+ } break;
+ case PROPERTY_DESC_EMISSIVE: {
+ if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) {
+ print_verbose("Emissive real value: " + rtos(real_value->Value()));
+ spatial_material->set_emission_energy(real_value->Value());
+ } else if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
+ const Vector3 &color = vector_value->Value();
+ Color c;
+ c[0] = color[0];
+ c[1] = color[1];
+ c[2] = color[2];
+ spatial_material->set_emission(c);
+ }
+ } break;
+ case PROPERTY_DESC_EMISSIVE_COLOR: {
+ if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
+ const Vector3 &color = vector_value->Value();
+ Color c;
+ c[0] = color[0];
+ c[1] = color[1];
+ c[2] = color[2];
+ spatial_material->set_emission(c);
+ } else {
+ print_error("unsupported value type for emissive color");
+ }
+ } break;
+ case PROPERTY_DESC_NOT_FOUND:
+ case PROPERTY_DESC_IGNORE:
+ break;
+ default:
+ break;
+ }
+ }
+
+ return spatial_material;
+}
diff --git a/modules/fbx/data/fbx_material.h b/modules/fbx/data/fbx_material.h
new file mode 100644
index 0000000000..e974a256f6
--- /dev/null
+++ b/modules/fbx/data/fbx_material.h
@@ -0,0 +1,286 @@
+/*************************************************************************/
+/* fbx_material.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_MATERIAL_H
+#define FBX_MATERIAL_H
+
+#include "tools/import_utils.h"
+
+#include "core/object/reference.h"
+#include "core/string/ustring.h"
+
+struct FBXMaterial : public Reference {
+ String material_name = String();
+ bool warning_non_pbr_material = false;
+ FBXDocParser::Material *material = nullptr;
+
+ /* Godot materials
+ *** Texture Maps:
+ * Albedo - color, texture
+ * Metallic - specular, metallic, texture
+ * Roughness - roughness, texture
+ * Emission - color, texture
+ * Normal Map - scale, texture
+ * Ambient Occlusion - texture
+ * Refraction - scale, texture
+ *** Has Settings for:
+ * UV1 - SCALE, OFFSET
+ * UV2 - SCALE, OFFSET
+ *** Flags for
+ * Transparent
+ * Cull Mode
+ */
+
+ enum class MapMode {
+ AlbedoM = 0,
+ MetallicM,
+ SpecularM,
+ EmissionM,
+ RoughnessM,
+ NormalM,
+ AmbientOcclusionM,
+ RefractionM,
+ ReflectionM,
+ };
+
+ /* Returns the string representation of the TextureParam enum */
+ static String get_texture_param_name(StandardMaterial3D::TextureParam param) {
+ switch (param) {
+ case StandardMaterial3D::TEXTURE_ALBEDO:
+ return "TEXTURE_ALBEDO";
+ case StandardMaterial3D::TEXTURE_METALLIC:
+ return "TEXTURE_METALLIC";
+ case StandardMaterial3D::TEXTURE_ROUGHNESS:
+ return "TEXTURE_ROUGHNESS";
+ case StandardMaterial3D::TEXTURE_EMISSION:
+ return "TEXTURE_EMISSION";
+ case StandardMaterial3D::TEXTURE_NORMAL:
+ return "TEXTURE_NORMAL";
+ case StandardMaterial3D::TEXTURE_RIM:
+ return "TEXTURE_RIM";
+ case StandardMaterial3D::TEXTURE_CLEARCOAT:
+ return "TEXTURE_CLEARCOAT";
+ case StandardMaterial3D::TEXTURE_FLOWMAP:
+ return "TEXTURE_FLOWMAP";
+ case StandardMaterial3D::TEXTURE_AMBIENT_OCCLUSION:
+ return "TEXTURE_AMBIENT_OCCLUSION";
+ // case StandardMaterial3D::TEXTURE_DEPTH: // TODO: work out how to make this function again!
+ // return "TEXTURE_DEPTH";
+ case StandardMaterial3D::TEXTURE_SUBSURFACE_SCATTERING:
+ return "TEXTURE_SUBSURFACE_SCATTERING";
+ // case StandardMaterial3D::TEXTURE_TRANSMISSION: // TODO: work out how to make this function again!
+ // return "TEXTURE_TRANSMISSION";
+ case StandardMaterial3D::TEXTURE_REFRACTION:
+ return "TEXTURE_REFRACTION";
+ case StandardMaterial3D::TEXTURE_DETAIL_MASK:
+ return "TEXTURE_DETAIL_MASK";
+ case StandardMaterial3D::TEXTURE_DETAIL_ALBEDO:
+ return "TEXTURE_DETAIL_ALBEDO";
+ case StandardMaterial3D::TEXTURE_DETAIL_NORMAL:
+ return "TEXTURE_DETAIL_NORMAL";
+ case StandardMaterial3D::TEXTURE_MAX:
+ return "TEXTURE_MAX";
+ default:
+ return "broken horribly";
+ }
+ };
+
+ // TODO make this static?
+ const std::map<std::string, bool> fbx_transparency_flags = {
+ /* Transparent */
+ { "TransparentColor", true },
+ { "Maya|opacity", true }
+ };
+
+ // TODO make this static?
+ const std::map<std::string, StandardMaterial3D::TextureParam> fbx_texture_map = {
+ /* Diffuse */
+ { "Maya|base", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "DiffuseColor", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "Maya|DiffuseTexture", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "Maya|baseColor", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "Maya|baseColor|file", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "3dsMax|Parameters|base_color_map", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "Maya|TEX_color_map|file", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ { "Maya|TEX_color_map", StandardMaterial3D::TextureParam::TEXTURE_ALBEDO },
+ /* Emission */
+ { "EmissiveColor", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "EmissiveFactor", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "Maya|emissionColor", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "Maya|emissionColor|file", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "3dsMax|Parameters|emission_map", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "Maya|TEX_emissive_map", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ { "Maya|TEX_emissive_map|file", StandardMaterial3D::TextureParam::TEXTURE_EMISSION },
+ /* Metallic */
+ { "Maya|metalness", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ { "Maya|metalness|file", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ { "3dsMax|Parameters|metalness_map", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ { "Maya|TEX_metallic_map", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ { "Maya|TEX_metallic_map|file", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+
+ /* Roughness */
+ // Arnold Roughness Map
+ { "Maya|specularRoughness", StandardMaterial3D::TextureParam::TEXTURE_ROUGHNESS },
+
+ { "3dsMax|Parameters|roughness_map", StandardMaterial3D::TextureParam::TEXTURE_ROUGHNESS },
+ { "Maya|TEX_roughness_map", StandardMaterial3D::TextureParam::TEXTURE_ROUGHNESS },
+ { "Maya|TEX_roughness_map|file", StandardMaterial3D::TextureParam::TEXTURE_ROUGHNESS },
+
+ /* Normal */
+ { "NormalMap", StandardMaterial3D::TextureParam::TEXTURE_NORMAL },
+ //{ "Bump", Material::TextureParam::TEXTURE_NORMAL },
+ //{ "3dsMax|Parameters|bump_map", Material::TextureParam::TEXTURE_NORMAL },
+ { "Maya|NormalTexture", StandardMaterial3D::TextureParam::TEXTURE_NORMAL },
+ //{ "Maya|normalCamera", Material::TextureParam::TEXTURE_NORMAL },
+ //{ "Maya|normalCamera|file", Material::TextureParam::TEXTURE_NORMAL },
+ { "Maya|TEX_normal_map", StandardMaterial3D::TextureParam::TEXTURE_NORMAL },
+ { "Maya|TEX_normal_map|file", StandardMaterial3D::TextureParam::TEXTURE_NORMAL },
+ /* AO */
+ { "Maya|TEX_ao_map", StandardMaterial3D::TextureParam::TEXTURE_AMBIENT_OCCLUSION },
+ { "Maya|TEX_ao_map|file", StandardMaterial3D::TextureParam::TEXTURE_AMBIENT_OCCLUSION },
+
+ // TODO: specular workflow conversion
+ // { "SpecularColor", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ // { "Maya|specularColor", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ // { "Maya|SpecularTexture", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ // { "Maya|SpecularTexture|file", StandardMaterial3D::TextureParam::TEXTURE_METALLIC },
+ // { "ShininessExponent", SpatialMaterial::TextureParam::UNSUPPORTED },
+ // { "ReflectionFactor", SpatialMaterial::TextureParam::UNSUPPORTED },
+
+ //{ "TransparentColor",SpatialMaterial::TextureParam::TEXTURE_CHANNEL_ALPHA },
+ //{ "TransparencyFactor",SpatialMaterial::TextureParam::TEXTURE_CHANNEL_ALPHA }
+
+ // TODO: diffuse roughness
+ //{ "Maya|diffuseRoughness", SpatialMaterial::TextureParam::UNSUPPORTED },
+ //{ "Maya|diffuseRoughness|file", SpatialMaterial::TextureParam::UNSUPPORTED },
+
+ };
+
+ // TODO make this static?
+ enum PropertyDesc {
+ PROPERTY_DESC_NOT_FOUND,
+ PROPERTY_DESC_ALBEDO_COLOR,
+ PROPERTY_DESC_TRANSPARENT,
+ PROPERTY_DESC_METALLIC,
+ PROPERTY_DESC_ROUGHNESS,
+ PROPERTY_DESC_SPECULAR,
+ PROPERTY_DESC_SPECULAR_COLOR,
+ PROPERTY_DESC_SHINYNESS,
+ PROPERTY_DESC_COAT,
+ PROPERTY_DESC_COAT_ROUGHNESS,
+ PROPERTY_DESC_EMISSIVE,
+ PROPERTY_DESC_EMISSIVE_COLOR,
+ PROPERTY_DESC_IGNORE
+ };
+
+ const std::map<std::string, PropertyDesc> fbx_properties_desc = {
+ /* Albedo */
+ { "DiffuseColor", PROPERTY_DESC_ALBEDO_COLOR },
+ { "Maya|baseColor", PROPERTY_DESC_ALBEDO_COLOR },
+
+ /* Specular */
+ { "Maya|specular", PROPERTY_DESC_SPECULAR },
+ { "Maya|specularColor", PROPERTY_DESC_SPECULAR_COLOR },
+
+ /* Specular roughness - arnold roughness map */
+ { "Maya|specularRoughness", PROPERTY_DESC_ROUGHNESS },
+
+ /* Transparent */
+ { "Opacity", PROPERTY_DESC_TRANSPARENT },
+ { "TransparencyFactor", PROPERTY_DESC_TRANSPARENT },
+ { "Maya|opacity", PROPERTY_DESC_TRANSPARENT },
+
+ /* Metallic */
+ { "Shininess", PROPERTY_DESC_METALLIC },
+ { "Reflectivity", PROPERTY_DESC_METALLIC },
+ { "Maya|metalness", PROPERTY_DESC_METALLIC },
+ { "Maya|metallic", PROPERTY_DESC_METALLIC },
+
+ /* Roughness */
+ { "Maya|roughness", PROPERTY_DESC_ROUGHNESS },
+
+ /* Coat */
+ //{ "Maya|coat", PROPERTY_DESC_COAT },
+
+ /* Coat roughness */
+ //{ "Maya|coatRoughness", PROPERTY_DESC_COAT_ROUGHNESS },
+
+ /* Emissive */
+ { "Maya|emission", PROPERTY_DESC_EMISSIVE },
+ { "Maya|emissive", PROPERTY_DESC_EMISSIVE },
+
+ /* Emissive color */
+ { "EmissiveColor", PROPERTY_DESC_EMISSIVE_COLOR },
+ { "Maya|emissionColor", PROPERTY_DESC_EMISSIVE_COLOR },
+
+ /* Ignore */
+ { "Maya|diffuseRoughness", PROPERTY_DESC_IGNORE },
+ { "Maya", PROPERTY_DESC_IGNORE },
+ { "Diffuse", PROPERTY_DESC_ALBEDO_COLOR },
+ { "Maya|TypeId", PROPERTY_DESC_IGNORE },
+ { "Ambient", PROPERTY_DESC_IGNORE },
+ { "AmbientColor", PROPERTY_DESC_IGNORE },
+ { "ShininessExponent", PROPERTY_DESC_IGNORE },
+ { "Specular", PROPERTY_DESC_IGNORE },
+ { "SpecularColor", PROPERTY_DESC_IGNORE },
+ { "SpecularFactor", PROPERTY_DESC_IGNORE },
+ //{ "BumpFactor", PROPERTY_DESC_IGNORE },
+ { "Maya|exitToBackground", PROPERTY_DESC_IGNORE },
+ { "Maya|indirectDiffuse", PROPERTY_DESC_IGNORE },
+ { "Maya|indirectSpecular", PROPERTY_DESC_IGNORE },
+ { "Maya|internalReflections", PROPERTY_DESC_IGNORE },
+ { "DiffuseFactor", PROPERTY_DESC_IGNORE },
+ { "AmbientFactor", PROPERTY_DESC_IGNORE },
+ { "ReflectionColor", PROPERTY_DESC_IGNORE },
+ { "Emissive", PROPERTY_DESC_IGNORE },
+ { "Maya|coatColor", PROPERTY_DESC_IGNORE },
+ { "Maya|coatNormal", PROPERTY_DESC_IGNORE },
+ { "Maya|coatIOR", PROPERTY_DESC_IGNORE },
+ };
+
+ /* storing the texture properties like color */
+ template <class T>
+ struct TexturePropertyMapping : Reference {
+ StandardMaterial3D::TextureParam map_mode = StandardMaterial3D::TextureParam::TEXTURE_ALBEDO;
+ const T property = T();
+ };
+
+ static void add_search_string(String p_filename, String p_current_directory, String search_directory, Vector<String> &texture_search_paths);
+
+ static String find_texture_path_by_filename(const String p_filename, const String p_current_directory);
+
+ String get_material_name() const;
+
+ void set_imported_material(FBXDocParser::Material *p_material);
+
+ Ref<StandardMaterial3D> import_material(ImportState &state);
+};
+
+#endif // FBX_MATERIAL_H
diff --git a/modules/fbx/data/fbx_mesh_data.cpp b/modules/fbx/data/fbx_mesh_data.cpp
new file mode 100644
index 0000000000..883651943e
--- /dev/null
+++ b/modules/fbx/data/fbx_mesh_data.cpp
@@ -0,0 +1,1447 @@
+/*************************************************************************/
+/* fbx_mesh_data.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "fbx_mesh_data.h"
+
+#include "core/templates/local_vector.h"
+#include "scene/resources/mesh.h"
+#include "scene/resources/surface_tool.h"
+
+#include "thirdparty/misc/polypartition.h"
+
+template <class T>
+T collect_first(const Vector<VertexData<T>> *p_data, T p_fall_back) {
+ if (p_data->is_empty()) {
+ return p_fall_back;
+ }
+
+ return (*p_data)[0].data;
+}
+
+template <class T>
+HashMap<int, T> collect_all(const Vector<VertexData<T>> *p_data, HashMap<int, T> p_fall_back) {
+ if (p_data->is_empty()) {
+ return p_fall_back;
+ }
+
+ HashMap<int, T> collection;
+ for (int i = 0; i < p_data->size(); i += 1) {
+ const VertexData<T> &vd = (*p_data)[i];
+ collection[vd.polygon_index] = vd.data;
+ }
+ return collection;
+}
+
+template <class T>
+T collect_average(const Vector<VertexData<T>> *p_data, T p_fall_back) {
+ if (p_data->is_empty()) {
+ return p_fall_back;
+ }
+
+ T combined = (*p_data)[0].data; // Make sure the data is always correctly initialized.
+ print_verbose("size of data: " + itos(p_data->size()));
+ for (int i = 1; i < p_data->size(); i += 1) {
+ combined += (*p_data)[i].data;
+ }
+ combined = combined / real_t(p_data->size());
+
+ return combined.normalized();
+}
+
+HashMap<int, Vector3> collect_normal(const Vector<VertexData<Vector3>> *p_data, HashMap<int, Vector3> p_fall_back) {
+ if (p_data->is_empty()) {
+ return p_fall_back;
+ }
+
+ HashMap<int, Vector3> collection;
+ for (int i = 0; i < p_data->size(); i += 1) {
+ const VertexData<Vector3> &vd = (*p_data)[i];
+ collection[vd.polygon_index] = vd.data;
+ }
+ return collection;
+}
+
+HashMap<int, Vector2> collect_uv(const Vector<VertexData<Vector2>> *p_data, HashMap<int, Vector2> p_fall_back) {
+ if (p_data->is_empty()) {
+ return p_fall_back;
+ }
+
+ HashMap<int, Vector2> collection;
+ for (int i = 0; i < p_data->size(); i += 1) {
+ const VertexData<Vector2> &vd = (*p_data)[i];
+ collection[vd.polygon_index] = vd.data;
+ }
+ return collection;
+}
+
+typedef int Vertex;
+typedef int SurfaceId;
+typedef int PolygonId;
+typedef int DataIndex;
+
+struct SurfaceData {
+ Ref<SurfaceTool> surface_tool;
+ OrderedHashMap<Vertex, int> lookup_table; // proposed fix is to replace lookup_table[vertex_id] to give the position of the vertices_map[int] index.
+ LocalVector<Vertex> vertices_map; // this must be ordered the same as insertion <-- slow to do find() operation.
+ Ref<Material> material;
+ HashMap<PolygonId, Vector<DataIndex>> surface_polygon_vertex;
+ Array morphs;
+};
+
+EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression) {
+ mesh_geometry = p_mesh_geometry;
+ // todo: make this just use a uint64_t FBX ID this is a copy of our original materials unfortunately.
+ const std::vector<const FBXDocParser::Material *> &material_lookup = model->GetMaterials();
+
+ // TODO: perf hotspot on large files
+ // this can be a very large copy
+ std::vector<int> polygon_indices = mesh_geometry->get_polygon_indices();
+ std::vector<Vector3> vertices = mesh_geometry->get_vertices();
+
+ // Phase 1. Parse all FBX data.
+ HashMap<int, Vector3> normals;
+ HashMap<int, HashMap<int, Vector3>> normals_raw = extract_per_vertex_data(
+ vertices.size(),
+ mesh_geometry->get_edge_map(),
+ polygon_indices,
+ mesh_geometry->get_normals(),
+ &collect_all,
+ HashMap<int, Vector3>());
+
+ HashMap<int, Vector2> uvs_0;
+ HashMap<int, HashMap<int, Vector2>> uvs_0_raw = extract_per_vertex_data(
+ vertices.size(),
+ mesh_geometry->get_edge_map(),
+ polygon_indices,
+ mesh_geometry->get_uv_0(),
+ &collect_all,
+ HashMap<int, Vector2>());
+
+ HashMap<int, Vector2> uvs_1;
+ HashMap<int, HashMap<int, Vector2>> uvs_1_raw = extract_per_vertex_data(
+ vertices.size(),
+ mesh_geometry->get_edge_map(),
+ polygon_indices,
+ mesh_geometry->get_uv_1(),
+ &collect_all,
+ HashMap<int, Vector2>());
+
+ HashMap<int, Color> colors;
+ HashMap<int, HashMap<int, Color>> colors_raw = extract_per_vertex_data(
+ vertices.size(),
+ mesh_geometry->get_edge_map(),
+ polygon_indices,
+ mesh_geometry->get_colors(),
+ &collect_all,
+ HashMap<int, Color>());
+
+ // TODO what about tangents?
+ // TODO what about bi-nomials?
+ // TODO there is other?
+
+ HashMap<int, SurfaceId> polygon_surfaces = extract_per_polygon(
+ vertices.size(),
+ polygon_indices,
+ mesh_geometry->get_material_allocation_id(),
+ -1);
+
+ HashMap<String, MorphVertexData> morphs;
+ extract_morphs(mesh_geometry, morphs);
+
+ // TODO please add skinning.
+ //mesh_id = mesh_geometry->ID();
+
+ sanitize_vertex_weights(state);
+
+ // Re organize polygon vertices to to correctly take into account strange
+ // UVs.
+ reorganize_vertices(
+ polygon_indices,
+ vertices,
+ normals,
+ uvs_0,
+ uvs_1,
+ colors,
+ morphs,
+ normals_raw,
+ colors_raw,
+ uvs_0_raw,
+ uvs_1_raw);
+
+ const int color_count = colors.size();
+ print_verbose("Vertex color count: " + itos(color_count));
+
+ // Make sure that from this moment on the mesh_geometry is no used anymore.
+ // This is a safety step, because the mesh_geometry data are no more valid
+ // at this point.
+
+ const int vertex_count = vertices.size();
+
+ print_verbose("Vertex count: " + itos(vertex_count));
+
+ // The map key is the material allocator id that is also used as surface id.
+ HashMap<SurfaceId, SurfaceData> surfaces;
+
+ // Phase 2. For each material create a surface tool (So a different mesh).
+ {
+ if (polygon_surfaces.is_empty()) {
+ // No material, just use the default one with index -1.
+ // Set -1 to all polygons.
+ const int polygon_count = count_polygons(polygon_indices);
+ for (int p = 0; p < polygon_count; p += 1) {
+ polygon_surfaces[p] = -1;
+ }
+ }
+
+ // Create the surface now.
+ for (const int *polygon_id = polygon_surfaces.next(nullptr); polygon_id != nullptr; polygon_id = polygon_surfaces.next(polygon_id)) {
+ const int surface_id = polygon_surfaces[*polygon_id];
+ if (surfaces.has(surface_id) == false) {
+ SurfaceData sd;
+ sd.surface_tool.instance();
+ sd.surface_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
+
+ if (surface_id < 0) {
+ // nothing to do
+ } else if (surface_id < (int)material_lookup.size()) {
+ const FBXDocParser::Material *mat_mapping = material_lookup.at(surface_id);
+ const uint64_t mapping_id = mat_mapping->ID();
+ if (state.cached_materials.has(mapping_id)) {
+ sd.material = state.cached_materials[mapping_id];
+ }
+ } else {
+ WARN_PRINT("out of bounds surface detected, FBX file has corrupt material data");
+ }
+
+ surfaces.set(surface_id, sd);
+ }
+ }
+ }
+
+ // Phase 3. Map the vertices relative to each surface, in this way we can
+ // just insert the vertices that we need per each surface.
+ {
+ PolygonId polygon_index = -1;
+ SurfaceId surface_id = -1;
+ SurfaceData *surface_data = nullptr;
+
+ for (size_t polygon_vertex = 0; polygon_vertex < polygon_indices.size(); polygon_vertex += 1) {
+ if (is_start_of_polygon(polygon_indices, polygon_vertex)) {
+ polygon_index += 1;
+ ERR_FAIL_COND_V_MSG(polygon_surfaces.has(polygon_index) == false, nullptr, "The FBX file is corrupted, This surface_index is not expected.");
+ surface_id = polygon_surfaces[polygon_index];
+ surface_data = surfaces.getptr(surface_id);
+ CRASH_COND(surface_data == nullptr); // Can't be null.
+ }
+
+ const int vertex = get_vertex_from_polygon_vertex(polygon_indices, polygon_vertex);
+
+ // The vertex position in the surface
+ // Uses a lookup table for speed with large scenes
+ bool has_polygon_vertex_index = surface_data->lookup_table.has(vertex);
+ int surface_polygon_vertex_index = -1;
+
+ if (has_polygon_vertex_index) {
+ surface_polygon_vertex_index = surface_data->lookup_table[vertex];
+ } else {
+ surface_polygon_vertex_index = surface_data->vertices_map.size();
+ surface_data->lookup_table[vertex] = surface_polygon_vertex_index;
+ surface_data->vertices_map.push_back(vertex);
+ }
+
+ surface_data->surface_polygon_vertex[polygon_index].push_back(surface_polygon_vertex_index);
+ }
+ }
+
+ //print_verbose("[debug UV 1] UV1: " + itos(uvs_0.size()));
+ //print_verbose("[debug UV 2] UV2: " + itos(uvs_1.size()));
+
+ // Phase 4. Per each surface just insert the vertices and add the indices.
+ for (const SurfaceId *surface_id = surfaces.next(nullptr); surface_id != nullptr; surface_id = surfaces.next(surface_id)) {
+ SurfaceData *surface = surfaces.getptr(*surface_id);
+
+ // Just add the vertices data.
+ for (unsigned int i = 0; i < surface->vertices_map.size(); i += 1) {
+ const Vertex vertex = surface->vertices_map[i];
+
+ // This must be done before add_vertex because the surface tool is
+ // expecting this before the st->add_vertex() call
+ add_vertex(state,
+ surface->surface_tool,
+ state.scale,
+ vertex,
+ vertices,
+ normals,
+ uvs_0,
+ uvs_1,
+ colors);
+ }
+
+ // Triangulate the various polygons and add the indices.
+ for (const PolygonId *polygon_id = surface->surface_polygon_vertex.next(nullptr); polygon_id != nullptr; polygon_id = surface->surface_polygon_vertex.next(polygon_id)) {
+ const Vector<DataIndex> *indices = surface->surface_polygon_vertex.getptr(*polygon_id);
+
+ triangulate_polygon(
+ surface->surface_tool,
+ *indices,
+ surface->vertices_map,
+ vertices);
+ }
+ }
+
+ // Phase 5. Compose the morphs if any.
+ for (const SurfaceId *surface_id = surfaces.next(nullptr); surface_id != nullptr; surface_id = surfaces.next(surface_id)) {
+ SurfaceData *surface = surfaces.getptr(*surface_id);
+
+ for (const String *morph_name = morphs.next(nullptr); morph_name != nullptr; morph_name = morphs.next(morph_name)) {
+ MorphVertexData *morph_data = morphs.getptr(*morph_name);
+
+ // As said by the docs, this is not supposed to be different than
+ // vertex_count.
+ CRASH_COND(morph_data->vertices.size() != vertex_count);
+ CRASH_COND(morph_data->normals.size() != vertex_count);
+
+ Vector3 *vertices_ptr = morph_data->vertices.ptrw();
+ Vector3 *normals_ptr = morph_data->normals.ptrw();
+
+ Ref<SurfaceTool> morph_st;
+ morph_st.instance();
+ morph_st->begin(Mesh::PRIMITIVE_TRIANGLES);
+
+ for (unsigned int vi = 0; vi < surface->vertices_map.size(); vi += 1) {
+ const Vertex vertex = surface->vertices_map[vi];
+ add_vertex(
+ state,
+ morph_st,
+ state.scale,
+ vertex,
+ vertices,
+ normals,
+ uvs_0,
+ uvs_1,
+ colors,
+ vertices_ptr[vertex],
+ normals_ptr[vertex]);
+ }
+
+ if (state.is_blender_fbx) {
+ morph_st->generate_normals();
+ }
+ morph_st->generate_tangents();
+ surface->morphs.push_back(morph_st->commit_to_arrays());
+ }
+ }
+
+ // Phase 6. Compose the mesh and return it.
+ Ref<EditorSceneImporterMesh> mesh;
+ mesh.instance();
+
+ // Add blend shape info.
+ for (const String *morph_name = morphs.next(nullptr); morph_name != nullptr; morph_name = morphs.next(morph_name)) {
+ mesh->add_blend_shape(*morph_name);
+ }
+
+ // TODO always normalized, Why?
+ mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
+
+ // Add surfaces.
+ int in_mesh_surface_id = 0;
+ for (const SurfaceId *surface_id = surfaces.next(nullptr); surface_id != nullptr; surface_id = surfaces.next(surface_id)) {
+ SurfaceData *surface = surfaces.getptr(*surface_id);
+
+ if (state.is_blender_fbx) {
+ surface->surface_tool->generate_normals();
+ }
+ // you can't generate them without a valid uv map.
+ if (uvs_0_raw.size() > 0) {
+ surface->surface_tool->generate_tangents();
+ }
+
+ Array mesh_array = surface->surface_tool->commit_to_arrays();
+ Array blend_shapes = surface->morphs;
+
+ if (surface->material.is_valid()) {
+ mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, mesh_array, blend_shapes, Dictionary(), surface->material, surface->material->get_name());
+ } else {
+ mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, mesh_array, blend_shapes);
+ }
+
+ in_mesh_surface_id += 1;
+ }
+
+ EditorSceneImporterMeshNode3D *godot_mesh = memnew(EditorSceneImporterMeshNode3D);
+ godot_mesh->set_mesh(mesh);
+ return godot_mesh;
+}
+
+void FBXMeshData::sanitize_vertex_weights(const ImportState &state) {
+ const int max_vertex_influence_count = RS::ARRAY_WEIGHTS_SIZE;
+ Map<int, int> skeleton_to_skin_bind_id;
+ // TODO: error's need added
+ const FBXDocParser::Skin *fbx_skin = mesh_geometry->DeformerSkin();
+
+ if (fbx_skin == nullptr || fbx_skin->Clusters().size() == 0) {
+ return; // do nothing
+ }
+
+ //
+ // Precalculate the skin cluster mapping
+ //
+
+ int bind_id = 0;
+ for (const FBXDocParser::Cluster *cluster : fbx_skin->Clusters()) {
+ Ref<FBXBone> bone = state.fbx_bone_map[cluster->TargetNode()->ID()];
+ skeleton_to_skin_bind_id.insert(bone->godot_bone_id, bind_id);
+ bind_id++;
+ }
+
+ for (const Vertex *v = vertex_weights.next(nullptr); v != nullptr; v = vertex_weights.next(v)) {
+ VertexWeightMapping *vm = vertex_weights.getptr(*v);
+ ERR_CONTINUE(vm->bones.size() != vm->weights.size()); // No message, already checked.
+ ERR_CONTINUE(vm->bones_ref.size() != vm->weights.size()); // No message, already checked.
+
+ const int initial_size = vm->weights.size();
+ {
+ // Init bone id
+ int *bones_ptr = vm->bones.ptrw();
+ Ref<FBXBone> *bones_ref_ptr = vm->bones_ref.ptrw();
+
+ for (int i = 0; i < vm->weights.size(); i += 1) {
+ // At this point this is not possible because the skeleton is already initialized.
+ CRASH_COND(bones_ref_ptr[i]->godot_bone_id == -2);
+ bones_ptr[i] = skeleton_to_skin_bind_id[bones_ref_ptr[i]->godot_bone_id];
+ }
+
+ // From this point on the data is no more valid.
+ vm->bones_ref.clear();
+ }
+
+ {
+ // Sort
+ real_t *weights_ptr = vm->weights.ptrw();
+ int *bones_ptr = vm->bones.ptrw();
+ for (int i = 0; i < vm->weights.size(); i += 1) {
+ for (int x = i + 1; x < vm->weights.size(); x += 1) {
+ if (weights_ptr[i] < weights_ptr[x]) {
+ SWAP(weights_ptr[i], weights_ptr[x]);
+ SWAP(bones_ptr[i], bones_ptr[x]);
+ }
+ }
+ }
+ }
+
+ {
+ // Resize
+ vm->weights.resize(max_vertex_influence_count);
+ vm->bones.resize(max_vertex_influence_count);
+ real_t *weights_ptr = vm->weights.ptrw();
+ int *bones_ptr = vm->bones.ptrw();
+ for (int i = initial_size; i < max_vertex_influence_count; i += 1) {
+ weights_ptr[i] = 0.0;
+ bones_ptr[i] = 0;
+ }
+
+ // Normalize
+ real_t sum = 0.0;
+ for (int i = 0; i < max_vertex_influence_count; i += 1) {
+ sum += weights_ptr[i];
+ }
+ if (sum > 0.0) {
+ for (int i = 0; i < vm->weights.size(); i += 1) {
+ weights_ptr[i] = weights_ptr[i] / sum;
+ }
+ }
+ }
+ }
+}
+
+void FBXMeshData::reorganize_vertices(
+ // TODO: perf hotspot on insane files
+ std::vector<int> &r_polygon_indices,
+ std::vector<Vector3> &r_vertices,
+ HashMap<int, Vector3> &r_normals,
+ HashMap<int, Vector2> &r_uv_1,
+ HashMap<int, Vector2> &r_uv_2,
+ HashMap<int, Color> &r_color,
+ HashMap<String, MorphVertexData> &r_morphs,
+ HashMap<int, HashMap<int, Vector3>> &r_normals_raw,
+ HashMap<int, HashMap<int, Color>> &r_colors_raw,
+ HashMap<int, HashMap<int, Vector2>> &r_uv_1_raw,
+ HashMap<int, HashMap<int, Vector2>> &r_uv_2_raw) {
+ // Key: OldVertex; Value: [New vertices];
+ HashMap<int, Vector<int>> duplicated_vertices;
+
+ PolygonId polygon_index = -1;
+ for (int pv = 0; pv < (int)r_polygon_indices.size(); pv += 1) {
+ if (is_start_of_polygon(r_polygon_indices, pv)) {
+ polygon_index += 1;
+ }
+ const Vertex index = get_vertex_from_polygon_vertex(r_polygon_indices, pv);
+
+ bool need_duplication = false;
+ Vector2 this_vert_poly_uv1 = Vector2();
+ Vector2 this_vert_poly_uv2 = Vector2();
+ Vector3 this_vert_poly_normal = Vector3();
+ Color this_vert_poly_color = Color();
+
+ // Take the normal and see if we need to duplicate this polygon.
+ if (r_normals_raw.has(index)) {
+ const HashMap<PolygonId, Vector3> *nrml_arr = r_normals_raw.getptr(index);
+
+ if (nrml_arr->has(polygon_index)) {
+ this_vert_poly_normal = nrml_arr->get(polygon_index);
+ } else if (nrml_arr->has(-1)) {
+ this_vert_poly_normal = nrml_arr->get(-1);
+ } else {
+ print_error("invalid normal detected: " + itos(index) + " polygon index: " + itos(polygon_index));
+ for (const PolygonId *pid = nrml_arr->next(nullptr); pid != nullptr; pid = nrml_arr->next(pid)) {
+ print_verbose("debug contents key: " + itos(*pid));
+
+ if (nrml_arr->has(*pid)) {
+ print_verbose("contents valid: " + nrml_arr->get(*pid));
+ }
+ }
+ }
+
+ // Now, check if we need to duplicate it.
+ for (const PolygonId *pid = nrml_arr->next(nullptr); pid != nullptr; pid = nrml_arr->next(pid)) {
+ if (*pid == polygon_index) {
+ continue;
+ }
+
+ const Vector3 vert_poly_normal = *nrml_arr->getptr(*pid);
+ if ((this_vert_poly_normal - vert_poly_normal).length_squared() > CMP_EPSILON) {
+ // Yes this polygon need duplication.
+ need_duplication = true;
+ break;
+ }
+ }
+ }
+
+ // TODO: make me vertex color
+ // Take the normal and see if we need to duplicate this polygon.
+ if (r_colors_raw.has(index)) {
+ const HashMap<PolygonId, Color> *color_arr = r_colors_raw.getptr(index);
+
+ if (color_arr->has(polygon_index)) {
+ this_vert_poly_color = color_arr->get(polygon_index);
+ } else if (color_arr->has(-1)) {
+ this_vert_poly_color = color_arr->get(-1);
+ } else {
+ print_error("invalid color detected: " + itos(index) + " polygon index: " + itos(polygon_index));
+ for (const PolygonId *pid = color_arr->next(nullptr); pid != nullptr; pid = color_arr->next(pid)) {
+ print_verbose("debug contents key: " + itos(*pid));
+
+ if (color_arr->has(*pid)) {
+ print_verbose("contents valid: " + color_arr->get(*pid));
+ }
+ }
+ }
+
+ // Now, check if we need to duplicate it.
+ for (const PolygonId *pid = color_arr->next(nullptr); pid != nullptr; pid = color_arr->next(pid)) {
+ if (*pid == polygon_index) {
+ continue;
+ }
+
+ const Color vert_poly_color = *color_arr->getptr(*pid);
+ if (!this_vert_poly_color.is_equal_approx(vert_poly_color)) {
+ // Yes this polygon need duplication.
+ need_duplication = true;
+ break;
+ }
+ }
+ }
+
+ // Take the UV1 and UV2 and see if we need to duplicate this polygon.
+ {
+ HashMap<int, HashMap<int, Vector2>> *uv_raw = &r_uv_1_raw;
+ Vector2 *this_vert_poly_uv = &this_vert_poly_uv1;
+ for (int kk = 0; kk < 2; kk++) {
+ if (uv_raw->has(index)) {
+ const HashMap<PolygonId, Vector2> *uvs = uv_raw->getptr(index);
+
+ if (uvs->has(polygon_index)) {
+ // This Polygon has its own uv.
+ (*this_vert_poly_uv) = *uvs->getptr(polygon_index);
+
+ // Check if we need to duplicate it.
+ for (const PolygonId *pid = uvs->next(nullptr); pid != nullptr; pid = uvs->next(pid)) {
+ if (*pid == polygon_index) {
+ continue;
+ }
+ const Vector2 vert_poly_uv = *uvs->getptr(*pid);
+ if (((*this_vert_poly_uv) - vert_poly_uv).length_squared() > CMP_EPSILON) {
+ // Yes this polygon need duplication.
+ need_duplication = true;
+ break;
+ }
+ }
+ } else if (uvs->has(-1)) {
+ // It has the default UV.
+ (*this_vert_poly_uv) = *uvs->getptr(-1);
+ } else if (uvs->size() > 0) {
+ // No uv, this is strange, just take the first and duplicate.
+ (*this_vert_poly_uv) = *uvs->getptr(*uvs->next(nullptr));
+ WARN_PRINT("No UVs for this polygon, while there is no default and some other polygons have it. This FBX file may be corrupted.");
+ }
+ }
+ uv_raw = &r_uv_2_raw;
+ this_vert_poly_uv = &this_vert_poly_uv2;
+ }
+ }
+
+ // If we want to duplicate it, Let's see if we already duplicated this
+ // vertex.
+ if (need_duplication) {
+ if (duplicated_vertices.has(index)) {
+ Vertex similar_vertex = -1;
+ // Let's see if one of the new vertices has the same data of this.
+ const Vector<int> *new_vertices = duplicated_vertices.getptr(index);
+ for (int j = 0; j < new_vertices->size(); j += 1) {
+ const Vertex new_vertex = (*new_vertices)[j];
+ bool same_uv1 = false;
+ bool same_uv2 = false;
+ bool same_normal = false;
+ bool same_color = false;
+
+ if (r_uv_1.has(new_vertex)) {
+ if ((this_vert_poly_uv1 - (*r_uv_1.getptr(new_vertex))).length_squared() <= CMP_EPSILON) {
+ same_uv1 = true;
+ }
+ }
+
+ if (r_uv_2.has(new_vertex)) {
+ if ((this_vert_poly_uv2 - (*r_uv_2.getptr(new_vertex))).length_squared() <= CMP_EPSILON) {
+ same_uv2 = true;
+ }
+ }
+
+ if (r_color.has(new_vertex)) {
+ if (this_vert_poly_color.is_equal_approx((*r_color.getptr(new_vertex)))) {
+ same_color = true;
+ }
+ }
+
+ if (r_normals.has(new_vertex)) {
+ if ((this_vert_poly_normal - (*r_normals.getptr(new_vertex))).length_squared() <= CMP_EPSILON) {
+ same_uv2 = true;
+ }
+ }
+
+ if (same_uv1 && same_uv2 && same_normal && same_color) {
+ similar_vertex = new_vertex;
+ break;
+ }
+ }
+
+ if (similar_vertex != -1) {
+ // Update polygon.
+ if (is_end_of_polygon(r_polygon_indices, pv)) {
+ r_polygon_indices[pv] = ~similar_vertex;
+ } else {
+ r_polygon_indices[pv] = similar_vertex;
+ }
+ need_duplication = false;
+ }
+ }
+ }
+
+ if (need_duplication) {
+ const Vertex old_index = index;
+ const Vertex new_index = r_vertices.size();
+
+ // Polygon index.
+ if (is_end_of_polygon(r_polygon_indices, pv)) {
+ r_polygon_indices[pv] = ~new_index;
+ } else {
+ r_polygon_indices[pv] = new_index;
+ }
+
+ // Vertex position.
+ r_vertices.push_back(r_vertices[old_index]);
+
+ // Normals
+ if (r_normals_raw.has(old_index)) {
+ r_normals.set(new_index, this_vert_poly_normal);
+ r_normals_raw.getptr(old_index)->erase(polygon_index);
+ r_normals_raw[new_index][polygon_index] = this_vert_poly_normal;
+ }
+
+ // Vertex Color
+ if (r_colors_raw.has(old_index)) {
+ r_color.set(new_index, this_vert_poly_color);
+ r_colors_raw.getptr(old_index)->erase(polygon_index);
+ r_colors_raw[new_index][polygon_index] = this_vert_poly_color;
+ }
+
+ // UV 0
+ if (r_uv_1_raw.has(old_index)) {
+ r_uv_1.set(new_index, this_vert_poly_uv1);
+ r_uv_1_raw.getptr(old_index)->erase(polygon_index);
+ r_uv_1_raw[new_index][polygon_index] = this_vert_poly_uv1;
+ }
+
+ // UV 1
+ if (r_uv_2_raw.has(old_index)) {
+ r_uv_2.set(new_index, this_vert_poly_uv2);
+ r_uv_2_raw.getptr(old_index)->erase(polygon_index);
+ r_uv_2_raw[new_index][polygon_index] = this_vert_poly_uv2;
+ }
+
+ // Morphs
+ for (const String *mname = r_morphs.next(nullptr); mname != nullptr; mname = r_morphs.next(mname)) {
+ MorphVertexData *d = r_morphs.getptr(*mname);
+ // This can't never happen.
+ CRASH_COND(d == nullptr);
+ if (d->vertices.size() > old_index) {
+ d->vertices.push_back(d->vertices[old_index]);
+ }
+ if (d->normals.size() > old_index) {
+ d->normals.push_back(d->normals[old_index]);
+ }
+ }
+
+ if (vertex_weights.has(old_index)) {
+ vertex_weights.set(new_index, vertex_weights[old_index]);
+ }
+
+ duplicated_vertices[old_index].push_back(new_index);
+ } else {
+ if (r_normals_raw.has(index) &&
+ r_normals.has(index) == false) {
+ r_normals.set(index, this_vert_poly_normal);
+ }
+
+ if (r_colors_raw.has(index) && r_color.has(index) == false) {
+ r_color.set(index, this_vert_poly_color);
+ }
+
+ if (r_uv_1_raw.has(index) &&
+ r_uv_1.has(index) == false) {
+ r_uv_1.set(index, this_vert_poly_uv1);
+ }
+
+ if (r_uv_2_raw.has(index) &&
+ r_uv_2.has(index) == false) {
+ r_uv_2.set(index, this_vert_poly_uv2);
+ }
+ }
+ }
+}
+
+void FBXMeshData::add_vertex(
+ const ImportState &state,
+ Ref<SurfaceTool> p_surface_tool,
+ real_t p_scale,
+ Vertex p_vertex,
+ const std::vector<Vector3> &p_vertices_position,
+ const HashMap<int, Vector3> &p_normals,
+ const HashMap<int, Vector2> &p_uvs_0,
+ const HashMap<int, Vector2> &p_uvs_1,
+ const HashMap<int, Color> &p_colors,
+ const Vector3 &p_morph_value,
+ const Vector3 &p_morph_normal) {
+ ERR_FAIL_INDEX_MSG(p_vertex, (Vertex)p_vertices_position.size(), "FBX file is corrupted, the position of the vertex can't be retrieved.");
+
+ if (p_normals.has(p_vertex) && !state.is_blender_fbx) {
+ p_surface_tool->set_normal(p_normals[p_vertex] + p_morph_normal);
+ }
+
+ if (p_uvs_0.has(p_vertex)) {
+ //print_verbose("uv1: [" + itos(p_vertex) + "] " + p_uvs_0[p_vertex]);
+ // Inverts Y UV.
+ p_surface_tool->set_uv(Vector2(p_uvs_0[p_vertex].x, 1 - p_uvs_0[p_vertex].y));
+ }
+
+ if (p_uvs_1.has(p_vertex)) {
+ //print_verbose("uv2: [" + itos(p_vertex) + "] " + p_uvs_1[p_vertex]);
+ // Inverts Y UV.
+ p_surface_tool->set_uv2(Vector2(p_uvs_1[p_vertex].x, 1 - p_uvs_1[p_vertex].y));
+ }
+
+ if (p_colors.has(p_vertex)) {
+ p_surface_tool->set_color(p_colors[p_vertex]);
+ }
+
+ // TODO what about binormals?
+ // TODO there is other?
+
+ if (vertex_weights.has(p_vertex)) {
+ // Let's extract the weight info.
+ const VertexWeightMapping *vm = vertex_weights.getptr(p_vertex);
+ const Vector<int> &bones = vm->bones;
+
+ // the bug is that the bone idx is wrong because it is not ref'ing the skin.
+
+ if (bones.size() > RS::ARRAY_WEIGHTS_SIZE) {
+ print_error("[weight overflow detected]");
+ }
+
+ p_surface_tool->set_weights(vm->weights);
+ // 0 1 2 3 4 5 6 7 < local skeleton / skin for mesh
+ // 0 1 2 3 4 5 6 7 8 9 10 < actual skeleton with all joints
+ p_surface_tool->set_bones(bones);
+ }
+
+ // The surface tool want the vertex position as last thing.
+ p_surface_tool->add_vertex((p_vertices_position[p_vertex] + p_morph_value) * p_scale);
+}
+
+void FBXMeshData::triangulate_polygon(Ref<SurfaceTool> st, Vector<int> p_polygon_vertex, const Vector<Vertex> p_surface_vertex_map, const std::vector<Vector3> &p_vertices) const {
+ const int polygon_vertex_count = p_polygon_vertex.size();
+ if (polygon_vertex_count == 1) {
+ // point to triangle
+ st->add_index(p_polygon_vertex[0]);
+ st->add_index(p_polygon_vertex[0]);
+ st->add_index(p_polygon_vertex[0]);
+ return;
+ } else if (polygon_vertex_count == 2) {
+ // line to triangle
+ st->add_index(p_polygon_vertex[1]);
+ st->add_index(p_polygon_vertex[1]);
+ st->add_index(p_polygon_vertex[0]);
+ return;
+ } else if (polygon_vertex_count == 3) {
+ // triangle to triangle
+ st->add_index(p_polygon_vertex[0]);
+ st->add_index(p_polygon_vertex[2]);
+ st->add_index(p_polygon_vertex[1]);
+ return;
+ } else if (polygon_vertex_count == 4) {
+ // quad to triangle - this code is awesome for import times
+ // it prevents triangles being generated slowly
+ st->add_index(p_polygon_vertex[0]);
+ st->add_index(p_polygon_vertex[2]);
+ st->add_index(p_polygon_vertex[1]);
+ st->add_index(p_polygon_vertex[2]);
+ st->add_index(p_polygon_vertex[0]);
+ st->add_index(p_polygon_vertex[3]);
+ return;
+ } else {
+ // non triangulated - we must run the triangulation algorithm
+ bool is_simple_convex = false;
+ // this code is 'slow' but required it triangulates all the unsupported geometry.
+ // Doesn't allow for bigger polygons because those are unlikely be convex
+ if (polygon_vertex_count <= 6) {
+ // Start from true, check if it's false.
+ is_simple_convex = true;
+ Vector3 first_vec;
+ for (int i = 0; i < polygon_vertex_count; i += 1) {
+ const Vector3 p1 = p_vertices[p_surface_vertex_map[p_polygon_vertex[i]]];
+ const Vector3 p2 = p_vertices[p_surface_vertex_map[p_polygon_vertex[(i + 1) % polygon_vertex_count]]];
+ const Vector3 p3 = p_vertices[p_surface_vertex_map[p_polygon_vertex[(i + 2) % polygon_vertex_count]]];
+
+ const Vector3 edge1 = p1 - p2;
+ const Vector3 edge2 = p3 - p2;
+
+ const Vector3 res = edge1.normalized().cross(edge2.normalized()).normalized();
+ if (i == 0) {
+ first_vec = res;
+ } else {
+ if (first_vec.dot(res) < 0.0) {
+ // Ok we found an angle that is not the same dir of the
+ // others.
+ is_simple_convex = false;
+ break;
+ }
+ }
+ }
+ }
+
+ if (is_simple_convex) {
+ // This is a convex polygon, so just triangulate it.
+ for (int i = 0; i < (polygon_vertex_count - 2); i += 1) {
+ st->add_index(p_polygon_vertex[2 + i]);
+ st->add_index(p_polygon_vertex[1 + i]);
+ st->add_index(p_polygon_vertex[0]);
+ }
+ return;
+ }
+ }
+
+ {
+ // This is a concave polygon.
+
+ std::vector<Vector3> poly_vertices(polygon_vertex_count);
+ for (int i = 0; i < polygon_vertex_count; i += 1) {
+ poly_vertices[i] = p_vertices[p_surface_vertex_map[p_polygon_vertex[i]]];
+ }
+
+ const Vector3 poly_norm = get_poly_normal(poly_vertices);
+ if (poly_norm.length_squared() <= CMP_EPSILON) {
+ ERR_FAIL_COND_MSG(poly_norm.length_squared() <= CMP_EPSILON, "The normal of this poly was not computed. Is this FBX file corrupted.");
+ }
+
+ // Select the plan coordinate.
+ int axis_1_coord = 0;
+ int axis_2_coord = 1;
+ {
+ real_t inv = poly_norm.z;
+
+ const real_t axis_x = ABS(poly_norm.x);
+ const real_t axis_y = ABS(poly_norm.y);
+ const real_t axis_z = ABS(poly_norm.z);
+
+ if (axis_x > axis_y) {
+ if (axis_x > axis_z) {
+ // For the most part the normal point toward X.
+ axis_1_coord = 1;
+ axis_2_coord = 2;
+ inv = poly_norm.x;
+ }
+ } else if (axis_y > axis_z) {
+ // For the most part the normal point toward Y.
+ axis_1_coord = 2;
+ axis_2_coord = 0;
+ inv = poly_norm.y;
+ }
+
+ // Swap projection axes to take the negated projection vector into account
+ if (inv < 0.0f) {
+ SWAP(axis_1_coord, axis_2_coord);
+ }
+ }
+
+ TPPLPoly tppl_poly;
+ tppl_poly.Init(polygon_vertex_count);
+ std::vector<Vector2> projected_vertices(polygon_vertex_count);
+ for (int i = 0; i < polygon_vertex_count; i += 1) {
+ const Vector2 pv(poly_vertices[i][axis_1_coord], poly_vertices[i][axis_2_coord]);
+ projected_vertices[i] = pv;
+ tppl_poly.GetPoint(i) = pv;
+ }
+ tppl_poly.SetOrientation(TPPL_ORIENTATION_CCW);
+
+ List<TPPLPoly> out_poly;
+
+ TPPLPartition tppl_partition;
+ if (tppl_partition.Triangulate_OPT(&tppl_poly, &out_poly) == 0) { // Good result.
+ if (tppl_partition.Triangulate_EC(&tppl_poly, &out_poly) == 0) { // Medium result.
+ if (tppl_partition.Triangulate_MONO(&tppl_poly, &out_poly) == 0) { // Really poor result.
+ ERR_FAIL_MSG("The triangulation of this polygon failed, please try to triangulate your mesh or check if it has broken polygons.");
+ }
+ }
+ }
+
+ std::vector<Vector2> tris(out_poly.size());
+ for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) {
+ TPPLPoly &tp = I->get();
+
+ ERR_FAIL_COND_MSG(tp.GetNumPoints() != 3, "The triangulator retuned more points, how this is possible?");
+ // Find Index
+ for (int i = 2; i >= 0; i -= 1) {
+ const Vector2 vertex = tp.GetPoint(i);
+ bool done = false;
+ // Find Index
+ for (int y = 0; y < polygon_vertex_count; y += 1) {
+ if ((projected_vertices[y] - vertex).length_squared() <= CMP_EPSILON) {
+ // This seems the right vertex
+ st->add_index(p_polygon_vertex[y]);
+ done = true;
+ break;
+ }
+ }
+ ERR_FAIL_COND(done == false);
+ }
+ }
+ }
+}
+
+void FBXMeshData::gen_weight_info(Ref<SurfaceTool> st, Vertex vertex_id) const {
+ if (vertex_weights.is_empty()) {
+ return;
+ }
+
+ if (vertex_weights.has(vertex_id)) {
+ // Let's extract the weight info.
+ const VertexWeightMapping *vm = vertex_weights.getptr(vertex_id);
+ st->set_weights(vm->weights);
+ st->set_bones(vm->bones);
+ }
+}
+
+int FBXMeshData::get_vertex_from_polygon_vertex(const std::vector<int> &p_polygon_indices, int p_index) const {
+ if (p_index < 0 || p_index >= (int)p_polygon_indices.size()) {
+ return -1;
+ }
+
+ const int vertex = p_polygon_indices[p_index];
+ if (vertex >= 0) {
+ return vertex;
+ } else {
+ // Negative numbers are the end of the face, reversing the bits is
+ // possible to obtain the positive correct vertex number.
+ return ~vertex;
+ }
+}
+
+bool FBXMeshData::is_end_of_polygon(const std::vector<int> &p_polygon_indices, int p_index) const {
+ if (p_index < 0 || p_index >= (int)p_polygon_indices.size()) {
+ return false;
+ }
+
+ const int vertex = p_polygon_indices[p_index];
+
+ // If the index is negative this is the end of the Polygon.
+ return vertex < 0;
+}
+
+bool FBXMeshData::is_start_of_polygon(const std::vector<int> &p_polygon_indices, int p_index) const {
+ if (p_index < 0 || p_index >= (int)p_polygon_indices.size()) {
+ return false;
+ }
+
+ if (p_index == 0) {
+ return true;
+ }
+
+ // If the previous indices is negative this is the begin of a new Polygon.
+ return p_polygon_indices[p_index - 1] < 0;
+}
+
+int FBXMeshData::count_polygons(const std::vector<int> &p_polygon_indices) const {
+ // The negative numbers define the end of the polygon. Counting the amount of
+ // negatives the numbers of polygons are obtained.
+ int count = 0;
+ for (size_t i = 0; i < p_polygon_indices.size(); i += 1) {
+ if (p_polygon_indices[i] < 0) {
+ count += 1;
+ }
+ }
+ return count;
+}
+
+template <class R, class T>
+HashMap<int, R> FBXMeshData::extract_per_vertex_data(
+ int p_vertex_count,
+ const std::vector<FBXDocParser::MeshGeometry::Edge> &p_edge_map,
+ const std::vector<int> &p_mesh_indices,
+ const FBXDocParser::MeshGeometry::MappingData<T> &p_mapping_data,
+ R (*collector_function)(const Vector<VertexData<T>> *p_vertex_data, R p_fall_back),
+ R p_fall_back) const {
+ /* When index_to_direct is set
+ * index size is 184 ( contains index for the data array [values 0, 96] )
+ * data size is 96 (contains uv coordinates)
+ * this means index is simple data reduction basically
+ */
+ ////
+ if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct && p_mapping_data.index.size() == 0) {
+ print_verbose("debug count: index size: " + itos(p_mapping_data.index.size()) + ", data size: " + itos(p_mapping_data.data.size()));
+ print_verbose("vertex indices count: " + itos(p_mesh_indices.size()));
+ print_verbose("Edge map size: " + itos(p_edge_map.size()));
+ }
+
+ ERR_FAIL_COND_V_MSG(p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct && p_mapping_data.index.size() == 0, (HashMap<int, R>()), "FBX importer needs to map correctly to this field, please specify the override index name to fix this problem!");
+ ERR_FAIL_COND_V_MSG(p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index && p_mapping_data.index.size() == 0, (HashMap<int, R>()), "The FBX seems corrupted");
+
+ // Aggregate vertex data.
+ HashMap<Vertex, Vector<VertexData<T>>> aggregate_vertex_data;
+
+ switch (p_mapping_data.map_type) {
+ case FBXDocParser::MeshGeometry::MapType::none: {
+ // No data nothing to do.
+ return (HashMap<int, R>());
+ }
+ case FBXDocParser::MeshGeometry::MapType::vertex: {
+ ERR_FAIL_COND_V_MSG(p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct, (HashMap<int, R>()), "We will support in future");
+
+ if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::direct) {
+ // The data is mapped per vertex directly.
+ ERR_FAIL_COND_V_MSG((int)p_mapping_data.data.size() != p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR01");
+ for (size_t vertex_index = 0; vertex_index < p_mapping_data.data.size(); vertex_index += 1) {
+ aggregate_vertex_data[vertex_index].push_back({ -1, p_mapping_data.data[vertex_index] });
+ }
+ } else {
+ // The data is mapped per vertex using a reference.
+ // The indices array, contains a *reference_id for each vertex.
+ // * Note that the reference_id is the id of data into the data array.
+ //
+ // https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_layer_element_html
+ ERR_FAIL_COND_V_MSG((int)p_mapping_data.index.size() != p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR02");
+ for (size_t vertex_index = 0; vertex_index < p_mapping_data.index.size(); vertex_index += 1) {
+ ERR_FAIL_INDEX_V_MSG(p_mapping_data.index[vertex_index], (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR03.");
+ aggregate_vertex_data[vertex_index].push_back({ -1, p_mapping_data.data[p_mapping_data.index[vertex_index]] });
+ }
+ }
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::polygon_vertex: {
+ if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct) {
+ // The data is mapped using each index from the indexes array then direct to the data (data reduction algorithm)
+ ERR_FAIL_COND_V_MSG((int)p_mesh_indices.size() != (int)p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR04");
+ int polygon_id = -1;
+ for (size_t polygon_vertex_index = 0; polygon_vertex_index < p_mapping_data.index.size(); polygon_vertex_index += 1) {
+ if (is_start_of_polygon(p_mesh_indices, polygon_vertex_index)) {
+ polygon_id += 1;
+ }
+ const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index);
+ ERR_FAIL_COND_V_MSG(vertex_index < 0, (HashMap<int, R>()), "FBX file corrupted: #ERR05");
+ ERR_FAIL_COND_V_MSG(vertex_index >= p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR06");
+ const int index_to_direct = p_mapping_data.index[polygon_vertex_index];
+ T value = p_mapping_data.data[index_to_direct];
+ aggregate_vertex_data[vertex_index].push_back({ polygon_id, value });
+ }
+ } else if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::direct) {
+ // The data are mapped per polygon vertex directly.
+ ERR_FAIL_COND_V_MSG((int)p_mesh_indices.size() != (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR04");
+ int polygon_id = -1;
+ for (size_t polygon_vertex_index = 0; polygon_vertex_index < p_mapping_data.data.size(); polygon_vertex_index += 1) {
+ if (is_start_of_polygon(p_mesh_indices, polygon_vertex_index)) {
+ polygon_id += 1;
+ }
+ const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index);
+ ERR_FAIL_COND_V_MSG(vertex_index < 0, (HashMap<int, R>()), "FBX file corrupted: #ERR05");
+ ERR_FAIL_COND_V_MSG(vertex_index >= p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR06");
+
+ aggregate_vertex_data[vertex_index].push_back({ polygon_id, p_mapping_data.data[polygon_vertex_index] });
+ }
+ } else {
+ // The data is mapped per polygon_vertex using a reference.
+ // The indices array, contains a *reference_id for each polygon_vertex.
+ // * Note that the reference_id is the id of data into the data array.
+ //
+ // https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_layer_element_html
+ ERR_FAIL_COND_V_MSG(p_mesh_indices.size() != p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR7");
+ int polygon_id = -1;
+ for (size_t polygon_vertex_index = 0; polygon_vertex_index < p_mapping_data.index.size(); polygon_vertex_index += 1) {
+ if (is_start_of_polygon(p_mesh_indices, polygon_vertex_index)) {
+ polygon_id += 1;
+ }
+ const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index);
+ ERR_FAIL_COND_V_MSG(vertex_index < 0, (HashMap<int, R>()), "FBX file corrupted: #ERR8");
+ ERR_FAIL_COND_V_MSG(vertex_index >= p_vertex_count, (HashMap<int, R>()), "FBX file seems corrupted: #ERR9.");
+ ERR_FAIL_COND_V_MSG(p_mapping_data.index[polygon_vertex_index] < 0, (HashMap<int, R>()), "FBX file seems corrupted: #ERR10.");
+ ERR_FAIL_COND_V_MSG(p_mapping_data.index[polygon_vertex_index] >= (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR11.");
+ aggregate_vertex_data[vertex_index].push_back({ polygon_id, p_mapping_data.data[p_mapping_data.index[polygon_vertex_index]] });
+ }
+ }
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::polygon: {
+ if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::direct) {
+ // The data are mapped per polygon directly.
+ const int polygon_count = count_polygons(p_mesh_indices);
+ ERR_FAIL_COND_V_MSG(polygon_count != (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR12");
+
+ // Advance each polygon vertex, each new polygon advance the polygon index.
+ int polygon_index = -1;
+ for (size_t polygon_vertex_index = 0;
+ polygon_vertex_index < p_mesh_indices.size();
+ polygon_vertex_index += 1) {
+ if (is_start_of_polygon(p_mesh_indices, polygon_vertex_index)) {
+ polygon_index += 1;
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR13");
+ }
+
+ const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index);
+ ERR_FAIL_INDEX_V_MSG(vertex_index, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR14");
+
+ aggregate_vertex_data[vertex_index].push_back({ polygon_index, p_mapping_data.data[polygon_index] });
+ }
+ ERR_FAIL_COND_V_MSG((polygon_index + 1) != polygon_count, (HashMap<int, R>()), "FBX file seems corrupted: #ERR16. Not all Polygons are present in the file.");
+ } else {
+ // The data is mapped per polygon using a reference.
+ // The indices array, contains a *reference_id for each polygon.
+ // * Note that the reference_id is the id of data into the data array.
+ //
+ // https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_layer_element_html
+ const int polygon_count = count_polygons(p_mesh_indices);
+ ERR_FAIL_COND_V_MSG(polygon_count != (int)p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR17");
+
+ // Advance each polygon vertex, each new polygon advance the polygon index.
+ int polygon_index = -1;
+ for (size_t polygon_vertex_index = 0;
+ polygon_vertex_index < p_mesh_indices.size();
+ polygon_vertex_index += 1) {
+ if (is_start_of_polygon(p_mesh_indices, polygon_vertex_index)) {
+ polygon_index += 1;
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR18");
+ ERR_FAIL_INDEX_V_MSG(p_mapping_data.index[polygon_index], (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR19");
+ }
+
+ const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index);
+ ERR_FAIL_INDEX_V_MSG(vertex_index, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR20");
+
+ aggregate_vertex_data[vertex_index].push_back({ polygon_index, p_mapping_data.data[p_mapping_data.index[polygon_index]] });
+ }
+ ERR_FAIL_COND_V_MSG((polygon_index + 1) != polygon_count, (HashMap<int, R>()), "FBX file seems corrupted: #ERR22. Not all Polygons are present in the file.");
+ }
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::edge: {
+ if (p_mapping_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::direct) {
+ // The data are mapped per edge directly.
+ ERR_FAIL_COND_V_MSG(p_edge_map.size() != p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR23");
+ for (size_t edge_index = 0; edge_index < p_mapping_data.data.size(); edge_index += 1) {
+ const FBXDocParser::MeshGeometry::Edge edge = FBXDocParser::MeshGeometry::get_edge(p_edge_map, edge_index);
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_0, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR24");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_1, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR25");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_0, (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR26");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_1, (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR27");
+ aggregate_vertex_data[edge.vertex_0].push_back({ -1, p_mapping_data.data[edge_index] });
+ aggregate_vertex_data[edge.vertex_1].push_back({ -1, p_mapping_data.data[edge_index] });
+ }
+ } else {
+ // The data is mapped per edge using a reference.
+ // The indices array, contains a *reference_id for each polygon.
+ // * Note that the reference_id is the id of data into the data array.
+ //
+ // https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_layer_element_html
+ ERR_FAIL_COND_V_MSG(p_edge_map.size() != p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR28");
+ for (size_t edge_index = 0; edge_index < p_mapping_data.data.size(); edge_index += 1) {
+ const FBXDocParser::MeshGeometry::Edge edge = FBXDocParser::MeshGeometry::get_edge(p_edge_map, edge_index);
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_0, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR29");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_1, p_vertex_count, (HashMap<int, R>()), "FBX file corrupted: #ERR30");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_0, (int)p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR31");
+ ERR_FAIL_INDEX_V_MSG(edge.vertex_1, (int)p_mapping_data.index.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR32");
+ ERR_FAIL_INDEX_V_MSG(p_mapping_data.index[edge.vertex_0], (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR33");
+ ERR_FAIL_INDEX_V_MSG(p_mapping_data.index[edge.vertex_1], (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file corrupted: #ERR34");
+ aggregate_vertex_data[edge.vertex_0].push_back({ -1, p_mapping_data.data[p_mapping_data.index[edge_index]] });
+ aggregate_vertex_data[edge.vertex_1].push_back({ -1, p_mapping_data.data[p_mapping_data.index[edge_index]] });
+ }
+ }
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::all_the_same: {
+ // No matter the mode, no matter the data size; The first always win
+ // and is set to all the vertices.
+ ERR_FAIL_COND_V_MSG(p_mapping_data.data.size() <= 0, (HashMap<int, R>()), "FBX file seems corrupted: #ERR35");
+ if (p_mapping_data.data.size() > 0) {
+ for (int vertex_index = 0; vertex_index < p_vertex_count; vertex_index += 1) {
+ aggregate_vertex_data[vertex_index].push_back({ -1, p_mapping_data.data[0] });
+ }
+ }
+ } break;
+ }
+
+ if (aggregate_vertex_data.size() == 0) {
+ return (HashMap<int, R>());
+ }
+
+ // A map is used because turns out that the some FBX file are not well organized
+ // with vertices well compacted. Using a map allows avoid those issues.
+ HashMap<Vertex, R> result;
+
+ // Aggregate the collected data.
+ for (const Vertex *index = aggregate_vertex_data.next(nullptr); index != nullptr; index = aggregate_vertex_data.next(index)) {
+ Vector<VertexData<T>> *aggregated_vertex = aggregate_vertex_data.getptr(*index);
+ // This can't be null because we are just iterating.
+ CRASH_COND(aggregated_vertex == nullptr);
+
+ ERR_FAIL_INDEX_V_MSG(0, aggregated_vertex->size(), (HashMap<int, R>()), "The FBX file is corrupted, No valid data for this vertex index.");
+ result[*index] = collector_function(aggregated_vertex, p_fall_back);
+ }
+
+ // Sanitize the data now, if the file is broken we can try import it anyway.
+ bool problem_found = false;
+ for (size_t i = 0; i < p_mesh_indices.size(); i += 1) {
+ const Vertex vertex = get_vertex_from_polygon_vertex(p_mesh_indices, i);
+ if (result.has(vertex) == false) {
+ result[vertex] = p_fall_back;
+ problem_found = true;
+ }
+ }
+ if (problem_found) {
+ WARN_PRINT("Some data is missing, this FBX file may be corrupted: #WARN0.");
+ }
+
+ return result;
+}
+
+template <class T>
+HashMap<int, T> FBXMeshData::extract_per_polygon(
+ int p_vertex_count,
+ const std::vector<int> &p_polygon_indices,
+ const FBXDocParser::MeshGeometry::MappingData<T> &p_fbx_data,
+ T p_fallback_value) const {
+ ERR_FAIL_COND_V_MSG(p_fbx_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct && p_fbx_data.data.size() == 0, (HashMap<int, T>()), "invalid index to direct array");
+ ERR_FAIL_COND_V_MSG(p_fbx_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index && p_fbx_data.index.size() == 0, (HashMap<int, T>()), "The FBX seems corrupted");
+
+ const int polygon_count = count_polygons(p_polygon_indices);
+
+ // Aggregate vertex data.
+ HashMap<int, Vector<T>> aggregate_polygon_data;
+
+ switch (p_fbx_data.map_type) {
+ case FBXDocParser::MeshGeometry::MapType::none: {
+ // No data nothing to do.
+ return (HashMap<int, T>());
+ }
+ case FBXDocParser::MeshGeometry::MapType::vertex: {
+ ERR_FAIL_V_MSG((HashMap<int, T>()), "This data can't be extracted and organized per polygon, since into the FBX is mapped per vertex. This should not happen.");
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::polygon_vertex: {
+ ERR_FAIL_V_MSG((HashMap<int, T>()), "This data can't be extracted and organized per polygon, since into the FBX is mapped per polygon vertex. This should not happen.");
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::polygon: {
+ if (p_fbx_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::index_to_direct) {
+ // The data is stored efficiently index_to_direct allows less data in the FBX file.
+ for (int polygon_index = 0;
+ polygon_index < polygon_count;
+ polygon_index += 1) {
+ if (p_fbx_data.index.size() == 0) {
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_fbx_data.data.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR62");
+ aggregate_polygon_data[polygon_index].push_back(p_fbx_data.data[polygon_index]);
+ } else {
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_fbx_data.index.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR62");
+
+ const int index_to_direct = p_fbx_data.index[polygon_index];
+ T value = p_fbx_data.data[index_to_direct];
+ aggregate_polygon_data[polygon_index].push_back(value);
+ }
+ }
+ } else if (p_fbx_data.ref_type == FBXDocParser::MeshGeometry::ReferenceType::direct) {
+ // The data are mapped per polygon directly.
+ ERR_FAIL_COND_V_MSG(polygon_count != (int)p_fbx_data.data.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR51");
+
+ // Advance each polygon vertex, each new polygon advance the polygon index.
+ for (int polygon_index = 0;
+ polygon_index < polygon_count;
+ polygon_index += 1) {
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_fbx_data.data.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR52");
+ aggregate_polygon_data[polygon_index].push_back(p_fbx_data.data[polygon_index]);
+ }
+ } else {
+ // The data is mapped per polygon using a reference.
+ // The indices array, contains a *reference_id for each polygon.
+ // * Note that the reference_id is the id of data into the data array.
+ //
+ // https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_layer_element_html
+ ERR_FAIL_COND_V_MSG(polygon_count != (int)p_fbx_data.index.size(), (HashMap<int, T>()), "FBX file seems corrupted: #ERR52");
+
+ // Advance each polygon vertex, each new polygon advance the polygon index.
+ for (int polygon_index = 0;
+ polygon_index < polygon_count;
+ polygon_index += 1) {
+ ERR_FAIL_INDEX_V_MSG(polygon_index, (int)p_fbx_data.index.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR53");
+ ERR_FAIL_INDEX_V_MSG(p_fbx_data.index[polygon_index], (int)p_fbx_data.data.size(), (HashMap<int, T>()), "FBX file is corrupted: #ERR54");
+ aggregate_polygon_data[polygon_index].push_back(p_fbx_data.data[p_fbx_data.index[polygon_index]]);
+ }
+ }
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::edge: {
+ ERR_FAIL_V_MSG((HashMap<int, T>()), "This data can't be extracted and organized per polygon, since into the FBX is mapped per edge. This should not happen.");
+ } break;
+ case FBXDocParser::MeshGeometry::MapType::all_the_same: {
+ // No matter the mode, no matter the data size; The first always win
+ // and is set to all the vertices.
+ ERR_FAIL_COND_V_MSG(p_fbx_data.data.size() <= 0, (HashMap<int, T>()), "FBX file seems corrupted: #ERR55");
+ if (p_fbx_data.data.size() > 0) {
+ for (int polygon_index = 0; polygon_index < polygon_count; polygon_index += 1) {
+ aggregate_polygon_data[polygon_index].push_back(p_fbx_data.data[0]);
+ }
+ }
+ } break;
+ }
+
+ if (aggregate_polygon_data.size() == 0) {
+ return (HashMap<int, T>());
+ }
+
+ // A map is used because turns out that the some FBX file are not well organized
+ // with vertices well compacted. Using a map allows avoid those issues.
+ HashMap<int, T> polygons;
+
+ // Take the first value for each vertex.
+ for (const Vertex *index = aggregate_polygon_data.next(nullptr); index != nullptr; index = aggregate_polygon_data.next(index)) {
+ Vector<T> *aggregated_polygon = aggregate_polygon_data.getptr(*index);
+ // This can't be null because we are just iterating.
+ CRASH_COND(aggregated_polygon == nullptr);
+
+ ERR_FAIL_INDEX_V_MSG(0, (int)aggregated_polygon->size(), (HashMap<int, T>()), "The FBX file is corrupted, No valid data for this polygon index.");
+
+ // Validate the final value.
+ polygons[*index] = (*aggregated_polygon)[0];
+ }
+
+ // Sanitize the data now, if the file is broken we can try import it anyway.
+ bool problem_found = false;
+ for (int polygon_i = 0; polygon_i < polygon_count; polygon_i += 1) {
+ if (polygons.has(polygon_i) == false) {
+ polygons[polygon_i] = p_fallback_value;
+ problem_found = true;
+ }
+ }
+ if (problem_found) {
+ WARN_PRINT("Some data is missing, this FBX file may be corrupted: #WARN1.");
+ }
+
+ return polygons;
+}
+
+void FBXMeshData::extract_morphs(const FBXDocParser::MeshGeometry *mesh_geometry, HashMap<String, MorphVertexData> &r_data) {
+ r_data.clear();
+
+ const int vertex_count = mesh_geometry->get_vertices().size();
+
+ for (const FBXDocParser::BlendShape *blend_shape : mesh_geometry->get_blend_shapes()) {
+ for (const FBXDocParser::BlendShapeChannel *blend_shape_channel : blend_shape->BlendShapeChannels()) {
+ const std::vector<const FBXDocParser::ShapeGeometry *> &shape_geometries = blend_shape_channel->GetShapeGeometries();
+ for (const FBXDocParser::ShapeGeometry *shape_geometry : shape_geometries) {
+ String morph_name = ImportUtils::FBXAnimMeshName(shape_geometry->Name()).c_str();
+ if (morph_name.is_empty()) {
+ morph_name = "morph";
+ }
+
+ // TODO we have only these??
+ const std::vector<unsigned int> &morphs_vertex_indices = shape_geometry->GetIndices();
+ const std::vector<Vector3> &morphs_vertices = shape_geometry->GetVertices();
+ const std::vector<Vector3> &morphs_normals = shape_geometry->GetNormals();
+
+ ERR_FAIL_COND_MSG((int)morphs_vertex_indices.size() > vertex_count, "The FBX file is corrupted: #ERR103");
+ ERR_FAIL_COND_MSG(morphs_vertex_indices.size() != morphs_vertices.size(), "The FBX file is corrupted: #ERR104");
+ ERR_FAIL_COND_MSG((int)morphs_vertices.size() > vertex_count, "The FBX file is corrupted: #ERR105");
+ ERR_FAIL_COND_MSG(morphs_normals.size() != 0 && morphs_normals.size() != morphs_vertices.size(), "The FBX file is corrupted: #ERR106");
+
+ if (r_data.has(morph_name) == false) {
+ // This morph doesn't exist yet.
+ // Create it.
+ MorphVertexData md;
+ md.vertices.resize(vertex_count);
+ md.normals.resize(vertex_count);
+ r_data.set(morph_name, md);
+ }
+
+ MorphVertexData *data = r_data.getptr(morph_name);
+ Vector3 *data_vertices_ptr = data->vertices.ptrw();
+ Vector3 *data_normals_ptr = data->normals.ptrw();
+
+ for (int i = 0; i < (int)morphs_vertex_indices.size(); i += 1) {
+ const Vertex vertex = morphs_vertex_indices[i];
+
+ ERR_FAIL_INDEX_MSG(vertex, vertex_count, "The blend shapes of this FBX file are corrupted. It has a not valid vertex.");
+
+ data_vertices_ptr[vertex] = morphs_vertices[i];
+
+ if (morphs_normals.size() != 0) {
+ data_normals_ptr[vertex] = morphs_normals[i];
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/modules/fbx/data/fbx_mesh_data.h b/modules/fbx/data/fbx_mesh_data.h
new file mode 100644
index 0000000000..77510ff2ec
--- /dev/null
+++ b/modules/fbx/data/fbx_mesh_data.h
@@ -0,0 +1,184 @@
+/*************************************************************************/
+/* fbx_mesh_data.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_MESH_DATA_H
+#define FBX_MESH_DATA_H
+
+#include "core/templates/hash_map.h"
+#include "editor/import/resource_importer_scene.h"
+#include "editor/import/scene_importer_mesh_node_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/resources/surface_tool.h"
+
+#include "fbx_bone.h"
+#include "fbx_parser/FBXMeshGeometry.h"
+#include "import_state.h"
+#include "tools/import_utils.h"
+
+struct FBXNode;
+struct FBXMeshData;
+struct FBXBone;
+struct ImportState;
+
+struct VertexWeightMapping {
+ Vector<real_t> weights;
+ Vector<int> bones;
+ // This extra vector is used because the bone id is computed in a second step.
+ // TODO Get rid of this extra step is a good idea.
+ Vector<Ref<FBXBone>> bones_ref;
+};
+
+template <class T>
+struct VertexData {
+ int polygon_index;
+ T data;
+};
+
+// Caches mesh information and instantiates meshes for you using helper functions.
+struct FBXMeshData : Reference {
+ struct MorphVertexData {
+ // TODO we have only these??
+ /// Each element is a vertex. Not supposed to be void.
+ Vector<Vector3> vertices;
+ /// Each element is a vertex. Not supposed to be void.
+ Vector<Vector3> normals;
+ };
+
+ // FIXME: remove this is a hack for testing only
+ mutable const FBXDocParser::MeshGeometry *mesh_geometry = nullptr;
+
+ Ref<FBXNode> mesh_node = nullptr;
+ /// vertex id, Weight Info
+ /// later: perf we can use array here
+ HashMap<int, VertexWeightMapping> vertex_weights;
+
+ // translate fbx mesh data from document context to FBX Mesh Geometry Context
+ bool valid_weight_indexes = false;
+
+ EditorSceneImporterMeshNode3D *create_fbx_mesh(const ImportState &state, const FBXDocParser::MeshGeometry *p_mesh_geometry, const FBXDocParser::Model *model, bool use_compression);
+
+ void gen_weight_info(Ref<SurfaceTool> st, int vertex_id) const;
+
+ /* mesh maximum weight count */
+ bool valid_weight_count = false;
+ int max_weight_count = 0;
+ uint64_t armature_id = 0;
+ bool valid_armature_id = false;
+ EditorSceneImporterMeshNode3D *godot_mesh_instance = nullptr;
+
+private:
+ void sanitize_vertex_weights(const ImportState &state);
+
+ /// Make sure to reorganize the vertices so that the correct UV is taken.
+ /// This step is needed because differently from the normal, that can be
+ /// combined, the UV may need its own triangle because sometimes they have
+ /// really different UV for the same vertex but different polygon.
+ /// This function make sure to add another vertex for those UVS.
+ void reorganize_vertices(
+ std::vector<int> &r_polygon_indices,
+ std::vector<Vector3> &r_vertices,
+ HashMap<int, Vector3> &r_normals,
+ HashMap<int, Vector2> &r_uv_1,
+ HashMap<int, Vector2> &r_uv_2,
+ HashMap<int, Color> &r_color,
+ HashMap<String, MorphVertexData> &r_morphs,
+ HashMap<int, HashMap<int, Vector3>> &r_normals_raw,
+ HashMap<int, HashMap<int, Color>> &r_colors_raw,
+ HashMap<int, HashMap<int, Vector2>> &r_uv_1_raw,
+ HashMap<int, HashMap<int, Vector2>> &r_uv_2_raw);
+
+ void add_vertex(
+ const ImportState &state,
+ Ref<SurfaceTool> p_surface_tool,
+ real_t p_scale,
+ int p_vertex,
+ const std::vector<Vector3> &p_vertices_position,
+ const HashMap<int, Vector3> &p_normals,
+ const HashMap<int, Vector2> &p_uvs_0,
+ const HashMap<int, Vector2> &p_uvs_1,
+ const HashMap<int, Color> &p_colors,
+ const Vector3 &p_morph_value = Vector3(),
+ const Vector3 &p_morph_normal = Vector3());
+
+ void triangulate_polygon(Ref<SurfaceTool> st, Vector<int> p_polygon_vertex, Vector<int> p_surface_vertex_map, const std::vector<Vector3> &p_vertices) const;
+
+ /// This function is responsible to convert the FBX polygon vertex to
+ /// vertex index.
+ /// The polygon vertices are stored in an array with some negative
+ /// values. The negative values define the last face index.
+ /// For example the following `face_array` contains two faces, the former
+ /// with 3 vertices and the latter with a line:
+ /// [0,2,-2,3,-5]
+ /// Parsed as:
+ /// [0, 2, 1, 3, 4]
+ /// The negative values are computed using this formula: `(-value) - 1`
+ ///
+ /// Returns the vertex index from the poligon vertex.
+ /// Returns -1 if `p_index` is invalid.
+ int get_vertex_from_polygon_vertex(const std::vector<int> &p_face_indices, int p_index) const;
+
+ /// Returns true if this polygon_vertex_index is the end of a new polygon.
+ bool is_end_of_polygon(const std::vector<int> &p_face_indices, int p_index) const;
+
+ /// Returns true if this polygon_vertex_index is the begin of a new polygon.
+ bool is_start_of_polygon(const std::vector<int> &p_face_indices, int p_index) const;
+
+ /// Returns the number of polygons.
+ int count_polygons(const std::vector<int> &p_face_indices) const;
+
+ /// Used to extract data from the `MappingData` aligned with vertex.
+ /// Useful to extract normal/uvs/colors/tangents/etc...
+ /// If the function fails somehow, it returns an hollow vector and print an error.
+ template <class R, class T>
+ HashMap<int, R> extract_per_vertex_data(
+ int p_vertex_count,
+ const std::vector<FBXDocParser::MeshGeometry::Edge> &p_edges,
+ const std::vector<int> &p_mesh_indices,
+ const FBXDocParser::MeshGeometry::MappingData<T> &p_mapping_data,
+ R (*collector_function)(const Vector<VertexData<T>> *p_vertex_data, R p_fall_back),
+ R p_fall_back) const;
+
+ /// Used to extract data from the `MappingData` organized per polygon.
+ /// Useful to extract the material
+ /// If the function fails somehow, it returns an hollow vector and print an error.
+ template <class T>
+ HashMap<int, T> extract_per_polygon(
+ int p_vertex_count,
+ const std::vector<int> &p_face_indices,
+ const FBXDocParser::MeshGeometry::MappingData<T> &p_fbx_data,
+ T p_fallback_value) const;
+
+ /// Extracts the morph data and organizes it per vertices.
+ /// The returned `MorphVertexData` arrays are never something different
+ /// then the `vertex_count`.
+ void extract_morphs(const FBXDocParser::MeshGeometry *mesh_geometry, HashMap<String, MorphVertexData> &r_data);
+};
+
+#endif // FBX_MESH_DATA_H
diff --git a/modules/fbx/data/fbx_node.h b/modules/fbx/data/fbx_node.h
new file mode 100644
index 0000000000..a6f62f3388
--- /dev/null
+++ b/modules/fbx/data/fbx_node.h
@@ -0,0 +1,63 @@
+/*************************************************************************/
+/* fbx_node.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_NODE_H
+#define FBX_NODE_H
+
+#include "fbx_skeleton.h"
+#include "model_abstraction.h"
+#include "pivot_transform.h"
+
+#include "fbx_parser/FBXDocument.h"
+
+class Node3D;
+struct PivotTransform;
+
+struct FBXNode : Reference, ModelAbstraction {
+ uint64_t current_node_id = 0;
+ String node_name = String();
+ Node3D *godot_node = nullptr;
+
+ // used to parent the skeleton once the tree is built.
+ Ref<FBXSkeleton> skeleton_node = Ref<FBXSkeleton>();
+
+ void set_parent(Ref<FBXNode> p_parent) {
+ fbx_parent = p_parent;
+ }
+
+ void set_pivot_transform(Ref<PivotTransform> p_pivot_transform) {
+ pivot_transform = p_pivot_transform;
+ }
+
+ Ref<PivotTransform> pivot_transform = Ref<PivotTransform>(); // local and global xform data
+ Ref<FBXNode> fbx_parent = Ref<FBXNode>(); // parent node
+};
+
+#endif // FBX_NODE_H
diff --git a/modules/fbx/data/fbx_skeleton.cpp b/modules/fbx/data/fbx_skeleton.cpp
new file mode 100644
index 0000000000..622b589feb
--- /dev/null
+++ b/modules/fbx/data/fbx_skeleton.cpp
@@ -0,0 +1,123 @@
+/*************************************************************************/
+/* fbx_skeleton.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "fbx_skeleton.h"
+
+#include "import_state.h"
+
+#include "tools/import_utils.h"
+
+void FBXSkeleton::init_skeleton(const ImportState &state) {
+ int skeleton_bone_count = skeleton_bones.size();
+
+ if (skeleton == nullptr && skeleton_bone_count > 0) {
+ skeleton = memnew(Skeleton3D);
+
+ if (fbx_node.is_valid()) {
+ // cache skeleton attachment for later during node creation
+ // can't be done until after node hierarchy is built
+ if (fbx_node->godot_node != state.root) {
+ fbx_node->skeleton_node = Ref<FBXSkeleton>(this);
+ print_verbose("cached armature skeleton attachment for node " + fbx_node->node_name);
+ } else {
+ // root node must never be a skeleton to prevent cyclic skeletons from being allowed (skeleton in a skeleton)
+ fbx_node->godot_node->add_child(skeleton);
+ skeleton->set_owner(state.root_owner);
+ skeleton->set_name("Skeleton3D");
+ print_verbose("created armature skeleton for root");
+ }
+ } else {
+ memfree(skeleton);
+ skeleton = nullptr;
+ print_error("[doc] skeleton has no valid node to parent nodes to - erasing");
+ skeleton_bones.clear();
+ return;
+ }
+ }
+
+ // Make the bone name uniques.
+ for (int x = 0; x < skeleton_bone_count; x++) {
+ Ref<FBXBone> bone = skeleton_bones[x];
+ if (bone.is_valid()) {
+ // Make sure the bone name is unique.
+ const String bone_name = bone->bone_name;
+ int same_name_count = 0;
+ for (int y = x; y < skeleton_bone_count; y++) {
+ Ref<FBXBone> other_bone = skeleton_bones[y];
+ if (other_bone.is_valid()) {
+ if (other_bone->bone_name == bone_name) {
+ same_name_count += 1;
+ other_bone->bone_name += "_" + itos(same_name_count);
+ }
+ }
+ }
+ }
+ }
+
+ Map<int, Ref<FBXBone>> bone_map;
+ // implement fbx cluster skin logic here this is where it goes
+ int bone_count = 0;
+ for (int x = 0; x < skeleton_bone_count; x++) {
+ Ref<FBXBone> bone = skeleton_bones[x];
+ if (bone.is_valid()) {
+ skeleton->add_bone(bone->bone_name);
+ bone->godot_bone_id = bone_count;
+ bone->fbx_skeleton = Ref<FBXSkeleton>(this);
+ bone_map.insert(bone_count, bone);
+ print_verbose("added bone " + itos(bone->bone_id) + " " + bone->bone_name);
+ bone_count++;
+ }
+ }
+
+ ERR_FAIL_COND_MSG(skeleton->get_bone_count() != bone_count, "Not all bones got added, is the file corrupted?");
+
+ for (Map<int, Ref<FBXBone>>::Element *bone_element = bone_map.front(); bone_element; bone_element = bone_element->next()) {
+ const Ref<FBXBone> bone = bone_element->value();
+ int bone_index = bone_element->key();
+ print_verbose("working on bone: " + itos(bone_index) + " bone name:" + bone->bone_name);
+
+ skeleton->set_bone_rest(bone->godot_bone_id, get_unscaled_transform(bone->node->pivot_transform->LocalTransform, state.scale));
+
+ // lookup parent ID
+ if (bone->valid_parent && state.fbx_bone_map.has(bone->parent_bone_id)) {
+ Ref<FBXBone> parent_bone = state.fbx_bone_map[bone->parent_bone_id];
+ int bone_id = skeleton->find_bone(parent_bone->bone_name);
+ if (bone_id != -1) {
+ skeleton->set_bone_parent(bone_index, bone_id);
+ } else {
+ print_error("invalid bone parent: " + parent_bone->bone_name);
+ }
+ } else {
+ if (bone->godot_bone_id != -1) {
+ skeleton->set_bone_parent(bone_index, -1); // no parent for this bone
+ }
+ }
+ }
+}
diff --git a/modules/fbx/data/fbx_skeleton.h b/modules/fbx/data/fbx_skeleton.h
new file mode 100644
index 0000000000..df937cde49
--- /dev/null
+++ b/modules/fbx/data/fbx_skeleton.h
@@ -0,0 +1,53 @@
+/*************************************************************************/
+/* fbx_skeleton.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_SKELETON_H
+#define FBX_SKELETON_H
+
+#include "fbx_bone.h"
+#include "fbx_node.h"
+#include "model_abstraction.h"
+
+#include "core/object/reference.h"
+#include "scene/3d/skeleton_3d.h"
+
+struct FBXNode;
+struct ImportState;
+struct FBXBone;
+
+struct FBXSkeleton : Reference {
+ Ref<FBXNode> fbx_node = Ref<FBXNode>();
+ Vector<Ref<FBXBone>> skeleton_bones = Vector<Ref<FBXBone>>();
+ Skeleton3D *skeleton = nullptr;
+
+ void init_skeleton(const ImportState &state);
+};
+
+#endif // FBX_SKELETON_H
diff --git a/modules/fbx/data/import_state.h b/modules/fbx/data/import_state.h
new file mode 100644
index 0000000000..83bc43faff
--- /dev/null
+++ b/modules/fbx/data/import_state.h
@@ -0,0 +1,113 @@
+/*************************************************************************/
+/* import_state.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 IMPORT_STATE_H
+#define IMPORT_STATE_H
+
+#include "fbx_mesh_data.h"
+#include "tools/import_utils.h"
+#include "tools/validation_tools.h"
+
+#include "pivot_transform.h"
+
+#include "core/core_bind.h"
+#include "core/io/resource_importer.h"
+#include "core/templates/vector.h"
+#include "editor/import/resource_importer_scene.h"
+#include "editor/project_settings_editor.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/3d/skeleton_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/animation.h"
+#include "scene/resources/surface_tool.h"
+
+#include "modules/fbx/fbx_parser/FBXDocument.h"
+#include "modules/fbx/fbx_parser/FBXImportSettings.h"
+#include "modules/fbx/fbx_parser/FBXMeshGeometry.h"
+#include "modules/fbx/fbx_parser/FBXParser.h"
+#include "modules/fbx/fbx_parser/FBXTokenizer.h"
+#include "modules/fbx/fbx_parser/FBXUtil.h"
+
+struct FBXBone;
+struct FBXMeshData;
+struct FBXNode;
+struct FBXSkeleton;
+
+struct ImportState {
+ bool enable_material_import = true;
+ bool enable_animation_import = true;
+ bool is_blender_fbx = false;
+
+ Map<StringName, Ref<Texture>> cached_image_searches;
+ Map<uint64_t, Ref<Material>> cached_materials;
+
+ String path = String();
+ Node3D *root_owner = nullptr;
+ Node3D *root = nullptr;
+ real_t scale = 0.01;
+ Ref<FBXNode> fbx_root_node = Ref<FBXNode>();
+ // skeleton map - merged automatically when they are on the same x node in the tree so we can merge them automatically.
+ Map<uint64_t, Ref<FBXSkeleton>> skeleton_map = Map<uint64_t, Ref<FBXSkeleton>>();
+
+ // nodes on the same level get merged automatically.
+ //Map<uint64_t, Skeleton3D *> armature_map;
+ AnimationPlayer *animation_player = nullptr;
+
+ // Generation 4 - Raw document accessing for bone/skin/joint/kLocators
+ // joints are not necessarily bones but must be merged into the skeleton
+ // (bone id), bone
+ Map<uint64_t, Ref<FBXBone>> fbx_bone_map = Map<uint64_t, Ref<FBXBone>>(); // this is the bone name and setup information required for joints
+ // this will never contain joints only bones attached to a mesh.
+
+ // Generation 4 - Raw document for creating the nodes transforms in the scene
+ // this is a list of the nodes in the scene
+ // (id, node)
+ List<Ref<FBXNode>> fbx_node_list = List<Ref<FBXNode>>();
+
+ // All nodes which have been created in the scene
+ // this will not contain the root node of the scene
+ Map<uint64_t, Ref<FBXNode>> fbx_target_map = Map<uint64_t, Ref<FBXNode>>();
+
+ // mesh nodes which are created in node / mesh step - used for populating skin poses in MeshSkins
+ Map<uint64_t, Ref<FBXNode>> MeshNodes = Map<uint64_t, Ref<FBXNode>>();
+ // mesh skin map
+ Map<uint64_t, Ref<Skin>> MeshSkins = Map<uint64_t, Ref<Skin>>();
+
+ // this is the container for the mesh weight information and eventually
+ // any mesh data
+ // but not the skin, just stuff important for rendering
+ // skin is applied to mesh instance so not really required to be in here yet.
+ // maybe later
+ // fbx mesh id, FBXMeshData
+ Map<uint64_t, Ref<FBXMeshData>> renderer_mesh_data = Map<uint64_t, Ref<FBXMeshData>>();
+};
+
+#endif // IMPORT_STATE_H
diff --git a/modules/mono/glue/rid_glue.h b/modules/fbx/data/model_abstraction.h
index 506d715451..528960ab49 100644
--- a/modules/mono/glue/rid_glue.h
+++ b/modules/fbx/data/model_abstraction.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* rid_glue.h */
+/* model_abstraction.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,26 +28,25 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef RID_GLUE_H
-#define RID_GLUE_H
+#ifndef MODEL_ABSTRACTION_H
+#define MODEL_ABSTRACTION_H
-#ifdef MONO_GLUE_ENABLED
+#include "modules/fbx/fbx_parser/FBXDocument.h"
-#include "core/object.h"
-#include "core/rid.h"
+struct ModelAbstraction {
+ mutable const FBXDocParser::Model *fbx_model = nullptr;
-#include "../mono_gd/gd_mono_marshal.h"
+ void set_model(const FBXDocParser::Model *p_model) {
+ fbx_model = p_model;
+ }
-RID *godot_icall_RID_Ctor(Object *p_from);
+ bool has_model() const {
+ return fbx_model != nullptr;
+ }
-void godot_icall_RID_Dtor(RID *p_ptr);
+ const FBXDocParser::Model *get_model() const {
+ return fbx_model;
+ }
+};
-uint32_t godot_icall_RID_get_id(RID *p_ptr);
-
-// Register internal calls
-
-void godot_register_rid_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // RID_GLUE_H
+#endif // MODEL_ABSTRACTION_H
diff --git a/modules/fbx/data/pivot_transform.cpp b/modules/fbx/data/pivot_transform.cpp
new file mode 100644
index 0000000000..7a56074bc5
--- /dev/null
+++ b/modules/fbx/data/pivot_transform.cpp
@@ -0,0 +1,294 @@
+/*************************************************************************/
+/* pivot_transform.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "pivot_transform.h"
+
+#include "tools/import_utils.h"
+
+void PivotTransform::ReadTransformChain() {
+ const FBXDocParser::PropertyTable *props = fbx_model->Props();
+ const FBXDocParser::Model::RotOrder &rot = fbx_model->RotationOrder();
+ const FBXDocParser::TransformInheritance &inheritType = fbx_model->InheritType();
+ inherit_type = inheritType; // copy the inherit type we need it in the second step.
+ print_verbose("Model: " + String(fbx_model->Name().c_str()) + " Has inherit type: " + itos(fbx_model->InheritType()));
+ bool ok = false;
+ raw_pre_rotation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "PreRotation", ok));
+ if (ok) {
+ pre_rotation = ImportUtils::EulerToQuaternion(rot, ImportUtils::deg2rad(raw_pre_rotation));
+ print_verbose("valid pre_rotation: " + raw_pre_rotation + " euler conversion: " + (pre_rotation.get_euler() * (180 / Math_PI)));
+ }
+ raw_post_rotation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "PostRotation", ok));
+ if (ok) {
+ post_rotation = ImportUtils::EulerToQuaternion(FBXDocParser::Model::RotOrder_EulerXYZ, ImportUtils::deg2rad(raw_post_rotation));
+ print_verbose("valid post_rotation: " + raw_post_rotation + " euler conversion: " + (pre_rotation.get_euler() * (180 / Math_PI)));
+ }
+ const Vector3 &RotationPivot = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "RotationPivot", ok));
+ if (ok) {
+ rotation_pivot = ImportUtils::FixAxisConversions(RotationPivot);
+ }
+ const Vector3 &RotationOffset = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "RotationOffset", ok));
+ if (ok) {
+ rotation_offset = ImportUtils::FixAxisConversions(RotationOffset);
+ }
+ const Vector3 &ScalingOffset = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "ScalingOffset", ok));
+ if (ok) {
+ scaling_offset = ImportUtils::FixAxisConversions(ScalingOffset);
+ }
+ const Vector3 &ScalingPivot = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "ScalingPivot", ok));
+ if (ok) {
+ scaling_pivot = ImportUtils::FixAxisConversions(ScalingPivot);
+ }
+ const Vector3 &Translation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "Lcl Translation", ok));
+ if (ok) {
+ translation = ImportUtils::FixAxisConversions(Translation);
+ }
+ raw_rotation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "Lcl Rotation", ok));
+ if (ok) {
+ rotation = ImportUtils::EulerToQuaternion(rot, ImportUtils::deg2rad(raw_rotation));
+ }
+ const Vector3 &Scaling = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "Lcl Scaling", ok));
+ if (ok) {
+ scaling = Scaling;
+ }
+ const Vector3 &GeometricScaling = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "GeometricScaling", ok));
+ if (ok) {
+ geometric_scaling = GeometricScaling;
+ } else {
+ geometric_scaling = Vector3(0, 0, 0);
+ }
+
+ const Vector3 &GeometricRotation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "GeometricRotation", ok));
+ if (ok) {
+ geometric_rotation = ImportUtils::EulerToQuaternion(rot, ImportUtils::deg2rad(GeometricRotation));
+ } else {
+ geometric_rotation = Quat();
+ }
+
+ const Vector3 &GeometricTranslation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "GeometricTranslation", ok));
+ if (ok) {
+ geometric_translation = ImportUtils::FixAxisConversions(GeometricTranslation);
+ } else {
+ geometric_translation = Vector3(0, 0, 0);
+ }
+
+ if (geometric_rotation != Quat()) {
+ print_error("geometric rotation is unsupported!");
+ //CRASH_COND(true);
+ }
+
+ if (!geometric_scaling.is_equal_approx(Vector3(1, 1, 1))) {
+ print_error("geometric scaling is unsupported!");
+ //CRASH_COND(true);
+ }
+
+ if (!geometric_translation.is_equal_approx(Vector3(0, 0, 0))) {
+ print_error("geometric translation is unsupported.");
+ //CRASH_COND(true);
+ }
+}
+
+Transform PivotTransform::ComputeLocalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const {
+ Transform T, Roff, Rp, Soff, Sp, S;
+
+ // Here I assume this is the operation which needs done.
+ // Its WorldTransform * V
+
+ // Origin pivots
+ T.set_origin(p_translation);
+ Roff.set_origin(rotation_offset);
+ Rp.set_origin(rotation_pivot);
+ Soff.set_origin(scaling_offset);
+ Sp.set_origin(scaling_pivot);
+
+ // Scaling node
+ S.scale(p_scaling);
+ // Rotation pivots
+ Transform Rpre = Transform(pre_rotation);
+ Transform R = Transform(p_rotation);
+ Transform Rpost = Transform(post_rotation);
+
+ return T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse();
+}
+
+Transform PivotTransform::ComputeGlobalTransform(Transform t) const {
+ Vector3 pos = t.origin;
+ Vector3 scale = t.basis.get_scale();
+ Quat rot = t.basis.get_rotation_quat();
+ return ComputeGlobalTransform(pos, rot, scale);
+}
+
+Transform PivotTransform::ComputeLocalTransform(Transform t) const {
+ Vector3 pos = t.origin;
+ Vector3 scale = t.basis.get_scale();
+ Quat rot = t.basis.get_rotation_quat();
+ return ComputeLocalTransform(pos, rot, scale);
+}
+
+Transform PivotTransform::ComputeGlobalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const {
+ Transform T, Roff, Rp, Soff, Sp, S;
+
+ // Here I assume this is the operation which needs done.
+ // Its WorldTransform * V
+
+ // Origin pivots
+ T.set_origin(p_translation);
+ Roff.set_origin(rotation_offset);
+ Rp.set_origin(rotation_pivot);
+ Soff.set_origin(scaling_offset);
+ Sp.set_origin(scaling_pivot);
+
+ // Scaling node
+ S.scale(p_scaling);
+
+ // Rotation pivots
+ Transform Rpre = Transform(pre_rotation);
+ Transform R = Transform(p_rotation);
+ Transform Rpost = Transform(post_rotation);
+
+ Transform parent_global_xform;
+ Transform parent_local_scaling_m;
+
+ if (parent_transform.is_valid()) {
+ parent_global_xform = parent_transform->GlobalTransform;
+ parent_local_scaling_m = parent_transform->Local_Scaling_Matrix;
+ }
+
+ Transform local_rotation_m, parent_global_rotation_m;
+ Quat parent_global_rotation = parent_global_xform.basis.get_rotation_quat();
+ parent_global_rotation_m.basis.set_quat(parent_global_rotation);
+ local_rotation_m = Rpre * R * Rpost;
+
+ //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quat().normalized());
+
+ Transform local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation;
+ Vector3 parent_translation = parent_global_xform.get_origin();
+ parent_shear_translation.origin = parent_translation;
+ parent_shear_rotation = parent_shear_translation.affine_inverse() * parent_global_xform;
+ parent_shear_scaling = parent_global_rotation_m.affine_inverse() * parent_shear_rotation;
+ local_shear_scaling = S;
+
+ // Inherit type handler - we don't care about T here, just reordering RSrs etc.
+ Transform global_rotation_scale;
+ if (inherit_type == FBXDocParser::Transform_RrSs) {
+ global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_shear_scaling * local_shear_scaling;
+ } else if (inherit_type == FBXDocParser::Transform_RSrs) {
+ global_rotation_scale = parent_global_rotation_m * parent_shear_scaling * local_rotation_m * local_shear_scaling;
+ } else if (inherit_type == FBXDocParser::Transform_Rrs) {
+ Transform parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.affine_inverse();
+ global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_global_shear_m_noLocal * local_shear_scaling;
+ }
+ Transform local_transform = T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse();
+ //Transform local_translation_pivoted = Transform(Basis(), LocalTransform.origin);
+
+ // manual hack to force SSC not to be compensated for - until we can handle it properly with tests
+ return parent_global_xform * local_transform;
+}
+
+void PivotTransform::ComputePivotTransform() {
+ Transform T, Roff, Rp, Soff, Sp, S;
+
+ // Here I assume this is the operation which needs done.
+ // Its WorldTransform * V
+
+ // Origin pivots
+ T.set_origin(translation);
+ Roff.set_origin(rotation_offset);
+ Rp.set_origin(rotation_pivot);
+ Soff.set_origin(scaling_offset);
+ Sp.set_origin(scaling_pivot);
+
+ // Scaling node
+ if (!scaling.is_equal_approx(Vector3())) {
+ S.scale(scaling);
+ } else {
+ S.scale(Vector3(1, 1, 1));
+ }
+ Local_Scaling_Matrix = S; // copy for when node / child is looking for the value of this.
+
+ // Rotation pivots
+ Transform Rpre = Transform(pre_rotation);
+ Transform R = Transform(rotation);
+ Transform Rpost = Transform(post_rotation);
+
+ Transform parent_global_xform;
+ Transform parent_local_scaling_m;
+
+ if (parent_transform.is_valid()) {
+ parent_global_xform = parent_transform->GlobalTransform;
+ parent_local_scaling_m = parent_transform->Local_Scaling_Matrix;
+ }
+
+ Transform local_rotation_m, parent_global_rotation_m;
+ Quat parent_global_rotation = parent_global_xform.basis.get_rotation_quat();
+ parent_global_rotation_m.basis.set_quat(parent_global_rotation);
+ local_rotation_m = Rpre * R * Rpost;
+
+ //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quat().normalized());
+
+ Transform local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation;
+ Vector3 parent_translation = parent_global_xform.get_origin();
+ parent_shear_translation.origin = parent_translation;
+ parent_shear_rotation = parent_shear_translation.affine_inverse() * parent_global_xform;
+ parent_shear_scaling = parent_global_rotation_m.affine_inverse() * parent_shear_rotation;
+ local_shear_scaling = S;
+
+ // Inherit type handler - we don't care about T here, just reordering RSrs etc.
+ Transform global_rotation_scale;
+ if (inherit_type == FBXDocParser::Transform_RrSs) {
+ global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_shear_scaling * local_shear_scaling;
+ } else if (inherit_type == FBXDocParser::Transform_RSrs) {
+ global_rotation_scale = parent_global_rotation_m * parent_shear_scaling * local_rotation_m * local_shear_scaling;
+ } else if (inherit_type == FBXDocParser::Transform_Rrs) {
+ Transform parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.inverse();
+ global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_global_shear_m_noLocal * local_shear_scaling;
+ }
+ LocalTransform = Transform();
+ LocalTransform = T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse();
+
+ ERR_FAIL_COND_MSG(LocalTransform.basis.determinant() == 0, "invalid scale reset");
+
+ Transform local_translation_pivoted = Transform(Basis(), LocalTransform.origin);
+ GlobalTransform = Transform();
+ //GlobalTransform = parent_global_xform * LocalTransform;
+ Transform global_origin = Transform(Basis(), parent_translation);
+ GlobalTransform = (global_origin * local_translation_pivoted) * global_rotation_scale;
+
+ ImportUtils::debug_xform("local xform calculation", LocalTransform);
+ print_verbose("scale of node: " + S.basis.get_scale_local());
+ print_verbose("---------------------------------------------------------------");
+}
+
+void PivotTransform::Execute() {
+ ReadTransformChain();
+ ComputePivotTransform();
+
+ ImportUtils::debug_xform("global xform: ", GlobalTransform);
+ computed_global_xform = true;
+}
diff --git a/modules/fbx/data/pivot_transform.h b/modules/fbx/data/pivot_transform.h
new file mode 100644
index 0000000000..9996027870
--- /dev/null
+++ b/modules/fbx/data/pivot_transform.h
@@ -0,0 +1,115 @@
+/*************************************************************************/
+/* pivot_transform.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 PIVOT_TRANSFORM_H
+#define PIVOT_TRANSFORM_H
+
+#include "core/math/transform.h"
+#include "core/object/reference.h"
+
+#include "model_abstraction.h"
+
+#include "fbx_parser/FBXDocument.h"
+#include "tools/import_utils.h"
+
+enum TransformationComp {
+ TransformationComp_Translation,
+ TransformationComp_Scaling,
+ TransformationComp_Rotation,
+ TransformationComp_RotationOffset,
+ TransformationComp_RotationPivot,
+ TransformationComp_PreRotation,
+ TransformationComp_PostRotation,
+ TransformationComp_ScalingOffset,
+ TransformationComp_ScalingPivot,
+ TransformationComp_GeometricTranslation,
+ TransformationComp_GeometricRotation,
+ TransformationComp_GeometricScaling,
+ TransformationComp_MAXIMUM
+};
+// Abstract away pivot data so its simpler to handle
+struct PivotTransform : Reference, ModelAbstraction {
+ // at the end we want to keep geometric_ everything, post and pre rotation
+ // these are used during animation data processing / keyframe ingestion the rest can be simplified down / out.
+ Quat pre_rotation = Quat();
+ Quat post_rotation = Quat();
+ Quat rotation = Quat();
+ Quat geometric_rotation = Quat();
+ Vector3 rotation_pivot = Vector3();
+ Vector3 rotation_offset = Vector3();
+ Vector3 scaling_offset = Vector3(1.0, 1.0, 1.0);
+ Vector3 scaling_pivot = Vector3(1.0, 1.0, 1.0);
+ Vector3 translation = Vector3();
+ Vector3 scaling = Vector3(1.0, 1.0, 1.0);
+ Vector3 geometric_scaling = Vector3(1.0, 1.0, 1.0);
+ Vector3 geometric_translation = Vector3();
+
+ Vector3 raw_rotation = Vector3();
+ Vector3 raw_post_rotation = Vector3();
+ Vector3 raw_pre_rotation = Vector3();
+
+ /* Read pivots from the document */
+ void ReadTransformChain();
+
+ void debug_pivot_xform(String p_name) {
+ print_verbose("debugging node name: " + p_name);
+ print_verbose("raw rotation: " + raw_rotation * (180 / Math_PI));
+ print_verbose("raw pre_rotation " + raw_pre_rotation * (180 / Math_PI));
+ print_verbose("raw post_rotation " + raw_post_rotation * (180 / Math_PI));
+ }
+
+ Transform ComputeGlobalTransform(Transform t) const;
+ Transform ComputeLocalTransform(Transform t) const;
+ Transform ComputeGlobalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const;
+ Transform ComputeLocalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const;
+
+ /* Extract into xforms and calculate once */
+ void ComputePivotTransform();
+
+ /* Execute the command for the pivot generation */
+ void Execute();
+
+ void set_parent(Ref<PivotTransform> p_parent) {
+ parent_transform = p_parent;
+ }
+
+ bool computed_global_xform = false;
+ Ref<PivotTransform> parent_transform = Ref<PivotTransform>();
+ //Transform chain[TransformationComp_MAXIMUM];
+
+ // cached for later use
+ Transform GlobalTransform = Transform();
+ Transform LocalTransform = Transform();
+ Transform Local_Scaling_Matrix = Transform(); // used for inherit type.
+ Transform GeometricTransform = Transform(); // 3DS max only
+ FBXDocParser::TransformInheritance inherit_type = FBXDocParser::TransformInheritance_MAX; // maya fbx requires this - sorry <3
+};
+
+#endif // PIVOT_TRANSFORM_H
diff --git a/modules/fbx/doc_classes/EditorSceneImporterFBX.xml b/modules/fbx/doc_classes/EditorSceneImporterFBX.xml
new file mode 100644
index 0000000000..da1a68c27c
--- /dev/null
+++ b/modules/fbx/doc_classes/EditorSceneImporterFBX.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="EditorSceneImporterFBX" inherits="EditorSceneImporter" version="4.0">
+ <brief_description>
+ FBX 3D asset importer.
+ </brief_description>
+ <description>
+ This is an FBX 3D asset importer with full support for most FBX features.
+ If exporting a FBX scene from Autodesk Maya, use these FBX export settings:
+ [codeblock]
+ - Smoothing Groups
+ - Smooth Mesh
+ - Triangluate (for meshes with blend shapes)
+ - Bake Animation
+ - Resample All
+ - Deformed Models
+ - Skins
+ - Blend Shapes
+ - Curve Filters
+ - Constant Key Reducer
+ - Auto Tangents Only
+ - *Do not check* Constraints (as it will break the file)
+ - Can check Embed Media (embeds textures into the exported FBX file)
+ - Note that when importing embedded media, the texture and mesh will be a single immutable file.
+ - You will have to re-export then re-import the FBX if the texture has changed.
+ - Units: Centimeters
+ - Up Axis: Y
+ - Binary format in FBX 2017
+ [/codeblock]
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/fbx/editor_scene_importer_fbx.cpp b/modules/fbx/editor_scene_importer_fbx.cpp
new file mode 100644
index 0000000000..6576147b2b
--- /dev/null
+++ b/modules/fbx/editor_scene_importer_fbx.cpp
@@ -0,0 +1,1427 @@
+/*************************************************************************/
+/* editor_scene_importer_fbx.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_scene_importer_fbx.h"
+
+#include "data/fbx_anim_container.h"
+#include "data/fbx_material.h"
+#include "data/fbx_mesh_data.h"
+#include "data/fbx_skeleton.h"
+#include "tools/import_utils.h"
+
+#include "core/io/image_loader.h"
+#include "editor/editor_log.h"
+#include "editor/editor_node.h"
+#include "editor/import/resource_importer_scene.h"
+#include "editor/import/scene_importer_mesh_node_3d.h"
+#include "scene/3d/bone_attachment_3d.h"
+#include "scene/3d/camera_3d.h"
+#include "scene/3d/light_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/main/node.h"
+#include "scene/resources/material.h"
+
+#include "fbx_parser/FBXDocument.h"
+#include "fbx_parser/FBXImportSettings.h"
+#include "fbx_parser/FBXMeshGeometry.h"
+#include "fbx_parser/FBXParser.h"
+#include "fbx_parser/FBXProperties.h"
+#include "fbx_parser/FBXTokenizer.h"
+
+#include <string>
+
+void EditorSceneImporterFBX::get_extensions(List<String> *r_extensions) const {
+ // register FBX as the one and only format for FBX importing
+ const String import_setting_string = "filesystem/import/fbx/";
+ const String fbx_str = "fbx";
+ Vector<String> exts;
+ exts.push_back(fbx_str);
+ _register_project_setting_import(fbx_str, import_setting_string, exts, r_extensions, true);
+}
+
+void EditorSceneImporterFBX::_register_project_setting_import(const String generic,
+ const String import_setting_string,
+ const Vector<String> &exts,
+ List<String> *r_extensions,
+ const bool p_enabled) const {
+ const String use_generic = "use_" + generic;
+ _GLOBAL_DEF(import_setting_string + use_generic, p_enabled, true);
+ if (ProjectSettings::get_singleton()->get(import_setting_string + use_generic)) {
+ for (int32_t i = 0; i < exts.size(); i++) {
+ r_extensions->push_back(exts[i]);
+ }
+ }
+}
+
+uint32_t EditorSceneImporterFBX::get_import_flags() const {
+ return IMPORT_SCENE;
+}
+
+Node3D *EditorSceneImporterFBX::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps,
+ List<String> *r_missing_deps, Error *r_err) {
+ // done for performance when re-importing lots of files when testing importer in verbose only!
+ if (OS::get_singleton()->is_stdout_verbose()) {
+ EditorLog *log = EditorNode::get_log();
+ log->clear();
+ }
+ Error err;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
+
+ ERR_FAIL_COND_V(!f, NULL);
+
+ {
+ PackedByteArray data;
+ // broadphase tokenizing pass in which we identify the core
+ // syntax elements of FBX (brackets, commas, key:value mappings)
+ FBXDocParser::TokenList tokens;
+
+ bool is_binary = false;
+ data.resize(f->get_len());
+ f->get_buffer(data.ptrw(), data.size());
+ PackedByteArray fbx_header;
+ fbx_header.resize(64);
+ for (int32_t byte_i = 0; byte_i < 64; byte_i++) {
+ fbx_header.ptrw()[byte_i] = data.ptr()[byte_i];
+ }
+
+ String fbx_header_string;
+ if (fbx_header.size() >= 0) {
+ fbx_header_string.parse_utf8((const char *)fbx_header.ptr(), fbx_header.size());
+ }
+
+ print_verbose("[doc] opening fbx file: " + p_path);
+ print_verbose("[doc] fbx header: " + fbx_header_string);
+
+ // safer to check this way as there can be different formatted headers
+ if (fbx_header_string.find("Kaydara FBX Binary", 0) != -1) {
+ is_binary = true;
+ print_verbose("[doc] is binary");
+ FBXDocParser::TokenizeBinary(tokens, (const char *)data.ptrw(), (size_t)data.size());
+ } else {
+ print_verbose("[doc] is ascii");
+ FBXDocParser::Tokenize(tokens, (const char *)data.ptrw(), (size_t)data.size());
+ }
+
+ // The import process explained:
+ // 1. Tokens are made, these are then taken into the 'parser' below
+ // 2. The parser constructs 'Elements' and all 'real' FBX Types.
+ // 3. This creates a problem: shared_ptr ownership, should Elements later 'take ownership'
+ // 4. No, it shouldn't so we should either a.) use weak ref for elements; but this is not correct.
+
+ // use this information to construct a very rudimentary
+ // parse-tree representing the FBX scope structure
+ FBXDocParser::Parser parser(tokens, is_binary);
+ FBXDocParser::ImportSettings settings;
+ settings.strictMode = false;
+
+ // this function leaks a lot
+ FBXDocParser::Document doc(parser, settings);
+
+ // yeah so closing the file is a good idea (prevents readonly states)
+ f->close();
+
+ // safety for version handling
+ if (doc.IsSafeToImport()) {
+ bool is_blender_fbx = false;
+ //const FBXDocParser::PropertyPtr app_vendor = p_document->GlobalSettingsPtr()->Props()
+ // p_document->Creator()
+ const FBXDocParser::PropertyTable *import_props = doc.GetMetadataProperties();
+ const FBXDocParser::PropertyPtr app_name = import_props->Get("Original|ApplicationName");
+ const FBXDocParser::PropertyPtr app_vendor = import_props->Get("Original|ApplicationVendor");
+ const FBXDocParser::PropertyPtr app_version = import_props->Get("Original|ApplicationVersion");
+ //
+ if (app_name) {
+ const FBXDocParser::TypedProperty<std::string> *app_name_string = dynamic_cast<const FBXDocParser::TypedProperty<std::string> *>(app_name);
+ if (app_name_string) {
+ print_verbose("FBX App Name: " + String(app_name_string->Value().c_str()));
+ }
+ }
+
+ if (app_vendor) {
+ const FBXDocParser::TypedProperty<std::string> *app_vendor_string = dynamic_cast<const FBXDocParser::TypedProperty<std::string> *>(app_vendor);
+ if (app_vendor_string) {
+ print_verbose("FBX App Vendor: " + String(app_vendor_string->Value().c_str()));
+ is_blender_fbx = app_vendor_string->Value().find("Blender") != std::string::npos;
+ }
+ }
+
+ if (app_version) {
+ const FBXDocParser::TypedProperty<std::string> *app_version_string = dynamic_cast<const FBXDocParser::TypedProperty<std::string> *>(app_version);
+ if (app_version_string) {
+ print_verbose("FBX App Version: " + String(app_version_string->Value().c_str()));
+ }
+ }
+
+ if (is_blender_fbx) {
+ WARN_PRINT("We don't officially support Blender FBX animations yet, due to issues with upstream Blender,\n"
+ "so please wait for us to work around remaining issues. We will continue to import the file but it may be broken.\n"
+ "For minimal breakage, please export FBX from Blender with -Z forward, and Y up.");
+ }
+
+ Node3D *spatial = _generate_scene(p_path, &doc, p_flags, p_bake_fps, 8, is_blender_fbx);
+ // todo: move to document shutdown (will need to be validated after moving; this code has been validated already)
+ for (FBXDocParser::TokenPtr token : tokens) {
+ if (token) {
+ delete token;
+ token = nullptr;
+ }
+ }
+
+ return spatial;
+
+ } else {
+ ERR_PRINT(vformat("Cannot import FBX file: %s. It uses file format %d which is unsupported by Godot. Please re-export it or convert it to a newer format.", p_path, doc.FBXVersion()));
+ }
+ }
+
+ return memnew(Node3D);
+}
+
+template <class T>
+struct EditorSceneImporterAssetImportInterpolate {
+ T lerp(const T &a, const T &b, float c) const {
+ return a + (b - a) * c;
+ }
+
+ T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
+ const float t2 = t * t;
+ const float t3 = t2 * t;
+
+ return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
+ }
+
+ T bezier(T start, T control_1, T control_2, T end, float t) {
+ /* Formula from Wikipedia article on Bezier curves. */
+ const real_t omt = (1.0 - t);
+ const real_t omt2 = omt * omt;
+ const real_t omt3 = omt2 * omt;
+ const real_t t2 = t * t;
+ const real_t t3 = t2 * t;
+
+ return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
+ }
+};
+
+//thank you for existing, partial specialization
+template <>
+struct EditorSceneImporterAssetImportInterpolate<Quat> {
+ Quat lerp(const Quat &a, const Quat &b, float c) const {
+ ERR_FAIL_COND_V(!a.is_normalized(), Quat());
+ ERR_FAIL_COND_V(!b.is_normalized(), Quat());
+
+ return a.slerp(b, c).normalized();
+ }
+
+ Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
+ ERR_FAIL_COND_V(!p1.is_normalized(), Quat());
+ ERR_FAIL_COND_V(!p2.is_normalized(), Quat());
+
+ return p1.slerp(p2, c).normalized();
+ }
+
+ Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
+ ERR_FAIL_COND_V(!start.is_normalized(), Quat());
+ ERR_FAIL_COND_V(!end.is_normalized(), Quat());
+
+ return start.slerp(end, t).normalized();
+ }
+};
+
+template <class T>
+T EditorSceneImporterFBX::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time,
+ AssetImportAnimation::Interpolation p_interp) {
+ //could use binary search, worth it?
+ int idx = -1;
+ for (int i = 0; i < p_times.size(); i++) {
+ if (p_times[i] > p_time)
+ break;
+ idx++;
+ }
+
+ EditorSceneImporterAssetImportInterpolate<T> interp;
+
+ switch (p_interp) {
+ case AssetImportAnimation::INTERP_LINEAR: {
+ if (idx == -1) {
+ return p_values[0];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[p_times.size() - 1];
+ }
+
+ float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ return interp.lerp(p_values[idx], p_values[idx + 1], c);
+
+ } break;
+ case AssetImportAnimation::INTERP_STEP: {
+ if (idx == -1) {
+ return p_values[0];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[p_times.size() - 1];
+ }
+
+ return p_values[idx];
+
+ } break;
+ case AssetImportAnimation::INTERP_CATMULLROMSPLINE: {
+ if (idx == -1) {
+ return p_values[1];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[1 + p_times.size() - 1];
+ }
+
+ float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
+
+ } break;
+ case AssetImportAnimation::INTERP_CUBIC_SPLINE: {
+ if (idx == -1) {
+ return p_values[1];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[(p_times.size() - 1) * 3 + 1];
+ }
+
+ float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ T from = p_values[idx * 3 + 1];
+ T c1 = from + p_values[idx * 3 + 2];
+ T to = p_values[idx * 3 + 4];
+ T c2 = to + p_values[idx * 3 + 3];
+
+ return interp.bezier(from, c1, c2, to, c);
+
+ } break;
+ }
+
+ ERR_FAIL_V(p_values[0]);
+}
+
+Node3D *EditorSceneImporterFBX::_generate_scene(
+ const String &p_path,
+ const FBXDocParser::Document *p_document,
+ const uint32_t p_flags,
+ int p_bake_fps,
+ const int32_t p_max_bone_weights,
+ bool p_is_blender_fbx) {
+ ImportState state;
+ state.is_blender_fbx = p_is_blender_fbx;
+ state.path = p_path;
+ state.animation_player = NULL;
+
+ // create new root node for scene
+ Node3D *scene_root = memnew(Node3D);
+ state.root = memnew(Node3D);
+ state.root_owner = scene_root; // the real scene root... sorry compatibility code is painful...
+
+ state.root->set_name("RootNode");
+ scene_root->add_child(state.root);
+ state.root->set_owner(scene_root);
+
+ state.fbx_root_node.instance();
+ state.fbx_root_node->godot_node = state.root;
+
+ // Size relative to cm.
+ const real_t fbx_unit_scale = p_document->GlobalSettingsPtr()->UnitScaleFactor();
+
+ print_verbose("FBX unit scale import value: " + rtos(fbx_unit_scale));
+ // Set FBX file scale is relative to CM must be converted to M
+ state.scale = fbx_unit_scale / 100.0;
+ print_verbose("FBX unit scale is: " + rtos(state.scale));
+
+ // Enabled by default.
+ state.enable_material_import = true;
+ // Enabled by default.
+ state.enable_animation_import = true;
+ Ref<FBXNode> root_node;
+ root_node.instance();
+
+ // make sure fake noFBXDocParser::PropertyPtr ptrde always has a transform too ;)
+ Ref<PivotTransform> pivot_transform;
+ pivot_transform.instance();
+ root_node->pivot_transform = pivot_transform;
+ root_node->node_name = "root node";
+ root_node->current_node_id = 0;
+ root_node->godot_node = state.root;
+
+ // cache this node onto the fbx_target map.
+ state.fbx_target_map.insert(0, root_node);
+
+ // cache basic node information from FBX document
+ // grabs all FBX bones
+ BuildDocumentBones(Ref<FBXBone>(), state, p_document, 0L);
+ BuildDocumentNodes(Ref<PivotTransform>(), state, p_document, 0L, nullptr);
+
+ // Build document skinning information
+
+ // Algorithm is this:
+ // Get Deformer: object with "Skin" class.
+ // Deformer:: has link to Geometry:: (correct mesh for skin)
+ // Deformer:: has Source which is the SubDeformer:: (e.g. the Cluster)
+ // Notes at the end it configures the vertex weight mapping.
+
+ for (uint64_t skin_id : p_document->GetSkinIDs()) {
+ // Validate the parser
+ FBXDocParser::LazyObject *lazy_skin = p_document->GetObject(skin_id);
+ ERR_CONTINUE_MSG(lazy_skin == nullptr, "invalid lazy object [serious parser bug]");
+
+ // Validate the parser
+ const FBXDocParser::Skin *skin = lazy_skin->Get<FBXDocParser::Skin>();
+ ERR_CONTINUE_MSG(skin == nullptr, "invalid skin added to skin list [parser bug]");
+
+ const std::vector<const FBXDocParser::Connection *> source_to_destination = p_document->GetConnectionsBySourceSequenced(skin_id);
+ FBXDocParser::MeshGeometry *mesh = nullptr;
+ uint64_t mesh_id = 0;
+
+ // Most likely only contains the mesh link for the skin
+ // The mesh geometry.
+ for (const FBXDocParser::Connection *con : source_to_destination) {
+ // do something
+ print_verbose("src: " + itos(con->src));
+ FBXDocParser::Object *ob = con->DestinationObject();
+ mesh = dynamic_cast<FBXDocParser::MeshGeometry *>(ob);
+
+ if (mesh) {
+ mesh_id = mesh->ID();
+ break;
+ }
+ }
+
+ // Validate the mesh exists and was retrieved
+ ERR_CONTINUE_MSG(mesh_id == 0, "mesh id is invalid");
+ const std::vector<const FBXDocParser::Cluster *> clusters = skin->Clusters();
+
+ // NOTE: this will ONLY work on skinned bones (it is by design.)
+ // A cluster is a skinned bone so SKINS won't contain unskinned bones so we need to pre-add all bones and parent them in a step beforehand.
+ for (const FBXDocParser::Cluster *cluster : clusters) {
+ ERR_CONTINUE_MSG(cluster == nullptr, "invalid bone cluster");
+ const uint64_t deformer_id = cluster->ID();
+ std::vector<const FBXDocParser::Connection *> connections = p_document->GetConnectionsByDestinationSequenced(deformer_id);
+
+ // Weight data always has a node in the scene lets grab the limb's node in the scene :) (reverse set to true since it's the opposite way around)
+ const FBXDocParser::ModelLimbNode *limb_node = ProcessDOMConnection<FBXDocParser::ModelLimbNode>(p_document, deformer_id, true);
+
+ ERR_CONTINUE_MSG(limb_node == nullptr, "unable to resolve model for skinned bone");
+
+ const uint64_t model_id = limb_node->ID();
+
+ // This will never happen, so if it does you know you fucked up.
+ ERR_CONTINUE_MSG(!state.fbx_bone_map.has(model_id), "missing LimbNode detected");
+
+ // new bone instance
+ Ref<FBXBone> bone_element = state.fbx_bone_map[model_id];
+
+ //
+ // Bone Weight Information Configuration
+ //
+
+ // Cache Weight Information into bone for later usage if you want the raw data.
+ const std::vector<unsigned int> &indexes = cluster->GetIndices();
+ const std::vector<float> &weights = cluster->GetWeights();
+ Ref<FBXMeshData> mesh_vertex_data;
+
+ // this data will pre-exist if vertex weight information is found
+ if (state.renderer_mesh_data.has(mesh_id)) {
+ mesh_vertex_data = state.renderer_mesh_data[mesh_id];
+ } else {
+ mesh_vertex_data.instance();
+ state.renderer_mesh_data.insert(mesh_id, mesh_vertex_data);
+ }
+
+ mesh_vertex_data->armature_id = bone_element->armature_id;
+ mesh_vertex_data->valid_armature_id = true;
+
+ //print_verbose("storing mesh vertex data for mesh to use later");
+ ERR_CONTINUE_MSG(indexes.size() != weights.size(), "[doc] error mismatch between weight info");
+
+ for (size_t idx = 0; idx < indexes.size(); idx++) {
+ const size_t vertex_index = indexes[idx];
+ const real_t influence_weight = weights[idx];
+
+ VertexWeightMapping &vm = mesh_vertex_data->vertex_weights[vertex_index];
+ vm.weights.push_back(influence_weight);
+ vm.bones.push_back(0); // bone id is pushed on here during sanitization phase
+ vm.bones_ref.push_back(bone_element);
+ }
+
+ for (const int *vertex_index = mesh_vertex_data->vertex_weights.next(nullptr);
+ vertex_index != nullptr;
+ vertex_index = mesh_vertex_data->vertex_weights.next(vertex_index)) {
+ VertexWeightMapping *vm = mesh_vertex_data->vertex_weights.getptr(*vertex_index);
+ const int influence_count = vm->weights.size();
+ if (influence_count > mesh_vertex_data->max_weight_count) {
+ mesh_vertex_data->max_weight_count = influence_count;
+ mesh_vertex_data->valid_weight_count = true;
+ }
+ }
+
+ if (mesh_vertex_data->max_weight_count > 4) {
+ if (mesh_vertex_data->max_weight_count > 8) {
+ ERR_PRINT("[doc] Serious: maximum bone influences is 8 in this branch.");
+ }
+ // Clamp to 8 bone vertex influences.
+ mesh_vertex_data->max_weight_count = 8;
+ print_verbose("[doc] Using 8 vertex bone influences configuration.");
+ } else {
+ mesh_vertex_data->max_weight_count = 4;
+ print_verbose("[doc] Using 4 vertex bone influences configuration.");
+ }
+ }
+ }
+
+ // do we globally allow for import of materials
+ // (prevents overwrite of materials; so you can handle them explicitly)
+ if (state.enable_material_import) {
+ const std::vector<uint64_t> &materials = p_document->GetMaterialIDs();
+
+ for (uint64_t material_id : materials) {
+ FBXDocParser::LazyObject *lazy_material = p_document->GetObject(material_id);
+ FBXDocParser::Material *mat = (FBXDocParser::Material *)lazy_material->Get<FBXDocParser::Material>();
+ ERR_CONTINUE_MSG(!mat, "Could not convert fbx material by id: " + itos(material_id));
+
+ Ref<FBXMaterial> material;
+ material.instance();
+ material->set_imported_material(mat);
+
+ Ref<StandardMaterial3D> godot_material = material->import_material(state);
+
+ state.cached_materials.insert(material_id, godot_material);
+ }
+ }
+
+ // build skin and skeleton information
+ print_verbose("[doc] Skeleton3D Bone count: " + itos(state.fbx_bone_map.size()));
+
+ // Importing bones using document based method from FBX directly
+ // We do not use the assimp bone format to determine this information anymore.
+ if (state.fbx_bone_map.size() > 0) {
+ // We are using a single skeleton only method here
+ // this is because we really have no concept of skeletons in FBX
+ // their are bones in a scene but they have no specific armature
+ // we can detect armatures but the issue lies in the complexity
+ // we opted to merge the entire scene onto one skeleton for now
+ // if we need to change this we have an archive of the old code.
+
+ // bind pose normally only has 1 per mesh but can have more than one
+ // this is the point of skins
+ // in FBX first bind pose is the master for the first skin
+
+ // In order to handle the FBX skeleton we must also inverse any parent transforms on the bones
+ // just to rule out any parent node transforms in the bone data
+ // this is trivial to do and allows us to use the single skeleton method and merge them
+ // this means that the nodes from maya kLocators will be preserved as bones
+ // in the same rig without having to match this across skeletons and merge by detection
+ // we can just merge and undo any parent transforms
+ for (Map<uint64_t, Ref<FBXBone>>::Element *bone_element = state.fbx_bone_map.front(); bone_element; bone_element = bone_element->next()) {
+ Ref<FBXBone> bone = bone_element->value();
+ Ref<FBXSkeleton> fbx_skeleton_inst;
+
+ uint64_t armature_id = bone->armature_id;
+ if (state.skeleton_map.has(armature_id)) {
+ fbx_skeleton_inst = state.skeleton_map[armature_id];
+ } else {
+ fbx_skeleton_inst.instance();
+ state.skeleton_map.insert(armature_id, fbx_skeleton_inst);
+ }
+
+ print_verbose("populating skeleton with bone: " + bone->bone_name);
+
+ //// populate bone skeleton - since fbx has no DOM for the skeleton just a node.
+ //bone->bone_skeleton = fbx_skeleton_inst;
+
+ // now populate bone on the armature node list
+ fbx_skeleton_inst->skeleton_bones.push_back(bone);
+
+ CRASH_COND_MSG(!state.fbx_target_map.has(armature_id), "invalid armature [serious]");
+
+ Ref<FBXNode> node = state.fbx_target_map[armature_id];
+
+ CRASH_COND_MSG(node.is_null(), "invalid node [serious]");
+ CRASH_COND_MSG(node->pivot_transform.is_null(), "invalid pivot transform [serious]");
+ fbx_skeleton_inst->fbx_node = node;
+
+ ERR_CONTINUE_MSG(fbx_skeleton_inst->fbx_node.is_null(), "invalid skeleton node [serious]");
+
+ // we need to have a valid armature id and the model configured for the bone to be assigned fully.
+ // happens once per skeleton
+
+ if (state.fbx_target_map.has(armature_id) && !fbx_skeleton_inst->fbx_node->has_model()) {
+ print_verbose("allocated fbx skeleton primary / armature node for the level: " + fbx_skeleton_inst->fbx_node->node_name);
+ } else if (!state.fbx_target_map.has(armature_id) && !fbx_skeleton_inst->fbx_node->has_model()) {
+ print_error("bones are not mapped to an armature node for armature id: " + itos(armature_id) + " bone: " + bone->bone_name);
+ // this means bone will be removed and not used, which is safe actually and no skeleton will be created.
+ }
+ }
+
+ // setup skeleton instances if required :)
+ for (Map<uint64_t, Ref<FBXSkeleton>>::Element *skeleton_node = state.skeleton_map.front(); skeleton_node; skeleton_node = skeleton_node->next()) {
+ Ref<FBXSkeleton> &skeleton = skeleton_node->value();
+ skeleton->init_skeleton(state);
+
+ ERR_CONTINUE_MSG(skeleton->fbx_node.is_null(), "invalid fbx target map, missing skeleton");
+ }
+
+ // This list is not populated
+ for (Map<uint64_t, Ref<FBXNode>>::Element *skin_mesh = state.MeshNodes.front(); skin_mesh; skin_mesh = skin_mesh->next()) {
+ }
+ }
+
+ // build godot node tree
+ if (state.fbx_node_list.size() > 0) {
+ for (List<Ref<FBXNode>>::Element *node_element = state.fbx_node_list.front();
+ node_element;
+ node_element = node_element->next()) {
+ Ref<FBXNode> fbx_node = node_element->get();
+ EditorSceneImporterMeshNode3D *mesh_node = nullptr;
+ Ref<FBXMeshData> mesh_data_precached;
+
+ // check for valid geometry
+ if (fbx_node->fbx_model == nullptr) {
+ print_error("[doc] fundamental flaw, submit bug immediately with full import log with verbose logging on");
+ } else {
+ const std::vector<const FBXDocParser::Geometry *> &geometry = fbx_node->fbx_model->GetGeometry();
+ for (const FBXDocParser::Geometry *mesh : geometry) {
+ print_verbose("[doc] [" + itos(mesh->ID()) + "] mesh: " + fbx_node->node_name);
+
+ if (mesh == nullptr)
+ continue;
+
+ const FBXDocParser::MeshGeometry *mesh_geometry = dynamic_cast<const FBXDocParser::MeshGeometry *>(mesh);
+ if (mesh_geometry) {
+ uint64_t mesh_id = mesh_geometry->ID();
+
+ // this data will pre-exist if vertex weight information is found
+ if (state.renderer_mesh_data.has(mesh_id)) {
+ mesh_data_precached = state.renderer_mesh_data[mesh_id];
+ } else {
+ mesh_data_precached.instance();
+ state.renderer_mesh_data.insert(mesh_id, mesh_data_precached);
+ }
+
+ mesh_data_precached->mesh_node = fbx_node;
+
+ // mesh node, mesh id
+ mesh_node = mesh_data_precached->create_fbx_mesh(state, mesh_geometry, fbx_node->fbx_model, (p_flags & IMPORT_USE_COMPRESSION) != 0);
+ if (!state.MeshNodes.has(mesh_id)) {
+ state.MeshNodes.insert(mesh_id, fbx_node);
+ }
+ }
+
+ const FBXDocParser::ShapeGeometry *shape_geometry = dynamic_cast<const FBXDocParser::ShapeGeometry *>(mesh);
+ if (shape_geometry != nullptr) {
+ print_verbose("[doc] valid shape geometry converted");
+ }
+ }
+ }
+
+ Ref<FBXSkeleton> node_skeleton = fbx_node->skeleton_node;
+
+ if (node_skeleton.is_valid()) {
+ Skeleton3D *skel = node_skeleton->skeleton;
+ fbx_node->godot_node = skel;
+ } else if (mesh_node == nullptr) {
+ fbx_node->godot_node = memnew(Node3D);
+ } else {
+ fbx_node->godot_node = mesh_node;
+ }
+
+ fbx_node->godot_node->set_name(fbx_node->node_name);
+
+ // assign parent if valid
+ if (fbx_node->fbx_parent.is_valid()) {
+ fbx_node->fbx_parent->godot_node->add_child(fbx_node->godot_node);
+ fbx_node->godot_node->set_owner(state.root_owner);
+ }
+
+ // Node Transform debug, set local xform data.
+ fbx_node->godot_node->set_transform(get_unscaled_transform(fbx_node->pivot_transform->LocalTransform, state.scale));
+
+ // populate our mesh node reference
+ if (mesh_node != nullptr && mesh_data_precached.is_valid()) {
+ mesh_data_precached->godot_mesh_instance = mesh_node;
+ }
+ }
+ }
+
+ for (Map<uint64_t, Ref<FBXMeshData>>::Element *mesh_data = state.renderer_mesh_data.front(); mesh_data; mesh_data = mesh_data->next()) {
+ const uint64_t mesh_id = mesh_data->key();
+ Ref<FBXMeshData> mesh = mesh_data->value();
+
+ const FBXDocParser::MeshGeometry *mesh_geometry = p_document->GetObject(mesh_id)->Get<FBXDocParser::MeshGeometry>();
+
+ ERR_CONTINUE_MSG(mesh->mesh_node.is_null(), "invalid mesh allocation");
+
+ const FBXDocParser::Skin *mesh_skin = mesh_geometry->DeformerSkin();
+
+ if (!mesh_skin) {
+ continue; // safe to continue
+ }
+
+ //
+ // Skin bone configuration
+ //
+
+ //
+ // Get Mesh Node Xform only
+ //
+ //ERR_CONTINUE_MSG(!state.fbx_target_map.has(mesh_id), "invalid xform for the skin pose: " + itos(mesh_id));
+ //Ref<FBXNode> mesh_node_xform_data = state.fbx_target_map[mesh_id];
+
+ if (!mesh_skin) {
+ continue; // not a deformer.
+ }
+
+ if (mesh_skin->Clusters().size() == 0) {
+ continue; // possibly buggy mesh
+ }
+
+ // Lookup skin or create it if it's not found.
+ Ref<Skin> skin;
+ if (!state.MeshSkins.has(mesh_id)) {
+ print_verbose("Created new skin");
+ skin.instance();
+ state.MeshSkins.insert(mesh_id, skin);
+ } else {
+ print_verbose("Grabbed skin");
+ skin = state.MeshSkins[mesh_id];
+ }
+
+ for (const FBXDocParser::Cluster *cluster : mesh_skin->Clusters()) {
+ // node or bone this cluster targets (in theory will only be a bone target)
+ uint64_t skin_target_id = cluster->TargetNode()->ID();
+
+ print_verbose("adding cluster [" + itos(cluster->ID()) + "] " + String(cluster->Name().c_str()) + " for target: [" + itos(skin_target_id) + "] " + String(cluster->TargetNode()->Name().c_str()));
+ ERR_CONTINUE_MSG(!state.fbx_bone_map.has(skin_target_id), "no bone found by that ID? locator");
+
+ const Ref<FBXBone> bone = state.fbx_bone_map[skin_target_id];
+ const Ref<FBXSkeleton> skeleton = bone->fbx_skeleton;
+ const Ref<FBXNode> skeleton_node = skeleton->fbx_node;
+
+ skin->add_named_bind(
+ bone->bone_name,
+ get_unscaled_transform(
+ skeleton_node->pivot_transform->GlobalTransform.affine_inverse() * cluster->TransformLink().affine_inverse(), state.scale));
+ }
+
+ print_verbose("cluster name / id: " + String(mesh_skin->Name().c_str()) + " [" + itos(mesh_skin->ID()) + "]");
+ print_verbose("skeleton has " + itos(state.fbx_bone_map.size()) + " binds");
+ print_verbose("fbx skin has " + itos(mesh_skin->Clusters().size()) + " binds");
+ }
+
+ // mesh data iteration for populating skeleton mapping
+ for (Map<uint64_t, Ref<FBXMeshData>>::Element *mesh_data = state.renderer_mesh_data.front(); mesh_data; mesh_data = mesh_data->next()) {
+ Ref<FBXMeshData> mesh = mesh_data->value();
+ const uint64_t mesh_id = mesh_data->key();
+ EditorSceneImporterMeshNode3D *mesh_instance = mesh->godot_mesh_instance;
+ const int mesh_weights = mesh->max_weight_count;
+ Ref<FBXSkeleton> skeleton;
+ const bool valid_armature = mesh->valid_armature_id;
+ const uint64_t armature = mesh->armature_id;
+
+ if (mesh_weights > 0) {
+ // this is a bug, it means the weights were found but the skeleton wasn't
+ ERR_CONTINUE_MSG(!valid_armature, "[doc] fbx armature is missing");
+ } else {
+ continue; // safe to continue not a bug just a normal mesh
+ }
+
+ if (state.skeleton_map.has(armature)) {
+ skeleton = state.skeleton_map[armature];
+ print_verbose("[doc] armature mesh to skeleton mapping has been allocated");
+ } else {
+ print_error("[doc] unable to find armature mapping");
+ }
+
+ ERR_CONTINUE_MSG(!mesh_instance, "[doc] invalid mesh mapping for skeleton assignment");
+ ERR_CONTINUE_MSG(skeleton.is_null(), "[doc] unable to resolve the correct skeleton but we have weights!");
+
+ mesh_instance->set_skeleton_path(mesh_instance->get_path_to(skeleton->skeleton));
+ print_verbose("[doc] allocated skeleton to mesh " + mesh_instance->get_name());
+
+ // do we have a mesh skin for this mesh
+ ERR_CONTINUE_MSG(!state.MeshSkins.has(mesh_id), "no skin found for mesh");
+
+ Ref<Skin> mesh_skin = state.MeshSkins[mesh_id];
+
+ ERR_CONTINUE_MSG(mesh_skin.is_null(), "invalid skin stored in map");
+ print_verbose("[doc] allocated skin to mesh " + mesh_instance->get_name());
+ mesh_instance->set_skin(mesh_skin);
+ }
+
+ // build skin and skeleton information
+ print_verbose("[doc] Skeleton3D Bone count: " + itos(state.fbx_bone_map.size()));
+ const FBXDocParser::FileGlobalSettings *FBXSettings = p_document->GlobalSettingsPtr();
+
+ // Configure constraints
+ // NOTE: constraints won't be added quite yet, we don't have a real need for them *yet*. (they can be supported later on)
+ // const std::vector<uint64_t> fbx_constraints = p_document->GetConstraintStackIDs();
+
+ // get the animation FPS
+ float fps_setting = ImportUtils::get_fbx_fps(FBXSettings);
+
+ // enable animation import, only if local animation is enabled
+ if (state.enable_animation_import && (p_flags & IMPORT_ANIMATION)) {
+ // document animation stack list - get by ID so we can unload any non used animation stack
+ const std::vector<uint64_t> animation_stack = p_document->GetAnimationStackIDs();
+
+ for (uint64_t anim_id : animation_stack) {
+ FBXDocParser::LazyObject *lazyObject = p_document->GetObject(anim_id);
+ const FBXDocParser::AnimationStack *stack = lazyObject->Get<FBXDocParser::AnimationStack>();
+
+ if (stack != nullptr) {
+ String animation_name = ImportUtils::FBXNodeToName(stack->Name());
+ print_verbose("Valid animation stack has been found: " + animation_name);
+ // ReferenceTime is the same for some animations?
+ // LocalStop time is the start and end time
+ float r_start = CONVERT_FBX_TIME(stack->ReferenceStart());
+ float r_stop = CONVERT_FBX_TIME(stack->ReferenceStop());
+ float start_time = CONVERT_FBX_TIME(stack->LocalStart());
+ float end_time = CONVERT_FBX_TIME(stack->LocalStop());
+ float duration = end_time - start_time;
+
+ print_verbose("r_start " + rtos(r_start) + ", r_stop " + rtos(r_stop));
+ print_verbose("start_time" + rtos(start_time) + " end_time " + rtos(end_time));
+ print_verbose("anim duration : " + rtos(duration));
+
+ // we can safely create the animation player
+ if (state.animation_player == nullptr) {
+ print_verbose("Creating animation player");
+ state.animation_player = memnew(AnimationPlayer);
+ state.root->add_child(state.animation_player);
+ state.animation_player->set_owner(state.root_owner);
+ }
+
+ Ref<Animation> animation;
+ animation.instance();
+ animation->set_name(animation_name);
+ animation->set_length(duration);
+
+ print_verbose("Animation length: " + rtos(animation->get_length()) + " seconds");
+
+ // i think assimp was duplicating things, this lets me know to just reference or ignore this to prevent duplicate information in tracks
+ // this would mean that we would be doing three times as much work per track if my theory is correct.
+ // this was not the case but this is a good sanity check for the animation handler from the document.
+ // it also lets us know if the FBX specification massively changes the animation system, in theory such a change would make this show
+ // an fbx specification error, so best keep it in
+ // the overhead is tiny.
+ Map<uint64_t, const FBXDocParser::AnimationCurve *> CheckForDuplication;
+
+ const std::vector<const FBXDocParser::AnimationLayer *> &layers = stack->Layers();
+ print_verbose("FBX Animation layers: " + itos(layers.size()));
+ for (const FBXDocParser::AnimationLayer *layer : layers) {
+ std::vector<const FBXDocParser::AnimationCurveNode *> node_list = layer->Nodes();
+ print_verbose("Layer: " + ImportUtils::FBXNodeToName(layer->Name()) + ", " + " AnimCurveNode count " + itos(node_list.size()));
+
+ // first thing to do here is that i need to first get the animcurvenode to a Vector3
+ // we now need to put this into the track information for godot.
+ // to do this we need to know which track is what?
+
+ // target id, [ track name, [time index, vector] ]
+ // new map needs to be [ track name, keyframe_data ]
+ Map<uint64_t, Map<StringName, FBXTrack>> AnimCurveNodes;
+
+ // struct AnimTrack {
+ // // Animation track can be
+ // // visible, T, R, S
+ // Map<StringName, Map<uint64_t, Vector3> > animation_track;
+ // };
+
+ // Map<uint64_t, AnimTrack> AnimCurveNodes;
+
+ // so really, what does this mean to make an animtion track.
+ // we need to know what object the curves are for.
+ // we need the target ID and the target name for the track reduction.
+
+ FBXDocParser::Model::RotOrder quat_rotation_order = FBXDocParser::Model::RotOrder_EulerXYZ;
+
+ // T:: R:: S:: Visible:: Custom::
+ for (const FBXDocParser::AnimationCurveNode *curve_node : node_list) {
+ // when Curves() is called the curves are actually read, we could replace this with our own ProcessDomConnection code here if required.
+ // We may need to do this but ideally we use Curves
+ // note: when you call this there might be a delay in opening it
+ // uses mutable type to 'cache' the response until the AnimationCurveNode is cleaned up.
+ std::map<std::string, const FBXDocParser::AnimationCurve *> curves = curve_node->Curves();
+ const FBXDocParser::Object *object = curve_node->Target();
+ const FBXDocParser::Model *target = curve_node->TargetAsModel();
+ if (target == nullptr) {
+ if (object != nullptr) {
+ print_error("[doc] warning failed to find a target Model for curve: " + String(object->Name().c_str()));
+ } else {
+ //print_error("[doc] failed to resolve object");
+ continue;
+ }
+
+ continue;
+ } else {
+ //print_verbose("[doc] applied rotation order: " + itos(target->RotationOrder()));
+ quat_rotation_order = target->RotationOrder();
+ }
+
+ uint64_t target_id = target->ID();
+ String target_name = ImportUtils::FBXNodeToName(target->Name());
+
+ const FBXDocParser::PropertyTable *properties = curve_node->Props();
+ bool got_x = false, got_y = false, got_z = false;
+ float offset_x = FBXDocParser::PropertyGet<float>(properties, "d|X", got_x);
+ float offset_y = FBXDocParser::PropertyGet<float>(properties, "d|Y", got_y);
+ float offset_z = FBXDocParser::PropertyGet<float>(properties, "d|Z", got_z);
+
+ String curve_node_name = ImportUtils::FBXNodeToName(curve_node->Name());
+
+ // Reduce all curves for this node into a single container
+ // T, R, S is what we expect, although other tracks are possible
+ // like for example visibility tracks.
+
+ // We are not ordered here, we don't care about ordering, this happens automagically by godot when we insert with the
+ // key time :), so order is unimportant because the insertion will happen at a time index
+ // good to know: we do not need a list of these in another format :)
+ //Map<String, Vector<const Assimp::FBX::AnimationCurve *> > unordered_track;
+
+ // T
+ // R
+ // S
+ // Map[String, List<VECTOR>]
+
+ // So this is a reduction of the animation curve nodes
+ // We build this as a lookup, this is essentially our 'animation track'
+ //AnimCurveNodes.insert(curve_node_name, Map<uint64_t, Vector3>());
+
+ // create the animation curve information with the target id
+ // so the point of this makes a track with the name "T" for example
+ // the target ID is also set here, this means we don't need to do anything extra when we are in the 'create all animation tracks' step
+ FBXTrack &keyframe_map = AnimCurveNodes[target_id][StringName(curve_node_name)];
+
+ if (got_x && got_y && got_z) {
+ Vector3 default_value = Vector3(offset_x, offset_y, offset_z);
+ keyframe_map.default_value = default_value;
+ keyframe_map.has_default = true;
+ //print_verbose("track name: " + curve_node_name);
+ //print_verbose("xyz default: " + default_value);
+ }
+ // target id, [ track name, [time index, vector] ]
+ // Map<uint64_t, Map<StringName, Map<uint64_t, Vector3> > > AnimCurveNodes;
+
+ // we probably need the target id here.
+ // so map[uint64_t map]...
+ // Map<uint64_t, Vector3D> translation_keys, rotation_keys, scale_keys;
+
+ // extra const required by C++11 colon/Range operator
+ // note: do not use C++17 syntax here for dicts.
+ // this is banned in Godot.
+ for (std::pair<const std::string, const FBXDocParser::AnimationCurve *> &kvp : curves) {
+ const String curve_element = ImportUtils::FBXNodeToName(kvp.first);
+ const FBXDocParser::AnimationCurve *curve = kvp.second;
+ String curve_name = ImportUtils::FBXNodeToName(curve->Name());
+ uint64_t curve_id = curve->ID();
+
+ if (CheckForDuplication.has(curve_id)) {
+ print_error("(FBX spec changed?) We found a duplicate curve being used for an alternative node - report to godot issue tracker");
+ } else {
+ CheckForDuplication.insert(curve_id, curve);
+ }
+
+ // FBX has no name for AnimCurveNode::, most of the time, not seen any with valid name here.
+ const std::map<int64_t, float> &track_time = curve->GetValueTimeTrack();
+
+ if (track_time.size() > 0) {
+ for (std::pair<int64_t, float> keyframe : track_time) {
+ if (curve_element == "d|X") {
+ keyframe_map.keyframes[keyframe.first].x = keyframe.second;
+ } else if (curve_element == "d|Y") {
+ keyframe_map.keyframes[keyframe.first].y = keyframe.second;
+ } else if (curve_element == "d|Z") {
+ keyframe_map.keyframes[keyframe.first].z = keyframe.second;
+ } else {
+ //print_error("FBX Unsupported element: " + curve_element);
+ }
+
+ //print_verbose("[" + itos(target_id) + "] Keyframe added: " + itos(keyframe_map.size()));
+
+ //print_verbose("Keyframe t:" + rtos(animation_track_time) + " v: " + rtos(keyframe.second));
+ }
+ }
+ }
+ }
+
+ // Map<uint64_t, Map<StringName, Map<uint64_t, Vector3> > > AnimCurveNodes;
+ // add this animation track here
+
+ // target id, [ track name, [time index, vector] ]
+ //std::map<uint64_t, std::map<StringName, FBXTrack > > AnimCurveNodes;
+ for (Map<uint64_t, Map<StringName, FBXTrack>>::Element *track = AnimCurveNodes.front(); track; track = track->next()) {
+ // 5 tracks
+ // current track index
+ // track count is 5
+ // track count is 5.
+ // next track id is 5.
+ const uint64_t target_id = track->key();
+ int track_idx = animation->add_track(Animation::TYPE_TRANSFORM);
+
+ // animation->track_set_path(track_idx, node_path);
+ // animation->track_set_path(track_idx, node_path);
+ Ref<FBXBone> bone;
+
+ // note we must not run the below code if the entry doesn't exist, it will create dummy entries which is very bad.
+ // remember that state.fbx_bone_map[target_id] will create a new entry EVEN if you only read.
+ // this would break node animation targets, so if you change this be warned. :)
+ if (state.fbx_bone_map.has(target_id)) {
+ bone = state.fbx_bone_map[target_id];
+ }
+
+ Transform target_transform;
+
+ if (state.fbx_target_map.has(target_id)) {
+ Ref<FBXNode> node_ref = state.fbx_target_map[target_id];
+ target_transform = node_ref->pivot_transform->GlobalTransform;
+ //print_verbose("[doc] allocated animation node transform");
+ }
+
+ //int size_targets = state.fbx_target_map.size();
+ //print_verbose("Target ID map: " + itos(size_targets));
+ //print_verbose("[doc] debug bone map size: " + itos(state.fbx_bone_map.size()));
+
+ // if this is a skeleton mapped track we can just set the path for the track.
+ // todo: implement node paths here at some
+ if (state.fbx_bone_map.size() > 0 && state.fbx_bone_map.has(target_id)) {
+ if (bone->fbx_skeleton.is_valid() && bone.is_valid()) {
+ Ref<FBXSkeleton> fbx_skeleton = bone->fbx_skeleton;
+ String bone_path = state.root->get_path_to(fbx_skeleton->skeleton);
+ bone_path += ":" + fbx_skeleton->skeleton->get_bone_name(bone->godot_bone_id);
+ print_verbose("[doc] track bone path: " + bone_path);
+ NodePath path = bone_path;
+ animation->track_set_path(track_idx, path);
+ }
+ } else if (state.fbx_target_map.has(target_id)) {
+ //print_verbose("[doc] we have a valid target for a node animation");
+ Ref<FBXNode> target_node = state.fbx_target_map[target_id];
+ if (target_node.is_valid() && target_node->godot_node != nullptr) {
+ String node_path = state.root->get_path_to(target_node->godot_node);
+ NodePath path = node_path;
+ animation->track_set_path(track_idx, path);
+ //print_verbose("[doc] node animation path: " + node_path);
+ }
+ } else {
+ // note: this could actually be unsafe this means we should be careful about continuing here, if we see bizzare effects later we should disable this.
+ // I am not sure if this is unsafe or not, testing will tell us this.
+ print_error("[doc] invalid fbx target detected for this track");
+ continue;
+ }
+
+ // everything in FBX and Maya is a node therefore if this happens something is seriously broken.
+ if (!state.fbx_target_map.has(target_id)) {
+ print_error("unable to resolve this to an FBX object.");
+ continue;
+ }
+
+ Ref<FBXNode> target_node = state.fbx_target_map[target_id];
+ const FBXDocParser::Model *model = target_node->fbx_model;
+ const FBXDocParser::PropertyTable *props = model->Props();
+
+ Map<StringName, FBXTrack> &track_data = track->value();
+ FBXTrack &translation_keys = track_data[StringName("T")];
+ FBXTrack &rotation_keys = track_data[StringName("R")];
+ FBXTrack &scale_keys = track_data[StringName("S")];
+
+ double increment = 1.0f / fps_setting;
+ double time = 0.0f;
+
+ bool last = false;
+
+ Vector<Vector3> pos_values;
+ Vector<float> pos_times;
+ Vector<Vector3> scale_values;
+ Vector<float> scale_times;
+ Vector<Quat> rot_values;
+ Vector<float> rot_times;
+
+ double max_duration = 0;
+ double anim_length = animation->get_length();
+
+ for (std::pair<int64_t, Vector3> position_key : translation_keys.keyframes) {
+ pos_values.push_back(position_key.second * state.scale);
+ double animation_track_time = CONVERT_FBX_TIME(position_key.first);
+
+ if (animation_track_time > max_duration) {
+ max_duration = animation_track_time;
+ }
+
+ //print_verbose("pos keyframe: t:" + rtos(animation_track_time) + " value " + position_key.second);
+ pos_times.push_back(animation_track_time);
+ }
+
+ for (std::pair<int64_t, Vector3> scale_key : scale_keys.keyframes) {
+ scale_values.push_back(scale_key.second);
+ double animation_track_time = CONVERT_FBX_TIME(scale_key.first);
+
+ if (animation_track_time > max_duration) {
+ max_duration = animation_track_time;
+ }
+ //print_verbose("scale keyframe t:" + rtos(animation_track_time));
+ scale_times.push_back(animation_track_time);
+ }
+
+ //
+ // Pre and Post keyframe rotation handler
+ // -- Required because Maya and Autodesk <3 the pain when it comes to implementing animation code! enjoy <3
+
+ bool got_pre = false;
+ bool got_post = false;
+
+ Quat post_rotation;
+ Quat pre_rotation;
+
+ // Rotation matrix
+ const Vector3 &PreRotation = FBXDocParser::PropertyGet<Vector3>(props, "PreRotation", got_pre);
+ const Vector3 &PostRotation = FBXDocParser::PropertyGet<Vector3>(props, "PostRotation", got_post);
+
+ FBXDocParser::Model::RotOrder rot_order = model->RotationOrder();
+ if (got_pre) {
+ pre_rotation = ImportUtils::EulerToQuaternion(rot_order, ImportUtils::deg2rad(PreRotation));
+ }
+ if (got_post) {
+ post_rotation = ImportUtils::EulerToQuaternion(rot_order, ImportUtils::deg2rad(PostRotation));
+ }
+
+ Quat lastQuat = Quat();
+
+ for (std::pair<int64_t, Vector3> rotation_key : rotation_keys.keyframes) {
+ double animation_track_time = CONVERT_FBX_TIME(rotation_key.first);
+
+ //print_verbose("euler rotation key: " + rotation_key.second);
+ Quat rot_key_value = ImportUtils::EulerToQuaternion(quat_rotation_order, ImportUtils::deg2rad(rotation_key.second));
+
+ if (lastQuat != Quat() && rot_key_value.dot(lastQuat) < 0) {
+ rot_key_value.x = -rot_key_value.x;
+ rot_key_value.y = -rot_key_value.y;
+ rot_key_value.z = -rot_key_value.z;
+ rot_key_value.w = -rot_key_value.w;
+ }
+ // pre_post rotation possibly could fix orientation
+ Quat final_rotation = pre_rotation * rot_key_value * post_rotation;
+
+ lastQuat = final_rotation;
+
+ if (animation_track_time > max_duration) {
+ max_duration = animation_track_time;
+ }
+
+ rot_values.push_back(final_rotation);
+ rot_times.push_back(animation_track_time);
+ }
+
+ bool valid_rest = false;
+ Transform bone_rest;
+ int skeleton_bone = -1;
+ if (state.fbx_bone_map.has(target_id)) {
+ if (bone.is_valid() && bone->fbx_skeleton.is_valid()) {
+ skeleton_bone = bone->godot_bone_id;
+ if (skeleton_bone >= 0) {
+ bone_rest = bone->fbx_skeleton->skeleton->get_bone_rest(skeleton_bone);
+ valid_rest = true;
+ }
+ }
+
+ if (!valid_rest) {
+ print_verbose("invalid rest!");
+ }
+ }
+
+ const Vector3 def_pos = translation_keys.has_default ? (translation_keys.default_value * state.scale) : bone_rest.origin;
+ const Quat def_rot = rotation_keys.has_default ? ImportUtils::EulerToQuaternion(quat_rotation_order, ImportUtils::deg2rad(rotation_keys.default_value)) : bone_rest.basis.get_rotation_quat();
+ const Vector3 def_scale = scale_keys.has_default ? scale_keys.default_value : bone_rest.basis.get_scale();
+ print_verbose("track defaults: p(" + def_pos + ") s(" + def_scale + ") r(" + def_rot + ")");
+
+ while (true) {
+ Vector3 pos = def_pos;
+ Quat rot = def_rot;
+ Vector3 scale = def_scale;
+
+ if (pos_values.size()) {
+ pos = _interpolate_track<Vector3>(pos_times, pos_values, time,
+ AssetImportAnimation::INTERP_LINEAR);
+ }
+
+ if (rot_values.size()) {
+ rot = _interpolate_track<Quat>(rot_times, rot_values, time,
+ AssetImportAnimation::INTERP_LINEAR);
+ }
+
+ if (scale_values.size()) {
+ scale = _interpolate_track<Vector3>(scale_times, scale_values, time,
+ AssetImportAnimation::INTERP_LINEAR);
+ }
+
+ // node animations must also include pivots
+ if (skeleton_bone >= 0) {
+ Transform xform = Transform();
+ xform.basis.set_quat_scale(rot, scale);
+ xform.origin = pos;
+ const Transform t = bone_rest.affine_inverse() * xform;
+
+ // populate this again
+ rot = t.basis.get_rotation_quat();
+ rot.normalize();
+ scale = t.basis.get_scale();
+ pos = t.origin;
+ }
+
+ animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
+
+ if (last) {
+ break;
+ }
+
+ time += increment;
+ if (time > anim_length) {
+ last = true;
+ time = anim_length;
+ break;
+ }
+ }
+ }
+ }
+ state.animation_player->add_animation(animation_name, animation);
+ }
+ }
+
+ // AnimStack elements contain start stop time and name of animation
+ // AnimLayer is the current active layer of the animation (multiple layers can be active we only support 1)
+ // AnimCurveNode has a OP link back to the model which is the real node.
+ // AnimCurveNode has a direct link to AnimationCurve (of which it may have more than one)
+
+ // Store animation stack in list
+ // iterate over all AnimStacks like the cache node algorithm recursively
+ // this can then be used with ProcessDomConnection<> to link from
+ // AnimStack:: <-- (OO) --> AnimLayer:: <-- (OO) --> AnimCurveNode:: (which can OP resolve) to Model::
+ }
+
+ //
+ // Cleanup operations - explicit to prevent errors on shutdown - found that ref to ref does behave badly sometimes.
+ //
+
+ state.renderer_mesh_data.clear();
+ state.MeshSkins.clear();
+ state.fbx_target_map.clear();
+ state.fbx_node_list.clear();
+
+ for (Map<uint64_t, Ref<FBXBone>>::Element *element = state.fbx_bone_map.front(); element; element = element->next()) {
+ Ref<FBXBone> bone = element->value();
+ bone->parent_bone.unref();
+ bone->node.unref();
+ bone->fbx_skeleton.unref();
+ }
+
+ for (Map<uint64_t, Ref<FBXSkeleton>>::Element *element = state.skeleton_map.front(); element; element = element->next()) {
+ Ref<FBXSkeleton> skel = element->value();
+ skel->fbx_node.unref();
+ skel->skeleton_bones.clear();
+ }
+
+ state.fbx_bone_map.clear();
+ state.skeleton_map.clear();
+ state.fbx_root_node.unref();
+
+ return scene_root;
+}
+
+void EditorSceneImporterFBX::BuildDocumentBones(Ref<FBXBone> p_parent_bone,
+ ImportState &state, const FBXDocParser::Document *p_doc,
+ uint64_t p_id) {
+ const std::vector<const FBXDocParser::Connection *> &conns = p_doc->GetConnectionsByDestinationSequenced(p_id, "Model");
+ // FBX can do an join like this
+ // Model -> SubDeformer (bone) -> Deformer (skin pose)
+ // This is important because we need to somehow link skin back to bone id in skeleton :)
+ // The rules are:
+ // A subdeformer will exist if 'limbnode' class tag present
+ // The subdeformer will not necessarily have a deformer as joints do not have one
+ for (const FBXDocParser::Connection *con : conns) {
+ // goto: bone creation
+ //print_verbose("con: " + String(con->PropertyName().c_str()));
+
+ // ignore object-property links we want the object to object links nothing else
+ if (con->PropertyName().length()) {
+ continue;
+ }
+
+ // convert connection source object into Object base class
+ const FBXDocParser::Object *const object = con->SourceObject();
+
+ if (nullptr == object) {
+ print_verbose("failed to convert source object for Model link");
+ continue;
+ }
+
+ // FBX Model::Cube, Model::Bone001, etc elements
+ // This detects if we can cast the object into this model structure.
+ const FBXDocParser::Model *const model = dynamic_cast<const FBXDocParser::Model *>(object);
+
+ // declare our bone element reference (invalid, unless we create a bone in this step)
+ // this lets us pass valid armature information into children objects and this is why we moved this up here
+ // previously this was created .instanced() on the same line.
+ Ref<FBXBone> bone_element;
+
+ if (model != nullptr) {
+ // model marked with limb node / casted.
+ const FBXDocParser::ModelLimbNode *const limb_node = dynamic_cast<const FBXDocParser::ModelLimbNode *>(model);
+ if (limb_node != nullptr) {
+ // Write bone into bone list for FBX
+
+ ERR_FAIL_COND_MSG(state.fbx_bone_map.has(limb_node->ID()), "[serious] duplicate LimbNode detected");
+
+ bool parent_is_bone = state.fbx_bone_map.find(p_id);
+ bone_element.instance();
+
+ // used to build the bone hierarchy in the skeleton
+ bone_element->parent_bone_id = parent_is_bone ? p_id : 0;
+ bone_element->valid_parent = parent_is_bone;
+ bone_element->limb_node = limb_node;
+
+ // parent is a node and this is the first bone
+ if (!parent_is_bone) {
+ uint64_t armature_id = p_id;
+ bone_element->valid_armature_id = true;
+ bone_element->armature_id = armature_id;
+ print_verbose("[doc] valid armature has been configured for first child: " + itos(armature_id));
+ } else if (p_parent_bone.is_valid()) {
+ if (p_parent_bone->valid_armature_id) {
+ bone_element->valid_armature_id = true;
+ bone_element->armature_id = p_parent_bone->armature_id;
+ print_verbose("[doc] bone has valid armature id:" + itos(bone_element->armature_id));
+ } else {
+ print_error("[doc] unassigned armature id: " + String(limb_node->Name().c_str()));
+ }
+ } else {
+ print_error("[doc] error is this a bone? " + String(limb_node->Name().c_str()));
+ }
+
+ if (!parent_is_bone) {
+ print_verbose("[doc] Root bone: " + bone_element->bone_name);
+ }
+
+ uint64_t limb_id = limb_node->ID();
+ bone_element->bone_id = limb_id;
+ bone_element->bone_name = ImportUtils::FBXNodeToName(model->Name());
+ bone_element->parent_bone = p_parent_bone;
+
+ // insert limb by ID into list.
+ state.fbx_bone_map.insert(limb_node->ID(), bone_element);
+ }
+
+ // recursion call - child nodes
+ BuildDocumentBones(bone_element, state, p_doc, model->ID());
+ }
+ }
+}
+
+void EditorSceneImporterFBX::BuildDocumentNodes(
+ Ref<PivotTransform> parent_transform,
+ ImportState &state,
+ const FBXDocParser::Document *p_doc,
+ uint64_t id,
+ Ref<FBXNode> parent_node) {
+ // tree
+ // here we get the node 0 on the root by default
+ const std::vector<const FBXDocParser::Connection *> &conns = p_doc->GetConnectionsByDestinationSequenced(id, "Model");
+
+ // branch
+ for (const FBXDocParser::Connection *con : conns) {
+ // ignore object-property links
+ if (con->PropertyName().length()) {
+ // really important we document why this is ignored.
+ print_verbose("ignoring property link - no docs on why this is ignored");
+ continue;
+ }
+
+ // convert connection source object into Object base class
+ // Source objects can exist with 'null connections' this means that we only for sure know the source exists.
+ const FBXDocParser::Object *const source_object = con->SourceObject();
+
+ if (nullptr == source_object) {
+ print_verbose("failed to convert source object for Model link");
+ continue;
+ }
+
+ // FBX Model::Cube, Model::Bone001, etc elements
+ // This detects if we can cast the object into this model structure.
+ const FBXDocParser::Model *const model = dynamic_cast<const FBXDocParser::Model *>(source_object);
+ // model is the current node
+ if (nullptr != model) {
+ uint64_t current_node_id = model->ID();
+
+ Ref<FBXNode> new_node;
+ new_node.instance();
+ new_node->current_node_id = current_node_id;
+ new_node->node_name = ImportUtils::FBXNodeToName(model->Name());
+
+ Ref<PivotTransform> fbx_transform;
+ fbx_transform.instance();
+ fbx_transform->set_parent(parent_transform);
+ fbx_transform->set_model(model);
+ fbx_transform->debug_pivot_xform("name: " + new_node->node_name);
+ fbx_transform->Execute();
+
+ new_node->set_pivot_transform(fbx_transform);
+
+ // check if this node is a bone
+ if (state.fbx_bone_map.has(current_node_id)) {
+ Ref<FBXBone> bone = state.fbx_bone_map[current_node_id];
+ if (bone.is_valid()) {
+ bone->set_node(new_node);
+ print_verbose("allocated bone data: " + bone->bone_name);
+ }
+ }
+
+ // set the model, we can't just assign this safely
+ new_node->set_model(model);
+
+ if (parent_node.is_valid()) {
+ new_node->set_parent(parent_node);
+ } else {
+ new_node->set_parent(state.fbx_root_node);
+ }
+
+ CRASH_COND_MSG(new_node->pivot_transform.is_null(), "invalid fbx target map pivot transform [serious]");
+
+ // populate lookup tables with references
+ // [fbx_node_id, fbx_node]
+
+ state.fbx_node_list.push_back(new_node);
+ if (!state.fbx_target_map.has(new_node->current_node_id)) {
+ state.fbx_target_map[new_node->current_node_id] = new_node;
+ }
+
+ // print node name
+ print_verbose("[doc] new node " + new_node->node_name);
+
+ // sub branches
+ BuildDocumentNodes(new_node->pivot_transform, state, p_doc, current_node_id, new_node);
+ }
+ }
+}
diff --git a/modules/fbx/editor_scene_importer_fbx.h b/modules/fbx/editor_scene_importer_fbx.h
new file mode 100644
index 0000000000..39f8648b0f
--- /dev/null
+++ b/modules/fbx/editor_scene_importer_fbx.h
@@ -0,0 +1,135 @@
+/*************************************************************************/
+/* editor_scene_importer_fbx.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 EDITOR_SCENE_IMPORTER_FBX_H
+#define EDITOR_SCENE_IMPORTER_FBX_H
+
+#ifdef TOOLS_ENABLED
+
+#include "data/import_state.h"
+#include "tools/import_utils.h"
+
+#include "core/core_bind.h"
+#include "core/io/resource_importer.h"
+#include "core/string/ustring.h"
+#include "core/templates/local_vector.h"
+#include "core/templates/vector.h"
+#include "core/variant/dictionary.h"
+#include "editor/import/resource_importer_scene.h"
+#include "editor/project_settings_editor.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/3d/skeleton_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/animation.h"
+#include "scene/resources/surface_tool.h"
+
+#include "fbx_parser/FBXDocument.h"
+#include "fbx_parser/FBXImportSettings.h"
+#include "fbx_parser/FBXMeshGeometry.h"
+#include "fbx_parser/FBXUtil.h"
+
+#define CONVERT_FBX_TIME(time) static_cast<double>(time) / 46186158000LL
+
+class EditorSceneImporterFBX : public EditorSceneImporter {
+private:
+ GDCLASS(EditorSceneImporterFBX, EditorSceneImporter);
+
+ struct AssetImportAnimation {
+ enum Interpolation {
+ INTERP_LINEAR,
+ INTERP_STEP,
+ INTERP_CATMULLROMSPLINE,
+ INTERP_CUBIC_SPLINE
+ };
+ };
+
+ // ------------------------------------------------------------------------------------------------
+ template <typename T>
+ const T *ProcessDOMConnection(
+ const FBXDocParser::Document *doc,
+ uint64_t current_element,
+ bool reverse_lookup = false) {
+ const std::vector<const FBXDocParser::Connection *> &conns = reverse_lookup ? doc->GetConnectionsByDestinationSequenced(current_element) : doc->GetConnectionsBySourceSequenced(current_element);
+ //print_verbose("[doc] looking for " + String(element_to_find));
+ // using the temp pattern here so we can debug before it returns
+ // in some cases we return too early, with 'deformer object base class' in wrong place
+ // in assimp this means we can accidentally return too early...
+ const T *return_obj = nullptr;
+
+ for (const FBXDocParser::Connection *con : conns) {
+ const FBXDocParser::Object *source_object = con->SourceObject();
+ const FBXDocParser::Object *dest_object = con->DestinationObject();
+ if (source_object && dest_object != nullptr) {
+ //print_verbose("[doc] connection name: " + String(source_object->Name().c_str()) + ", dest: " + String(dest_object->Name().c_str()));
+ const T *temp = dynamic_cast<const T *>(reverse_lookup ? source_object : dest_object);
+ if (temp) {
+ return_obj = temp;
+ }
+ }
+ }
+
+ if (return_obj != nullptr) {
+ //print_verbose("[doc] returned valid element");
+ //print_verbose("Found object for bone");
+ return return_obj;
+ }
+
+ // safe to return nothing, need to use nullptr here as nullptr is used internally for FBX document.
+ return nullptr;
+ }
+
+ void BuildDocumentBones(Ref<FBXBone> p_parent_bone,
+ ImportState &state, const FBXDocParser::Document *p_doc,
+ uint64_t p_id);
+
+ void BuildDocumentNodes(Ref<PivotTransform> parent_transform, ImportState &state, const FBXDocParser::Document *doc, uint64_t id, Ref<FBXNode> fbx_parent);
+
+ Node3D *_generate_scene(const String &p_path, const FBXDocParser::Document *p_document,
+ const uint32_t p_flags,
+ int p_bake_fps,
+ const int32_t p_max_bone_weights,
+ bool p_is_blender_fbx);
+
+ template <class T>
+ T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, AssetImportAnimation::Interpolation p_interp);
+ void _register_project_setting_import(const String generic, const String import_setting_string, const Vector<String> &exts, List<String> *r_extensions, const bool p_enabled) const;
+
+public:
+ EditorSceneImporterFBX() {}
+ ~EditorSceneImporterFBX() {}
+
+ virtual void get_extensions(List<String> *r_extensions) const override;
+ virtual uint32_t get_import_flags() const override;
+ virtual Node3D *import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = NULL) override;
+};
+
+#endif // TOOLS_ENABLED
+#endif // EDITOR_SCENE_IMPORTER_FBX_H
diff --git a/modules/fbx/fbx_parser/ByteSwapper.h b/modules/fbx/fbx_parser/ByteSwapper.h
new file mode 100644
index 0000000000..f759c9117c
--- /dev/null
+++ b/modules/fbx/fbx_parser/ByteSwapper.h
@@ -0,0 +1,282 @@
+/*************************************************************************/
+/* ByteSwapper.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2020, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file Helper class tp perform various byte oder swappings
+ (e.g. little to big endian) */
+#ifndef BYTE_SWAPPER_H
+#define BYTE_SWAPPER_H
+
+#include <stdint.h>
+#include <algorithm>
+#include <locale>
+
+namespace FBXDocParser {
+// --------------------------------------------------------------------------------------
+/** Defines some useful byte order swap routines.
+ *
+ * This is required to read big-endian model formats on little-endian machines,
+ * and vice versa. Direct use of this class is DEPRECATED. Use #StreamReader instead. */
+// --------------------------------------------------------------------------------------
+class ByteSwap {
+ ByteSwap() {}
+
+public:
+ // ----------------------------------------------------------------------
+ /** Swap two bytes of data
+ * @param[inout] _szOut A void* to save the reintcasts for the caller. */
+ static inline void Swap2(void *_szOut) {
+ uint8_t *const szOut = reinterpret_cast<uint8_t *>(_szOut);
+ std::swap(szOut[0], szOut[1]);
+ }
+
+ // ----------------------------------------------------------------------
+ /** Swap four bytes of data
+ * @param[inout] _szOut A void* to save the reintcasts for the caller. */
+ static inline void Swap4(void *_szOut) {
+ uint8_t *const szOut = reinterpret_cast<uint8_t *>(_szOut);
+ std::swap(szOut[0], szOut[3]);
+ std::swap(szOut[1], szOut[2]);
+ }
+
+ // ----------------------------------------------------------------------
+ /** Swap eight bytes of data
+ * @param[inout] _szOut A void* to save the reintcasts for the caller. */
+ static inline void Swap8(void *_szOut) {
+ uint8_t *const szOut = reinterpret_cast<uint8_t *>(_szOut);
+ std::swap(szOut[0], szOut[7]);
+ std::swap(szOut[1], szOut[6]);
+ std::swap(szOut[2], szOut[5]);
+ std::swap(szOut[3], szOut[4]);
+ }
+
+ // ----------------------------------------------------------------------
+ /** ByteSwap a float. Not a joke.
+ * @param[inout] fOut ehm. .. */
+ static inline void Swap(float *fOut) {
+ Swap4(fOut);
+ }
+
+ // ----------------------------------------------------------------------
+ /** ByteSwap a double. Not a joke.
+ * @param[inout] fOut ehm. .. */
+ static inline void Swap(double *fOut) {
+ Swap8(fOut);
+ }
+
+ // ----------------------------------------------------------------------
+ /** ByteSwap an int16t. Not a joke.
+ * @param[inout] fOut ehm. .. */
+ static inline void Swap(int16_t *fOut) {
+ Swap2(fOut);
+ }
+
+ static inline void Swap(uint16_t *fOut) {
+ Swap2(fOut);
+ }
+
+ // ----------------------------------------------------------------------
+ /** ByteSwap an int32t. Not a joke.
+ * @param[inout] fOut ehm. .. */
+ static inline void Swap(int32_t *fOut) {
+ Swap4(fOut);
+ }
+
+ static inline void Swap(uint32_t *fOut) {
+ Swap4(fOut);
+ }
+
+ // ----------------------------------------------------------------------
+ /** ByteSwap an int64t. Not a joke.
+ * @param[inout] fOut ehm. .. */
+ static inline void Swap(int64_t *fOut) {
+ Swap8(fOut);
+ }
+
+ static inline void Swap(uint64_t *fOut) {
+ Swap8(fOut);
+ }
+
+ // ----------------------------------------------------------------------
+ //! Templatized ByteSwap
+ //! \returns param tOut as swapped
+ template <typename Type>
+ static inline Type Swapped(Type tOut) {
+ return _swapper<Type, sizeof(Type)>()(tOut);
+ }
+
+private:
+ template <typename T, size_t size>
+ struct _swapper;
+};
+
+template <typename T>
+struct ByteSwap::_swapper<T, 2> {
+ T operator()(T tOut) {
+ Swap2(&tOut);
+ return tOut;
+ }
+};
+
+template <typename T>
+struct ByteSwap::_swapper<T, 4> {
+ T operator()(T tOut) {
+ Swap4(&tOut);
+ return tOut;
+ }
+};
+
+template <typename T>
+struct ByteSwap::_swapper<T, 8> {
+ T operator()(T tOut) {
+ Swap8(&tOut);
+ return tOut;
+ }
+};
+
+// --------------------------------------------------------------------------------------
+// ByteSwap macros for BigEndian/LittleEndian support
+// --------------------------------------------------------------------------------------
+#if (defined AI_BUILD_BIG_ENDIAN)
+#define AI_LE(t) (t)
+#define AI_BE(t) ByteSwap::Swapped(t)
+#define AI_LSWAP2(p)
+#define AI_LSWAP4(p)
+#define AI_LSWAP8(p)
+#define AI_LSWAP2P(p)
+#define AI_LSWAP4P(p)
+#define AI_LSWAP8P(p)
+#define LE_NCONST const
+#define AI_SWAP2(p) ByteSwap::Swap2(&(p))
+#define AI_SWAP4(p) ByteSwap::Swap4(&(p))
+#define AI_SWAP8(p) ByteSwap::Swap8(&(p))
+#define AI_SWAP2P(p) ByteSwap::Swap2((p))
+#define AI_SWAP4P(p) ByteSwap::Swap4((p))
+#define AI_SWAP8P(p) ByteSwap::Swap8((p))
+#define BE_NCONST
+#else
+#define AI_BE(t) (t)
+#define AI_LE(t) ByteSwap::Swapped(t)
+#define AI_SWAP2(p)
+#define AI_SWAP4(p)
+#define AI_SWAP8(p)
+#define AI_SWAP2P(p)
+#define AI_SWAP4P(p)
+#define AI_SWAP8P(p)
+#define BE_NCONST const
+#define AI_LSWAP2(p) ByteSwap::Swap2(&(p))
+#define AI_LSWAP4(p) ByteSwap::Swap4(&(p))
+#define AI_LSWAP8(p) ByteSwap::Swap8(&(p))
+#define AI_LSWAP2P(p) ByteSwap::Swap2((p))
+#define AI_LSWAP4P(p) ByteSwap::Swap4((p))
+#define AI_LSWAP8P(p) ByteSwap::Swap8((p))
+#define LE_NCONST
+#endif
+
+namespace Intern {
+
+// --------------------------------------------------------------------------------------------
+template <typename T, bool doit>
+struct ByteSwapper {
+ void operator()(T *inout) {
+ ByteSwap::Swap(inout);
+ }
+};
+
+template <typename T>
+struct ByteSwapper<T, false> {
+ void operator()(T *) {
+ }
+};
+
+// --------------------------------------------------------------------------------------------
+template <bool SwapEndianess, typename T, bool RuntimeSwitch>
+struct Getter {
+ void operator()(T *inout, bool le) {
+ le = !le;
+ if (le) {
+ ByteSwapper<T, (sizeof(T) > 1 ? true : false)>()(inout);
+ } else
+ ByteSwapper<T, false>()(inout);
+ }
+};
+
+template <bool SwapEndianess, typename T>
+struct Getter<SwapEndianess, T, false> {
+ void operator()(T *inout, bool /*le*/) {
+ // static branch
+ ByteSwapper<T, (SwapEndianess && sizeof(T) > 1)>()(inout);
+ }
+};
+} // namespace Intern
+} // namespace FBXDocParser
+
+#endif // BYTE_SWAPPER_H
diff --git a/modules/fbx/fbx_parser/CREDITS b/modules/fbx/fbx_parser/CREDITS
new file mode 100644
index 0000000000..62b449614e
--- /dev/null
+++ b/modules/fbx/fbx_parser/CREDITS
@@ -0,0 +1,183 @@
+===============================================================
+Open Asset Import Library (Assimp)
+Developers and Contributors
+===============================================================
+
+The following is a non-exhaustive list of all constributors over the years.
+If you think your name should be listed here, drop us a line and we'll add you.
+
+- Alexander Gessler,
+3DS-, BLEND-, ASE-, DXF-, HMP-, MDL-, MD2-, MD3-, MD5-, MDC-, NFF-, PLY-, STL-, RAW-, OFF-, MS3D-, Q3D- and LWO-Loader, Assimp-Viewer, assimp-cmd, -noboost, Website (Design).
+
+- Thomas Schulze,
+X-, Collada-, BVH-Loader, Postprocessing framework. Data structure & Interface design, documentation.
+
+- Kim Kulling,
+Obj-, Q3BSD-, OpenGEX-Loader, Logging system, CMake-build-environment, Linux-build, Website ( Admin ), Coverity ( Admin ), Glitter ( Admin ).
+
+- R.Schmidt,
+Linux build, eclipse support.
+
+- Matthias Gubisch,
+Assimp.net
+Visual Studio 9 support, bugfixes.
+
+- Mark Sibly
+B3D-Loader, Assimp testing
+
+- Jonathan Klein
+Ogre Loader, VC2010 fixes and CMake fixes.
+
+- Sebastian Hempel,
+PyAssimp (first version)
+Compile-Bugfixes for mingw, add environment for static library support in make.
+
+- Jonathan Pokrass
+Supplied a bugfix concerning the scaling in the md3 loader.
+
+- Andrew Galante,
+Submitted patches to make Assimp compile with GCC-4, a makefile and the xcode3 workspace.
+
+- Andreas Nagel
+First Assimp testing & verification under Windows Vista 64 Bit.
+
+- Marius Schr�der
+Allowed us to use many of his models for screenshots and testing.
+
+- Christian Schubert
+Supplied various XFiles for testing purposes.
+
+- Tizian Wieland
+Searched the web for hundreds of test models for internal use
+
+- John Connors
+Supplied patches for linux and SCons.
+
+- T. R.
+The GUY who performed some of the CSM mocaps.
+
+- Andy Maloney
+Contributed fixes for the documentation and the doxygen markup
+
+- Zhao Lei
+Contributed several bugfixes fixing memory leaks and improving float parsing
+
+- sueastside
+Updated PyAssimp to the latest Assimp data structures and provided a script to keep the Python binding up-to-date.
+
+- Tobias Rittig
+Collada testing with Cinema 4D
+
+- Brad Grantham
+Improvements in OpenGL-Sample.
+
+- Robert Ramirez
+Add group loading feature to Obj-Loader.
+
+- Chris Maiwald
+Many bugreports, improving Assimp's portability, regular testing & feedback.
+
+- Stepan Hrbek
+Bugreport and fix for a obj-materialloader crash.
+
+- David Nadlinger
+D bindings, CMake install support.
+
+- Dario Accornero
+Contributed several patches regarding Mac OS/XCode targets, bug reports.
+
+- Martin Walser (Samhayne)
+Contributed the 'SimpleTexturedOpenGl' sample.
+
+- Matthias Fauconneau
+Contributed a fix for the Q3-BSP loader.
+
+- Jørgen P. Tjernø
+Contributed updated and improved xcode workspaces
+
+- drparallax
+Contributed the /samples/SimpleAssimpViewX sample
+
+- Carsten Fuchs
+Contributed a fix for the Normalize method in aiQuaternion.
+
+- dbburgess
+Contributes a Android-specific build issue: log the hardware architecture for ARM.
+
+- alfiereinre7
+Contributes a obj-fileparser fix: missing tokens in the obj-token list.
+
+- Roman Kharitonov
+Contributes a fix for the configure script environment.
+
+- Ed Diana
+Contributed AssimpDelphi (/port/AssimpDelphi).
+
+- rdb
+Contributes a bundle of fixes and improvements for the bsp-importer.
+
+- Mick P
+For contributing the De-bone postprocessing step and filing various bug reports.
+
+- Rosen Diankov
+Contributed patches to build assimp debian packages using cmake.
+
+- Mark Page
+Contributed a patch to fix the VertexTriangleAdjacency postprocessing step.
+
+- IOhannes
+Contributed the Debian build fixes ( architecture macro ).
+
+- gellule
+Several LWO and LWS fixes (pivoting).
+
+- Marcel Metz
+GCC/Linux fixes for the SimpleOpenGL sample.
+
+- Brian Miller
+Bugfix for a compiler fix for iOS on arm.
+
+- Séverin Lemaignan
+Rewrite of PyAssimp, distutils and Python3 support
+
+- albert-wang
+Bugfixes for the collada parser
+
+- Ya ping Jin
+Bugfixes for uv-tanget calculation.
+
+- Jonne Nauha
+Ogre Binary format support
+
+- Filip Wasil, Tieto Poland Sp. z o.o.
+Android JNI asset extraction support
+
+- Richard Steffen
+Contributed ExportProperties interface
+Contributed X File exporter
+Contributed Step (stp) exporter
+
+- Thomas Iorns (mesilliac)
+Initial FBX Export support
+
+For a more detailed list just check: https://github.com/assimp/assimp/network/members
+
+
+========
+Patreons
+========
+
+Huge thanks to our Patreons!
+
+- migenius
+- Marcus
+- Cort
+- elect
+- Steffen
+
+
+===================
+Commercial Sponsors
+===================
+
+- MyDidimo (mydidimo.com): Sponsored development of FBX Export support
diff --git a/modules/fbx/fbx_parser/FBXAnimation.cpp b/modules/fbx/fbx_parser/FBXAnimation.cpp
new file mode 100644
index 0000000000..b11e2c7f55
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXAnimation.cpp
@@ -0,0 +1,290 @@
+/*************************************************************************/
+/* FBXAnimation.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXAnimation.cpp
+ * @brief Assimp::FBX::AnimationCurve, Assimp::FBX::AnimationCurveNode,
+ * Assimp::FBX::AnimationLayer, Assimp::FBX::AnimationStack
+ */
+
+#include "FBXCommon.h"
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXParser.h"
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+AnimationCurve::AnimationCurve(uint64_t id, const ElementPtr element, const std::string &name, const Document & /*doc*/) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+ const ElementPtr KeyTime = GetRequiredElement(sc, "KeyTime");
+ const ElementPtr KeyValueFloat = GetRequiredElement(sc, "KeyValueFloat");
+
+ // note preserved keys and values for legacy FBXConverter.cpp
+ // we can remove this once the animation system is written
+ // and clean up this code so we do not have copies everywhere.
+ ParseVectorDataArray(keys, KeyTime);
+ ParseVectorDataArray(values, KeyValueFloat);
+
+ if (keys.size() != values.size()) {
+ DOMError("the number of key times does not match the number of keyframe values", KeyTime);
+ }
+
+ // put the two lists into the map, underlying container is really just a dictionary
+ // these will always match, if not an error will throw and the file will not import
+ // this is useful because we then can report something and fix this later if it becomes an issue
+ // at this point we do not need a different count of these elements so this makes the
+ // most sense to do.
+ for (size_t x = 0; x < keys.size(); x++) {
+ keyvalues[keys[x]] = values[x];
+ }
+
+ const ElementPtr KeyAttrDataFloat = sc->GetElement("KeyAttrDataFloat");
+ if (KeyAttrDataFloat) {
+ ParseVectorDataArray(attributes, KeyAttrDataFloat);
+ }
+
+ const ElementPtr KeyAttrFlags = sc->GetElement("KeyAttrFlags");
+ if (KeyAttrFlags) {
+ ParseVectorDataArray(flags, KeyAttrFlags);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationCurve::~AnimationCurve() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationCurveNode::AnimationCurveNode(uint64_t id, const ElementPtr element, const std::string &name,
+ const Document &doc, const char *const *target_prop_whitelist /*= NULL*/,
+ size_t whitelist_size /*= 0*/) :
+ Object(id, element, name), target(), doc(doc) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ // find target node
+ const char *whitelist[] = { "Model", "NodeAttribute", "Deformer" };
+ const std::vector<const Connection *> &conns = doc.GetConnectionsBySourceSequenced(ID(), whitelist, 3);
+
+ for (const Connection *con : conns) {
+ // link should go for a property
+ if (!con->PropertyName().length()) {
+ continue;
+ }
+
+ Object *object = con->DestinationObject();
+
+ if (!object) {
+ DOMWarning("failed to read destination object for AnimationCurveNode->Model link, ignoring", element);
+ continue;
+ }
+
+ target = object;
+ prop = con->PropertyName();
+ break;
+ }
+
+ props = GetPropertyTable(doc, "AnimationCurveNode.FbxAnimCurveNode", element, sc, false);
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationCurveNode::~AnimationCurveNode() {
+ curves.clear();
+}
+
+// ------------------------------------------------------------------------------------------------
+const AnimationMap &AnimationCurveNode::Curves() const {
+ /* Lazy loaded animation curves, will only load if required */
+ if (curves.empty()) {
+ // resolve attached animation curves
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "AnimationCurve");
+
+ for (const Connection *con : conns) {
+ // So the advantage of having this STL boilerplate is that it's dead simple once you get it.
+ // The other advantage is casting is guaranteed to be safe and nullptr will be returned in the last step if it fails.
+ Object *ob = con->SourceObject();
+ AnimationCurve *anim_curve = dynamic_cast<AnimationCurve *>(ob);
+ ERR_CONTINUE_MSG(!anim_curve, "Failed to convert animation curve from object");
+
+ curves.insert(std::make_pair(con->PropertyName(), anim_curve));
+ }
+ }
+
+ return curves;
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationLayer::AnimationLayer(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Object(id, element, name), doc(doc) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ // note: the props table here bears little importance and is usually absent
+ props = GetPropertyTable(doc, "AnimationLayer.FbxAnimLayer", element, sc, true);
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationLayer::~AnimationLayer() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+const AnimationCurveNodeList AnimationLayer::Nodes(const char *const *target_prop_whitelist,
+ size_t whitelist_size /*= 0*/) const {
+ AnimationCurveNodeList nodes;
+
+ // resolve attached animation nodes
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "AnimationCurveNode");
+ nodes.reserve(conns.size());
+
+ for (const Connection *con : conns) {
+ // link should not go to a property
+ if (con->PropertyName().length()) {
+ continue;
+ }
+
+ Object *ob = con->SourceObject();
+
+ if (!ob) {
+ DOMWarning("failed to read source object for AnimationCurveNode->AnimationLayer link, ignoring", element);
+ continue;
+ }
+
+ const AnimationCurveNode *anim = dynamic_cast<AnimationCurveNode *>(ob);
+ if (!anim) {
+ DOMWarning("source object for ->AnimationLayer link is not an AnimationCurveNode", element);
+ continue;
+ }
+
+ if (target_prop_whitelist) {
+ const char *s = anim->TargetProperty().c_str();
+ bool ok = false;
+ for (size_t i = 0; i < whitelist_size; ++i) {
+ if (!strcmp(s, target_prop_whitelist[i])) {
+ ok = true;
+ break;
+ }
+ }
+ if (!ok) {
+ continue;
+ }
+ }
+ nodes.push_back(anim);
+ }
+
+ return nodes;
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationStack::AnimationStack(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ // note: we don't currently use any of these properties so we shouldn't bother if it is missing
+ props = GetPropertyTable(doc, "AnimationStack.FbxAnimStack", element, sc, true);
+
+ // resolve attached animation layers
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "AnimationLayer");
+ layers.reserve(conns.size());
+
+ for (const Connection *con : conns) {
+ // link should not go to a property
+ if (con->PropertyName().length()) {
+ continue;
+ }
+
+ Object *ob = con->SourceObject();
+ if (!ob) {
+ DOMWarning("failed to read source object for AnimationLayer->AnimationStack link, ignoring", element);
+ continue;
+ }
+
+ const AnimationLayer *anim = dynamic_cast<const AnimationLayer *>(ob);
+
+ if (!anim) {
+ DOMWarning("source object for ->AnimationStack link is not an AnimationLayer", element);
+ continue;
+ }
+
+ layers.push_back(anim);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+AnimationStack::~AnimationStack() {
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXBinaryTokenizer.cpp b/modules/fbx/fbx_parser/FBXBinaryTokenizer.cpp
new file mode 100644
index 0000000000..1d2b7765c5
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXBinaryTokenizer.cpp
@@ -0,0 +1,467 @@
+/*************************************************************************/
+/* FBXBinaryTokenizer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+/** @file FBXBinaryTokenizer.cpp
+ * @brief Implementation of a fake lexer for binary fbx files -
+ * we emit tokens so the parser needs almost no special handling
+ * for binary files.
+ */
+
+#include "ByteSwapper.h"
+#include "FBXTokenizer.h"
+#include "core/string/print_string.h"
+
+#include <stdint.h>
+
+namespace FBXDocParser {
+//enum Flag
+//{
+// e_unknown_0 = 1 << 0,
+// e_unknown_1 = 1 << 1,
+// e_unknown_2 = 1 << 2,
+// e_unknown_3 = 1 << 3,
+// e_unknown_4 = 1 << 4,
+// e_unknown_5 = 1 << 5,
+// e_unknown_6 = 1 << 6,
+// e_unknown_7 = 1 << 7,
+// e_unknown_8 = 1 << 8,
+// e_unknown_9 = 1 << 9,
+// e_unknown_10 = 1 << 10,
+// e_unknown_11 = 1 << 11,
+// e_unknown_12 = 1 << 12,
+// e_unknown_13 = 1 << 13,
+// e_unknown_14 = 1 << 14,
+// e_unknown_15 = 1 << 15,
+// e_unknown_16 = 1 << 16,
+// e_unknown_17 = 1 << 17,
+// e_unknown_18 = 1 << 18,
+// e_unknown_19 = 1 << 19,
+// e_unknown_20 = 1 << 20,
+// e_unknown_21 = 1 << 21,
+// e_unknown_22 = 1 << 22,
+// e_unknown_23 = 1 << 23,
+// e_flag_field_size_64_bit = 1 << 24, // Not sure what is
+// e_unknown_25 = 1 << 25,
+// e_unknown_26 = 1 << 26,
+// e_unknown_27 = 1 << 27,
+// e_unknown_28 = 1 << 28,
+// e_unknown_29 = 1 << 29,
+// e_unknown_30 = 1 << 30,
+// e_unknown_31 = 1 << 31
+//};
+//
+//bool check_flag(uint32_t flags, Flag to_check)
+//{
+// return (flags & to_check) != 0;
+//}
+// ------------------------------------------------------------------------------------------------
+Token::Token(const char *sbegin, const char *send, TokenType type, size_t offset) :
+ sbegin(sbegin),
+ send(send),
+ type(type),
+ line(offset),
+ column(BINARY_MARKER) {
+#ifdef DEBUG_ENABLED
+ contents = std::string(sbegin, static_cast<size_t>(send - sbegin));
+#endif
+ // calc length
+ // measure from sBegin to sEnd and validate?
+}
+
+namespace {
+
+// ------------------------------------------------------------------------------------------------
+// signal tokenization error
+void TokenizeError(const std::string &message, size_t offset) {
+ print_error("[FBX-Tokenize] " + String(message.c_str()) + ", offset " + itos(offset));
+}
+
+// ------------------------------------------------------------------------------------------------
+size_t Offset(const char *begin, const char *cursor) {
+ //ai_assert(begin <= cursor);
+
+ return cursor - begin;
+}
+
+// ------------------------------------------------------------------------------------------------
+void TokenizeError(const std::string &message, const char *begin, const char *cursor) {
+ TokenizeError(message, Offset(begin, cursor));
+}
+
+// ------------------------------------------------------------------------------------------------
+uint32_t ReadWord(const char *input, const char *&cursor, const char *end) {
+ const size_t k_to_read = sizeof(uint32_t);
+ if (Offset(cursor, end) < k_to_read) {
+ TokenizeError("cannot ReadWord, out of bounds", input, cursor);
+ }
+
+ uint32_t word;
+ ::memcpy(&word, cursor, 4);
+ AI_SWAP4(word);
+
+ cursor += k_to_read;
+
+ return word;
+}
+
+// ------------------------------------------------------------------------------------------------
+uint64_t ReadDoubleWord(const char *input, const char *&cursor, const char *end) {
+ const size_t k_to_read = sizeof(uint64_t);
+ if (Offset(cursor, end) < k_to_read) {
+ TokenizeError("cannot ReadDoubleWord, out of bounds", input, cursor);
+ }
+
+ uint64_t dword /*= *reinterpret_cast<const uint64_t*>(cursor)*/;
+ ::memcpy(&dword, cursor, sizeof(uint64_t));
+ AI_SWAP8(dword);
+
+ cursor += k_to_read;
+
+ return dword;
+}
+
+// ------------------------------------------------------------------------------------------------
+uint8_t ReadByte(const char *input, const char *&cursor, const char *end) {
+ if (Offset(cursor, end) < sizeof(uint8_t)) {
+ TokenizeError("cannot ReadByte, out of bounds", input, cursor);
+ }
+
+ uint8_t word; /* = *reinterpret_cast< const uint8_t* >( cursor )*/
+ ::memcpy(&word, cursor, sizeof(uint8_t));
+ ++cursor;
+
+ return word;
+}
+
+// ------------------------------------------------------------------------------------------------
+unsigned int ReadString(const char *&sbegin_out, const char *&send_out, const char *input,
+ const char *&cursor, const char *end, bool long_length = false, bool allow_null = false) {
+ const uint32_t len_len = long_length ? 4 : 1;
+ if (Offset(cursor, end) < len_len) {
+ TokenizeError("cannot ReadString, out of bounds reading length", input, cursor);
+ }
+
+ const uint32_t length = long_length ? ReadWord(input, cursor, end) : ReadByte(input, cursor, end);
+
+ if (Offset(cursor, end) < length) {
+ TokenizeError("cannot ReadString, length is out of bounds", input, cursor);
+ }
+
+ sbegin_out = cursor;
+ cursor += length;
+
+ send_out = cursor;
+
+ if (!allow_null) {
+ for (unsigned int i = 0; i < length; ++i) {
+ if (sbegin_out[i] == '\0') {
+ TokenizeError("failed ReadString, unexpected NUL character in string", input, cursor);
+ }
+ }
+ }
+
+ return length;
+}
+
+// ------------------------------------------------------------------------------------------------
+void ReadData(const char *&sbegin_out, const char *&send_out, const char *input, const char *&cursor, const char *end) {
+ if (Offset(cursor, end) < 1) {
+ TokenizeError("cannot ReadData, out of bounds reading length", input, cursor);
+ }
+
+ const char type = *cursor;
+ sbegin_out = cursor++;
+
+ switch (type) {
+ // 16 bit int
+ case 'Y':
+ cursor += 2;
+ break;
+
+ // 1 bit bool flag (yes/no)
+ case 'C':
+ cursor += 1;
+ break;
+
+ // 32 bit int
+ case 'I':
+ // <- fall through
+
+ // float
+ case 'F':
+ cursor += 4;
+ break;
+
+ // double
+ case 'D':
+ cursor += 8;
+ break;
+
+ // 64 bit int
+ case 'L':
+ cursor += 8;
+ break;
+
+ // note: do not write cursor += ReadWord(...cursor) as this would be UB
+
+ // raw binary data
+ case 'R': {
+ const uint32_t length = ReadWord(input, cursor, end);
+ cursor += length;
+ break;
+ }
+
+ case 'b':
+ // TODO: what is the 'b' type code? Right now we just skip over it /
+ // take the full range we could get
+ cursor = end;
+ break;
+
+ // array of *
+ case 'f':
+ case 'd':
+ case 'l':
+ case 'i':
+ case 'c': {
+ const uint32_t length = ReadWord(input, cursor, end);
+ const uint32_t encoding = ReadWord(input, cursor, end);
+
+ const uint32_t comp_len = ReadWord(input, cursor, end);
+
+ // compute length based on type and check against the stored value
+ if (encoding == 0) {
+ uint32_t stride = 0;
+ switch (type) {
+ case 'f':
+ case 'i':
+ stride = 4;
+ break;
+
+ case 'd':
+ case 'l':
+ stride = 8;
+ break;
+
+ case 'c':
+ stride = 1;
+ break;
+
+ default:
+ break;
+ };
+ //ai_assert(stride > 0);
+ if (length * stride != comp_len) {
+ TokenizeError("cannot ReadData, calculated data stride differs from what the file claims", input, cursor);
+ }
+ }
+ // zip/deflate algorithm (encoding==1)? take given length. anything else? die
+ else if (encoding != 1) {
+ TokenizeError("cannot ReadData, unknown encoding", input, cursor);
+ }
+ cursor += comp_len;
+ break;
+ }
+
+ // string
+ case 'S': {
+ const char *sb, *se;
+ // 0 characters can legally happen in such strings
+ ReadString(sb, se, input, cursor, end, true, true);
+ break;
+ }
+ default:
+ TokenizeError("cannot ReadData, unexpected type code: " + std::string(&type, 1), input, cursor);
+ }
+
+ if (cursor > end) {
+ TokenizeError("cannot ReadData, the remaining size is too small for the data type: " + std::string(&type, 1), input, cursor);
+ }
+
+ // the type code is contained in the returned range
+ send_out = cursor;
+}
+
+// ------------------------------------------------------------------------------------------------
+bool ReadScope(TokenList &output_tokens, const char *input, const char *&cursor, const char *end, bool const is64bits) {
+ // the first word contains the offset at which this block ends
+ const uint64_t end_offset = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
+
+ // we may get 0 if reading reached the end of the file -
+ // fbx files have a mysterious extra footer which I don't know
+ // how to extract any information from, but at least it always
+ // starts with a 0.
+ if (!end_offset) {
+ return false;
+ }
+
+ if (end_offset > Offset(input, end)) {
+ TokenizeError("block offset is out of range", input, cursor);
+ } else if (end_offset < Offset(input, cursor)) {
+ TokenizeError("block offset is negative out of range", input, cursor);
+ }
+
+ // the second data word contains the number of properties in the scope
+ const uint64_t prop_count = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
+
+ // the third data word contains the length of the property list
+ const uint64_t prop_length = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
+
+ // now comes the name of the scope/key
+ const char *sbeg, *send;
+ ReadString(sbeg, send, input, cursor, end);
+
+ output_tokens.push_back(new_Token(sbeg, send, TokenType_KEY, Offset(input, cursor)));
+
+ // now come the individual properties
+ const char *begin_cursor = cursor;
+ for (unsigned int i = 0; i < prop_count; ++i) {
+ ReadData(sbeg, send, input, cursor, begin_cursor + prop_length);
+
+ output_tokens.push_back(new_Token(sbeg, send, TokenType_DATA, Offset(input, cursor)));
+
+ if (i != prop_count - 1) {
+ output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_COMMA, Offset(input, cursor)));
+ }
+ }
+
+ if (Offset(begin_cursor, cursor) != prop_length) {
+ TokenizeError("property length not reached, something is wrong", input, cursor);
+ }
+
+ // at the end of each nested block, there is a NUL record to indicate
+ // that the sub-scope exists (i.e. to distinguish between P: and P : {})
+ // this NUL record is 13 bytes long on 32 bit version and 25 bytes long on 64 bit.
+ const size_t sentinel_block_length = is64bits ? (sizeof(uint64_t) * 3 + 1) : (sizeof(uint32_t) * 3 + 1);
+
+ if (Offset(input, cursor) < end_offset) {
+ if (end_offset - Offset(input, cursor) < sentinel_block_length) {
+ TokenizeError("insufficient padding bytes at block end", input, cursor);
+ }
+
+ output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_OPEN_BRACKET, Offset(input, cursor)));
+
+ // XXX this is vulnerable to stack overflowing ..
+ while (Offset(input, cursor) < end_offset - sentinel_block_length) {
+ ReadScope(output_tokens, input, cursor, input + end_offset - sentinel_block_length, is64bits);
+ }
+ output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_CLOSE_BRACKET, Offset(input, cursor)));
+
+ for (unsigned int i = 0; i < sentinel_block_length; ++i) {
+ if (cursor[i] != '\0') {
+ TokenizeError("failed to read nested block sentinel, expected all bytes to be 0", input, cursor);
+ }
+ }
+ cursor += sentinel_block_length;
+ }
+
+ if (Offset(input, cursor) != end_offset) {
+ TokenizeError("scope length not reached, something is wrong", input, cursor);
+ }
+
+ return true;
+}
+} // anonymous namespace
+
+// ------------------------------------------------------------------------------------------------
+// TODO: Test FBX Binary files newer than the 7500 version to check if the 64 bits address behaviour is consistent
+void TokenizeBinary(TokenList &output_tokens, const char *input, size_t length) {
+ if (length < 0x1b) {
+ //TokenizeError("file is too short",0);
+ }
+
+ //uint32_t offset = 0x15;
+ /* const char* cursor = input + 0x15;
+ const uint32_t flags = ReadWord(input, cursor, input + length);
+ const uint8_t padding_0 = ReadByte(input, cursor, input + length); // unused
+ const uint8_t padding_1 = ReadByte(input, cursor, input + length); // unused*/
+
+ if (strncmp(input, "Kaydara FBX Binary", 18)) {
+ TokenizeError("magic bytes not found", 0);
+ }
+
+ const char *cursor = input + 18;
+ /*Result ignored*/ ReadByte(input, cursor, input + length);
+ /*Result ignored*/ ReadByte(input, cursor, input + length);
+ /*Result ignored*/ ReadByte(input, cursor, input + length);
+ /*Result ignored*/ ReadByte(input, cursor, input + length);
+ /*Result ignored*/ ReadByte(input, cursor, input + length);
+ const uint32_t version = ReadWord(input, cursor, input + length);
+ print_verbose("FBX Version: " + itos(version));
+ //ASSIMP_LOG_DEBUG_F("FBX version: ", version);
+ const bool is64bits = version >= 7500;
+ const char *end = input + length;
+ while (cursor < end) {
+ if (!ReadScope(output_tokens, input, cursor, input + length, is64bits)) {
+ break;
+ }
+ }
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXCommon.h b/modules/fbx/fbx_parser/FBXCommon.h
new file mode 100644
index 0000000000..641d6d351e
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXCommon.h
@@ -0,0 +1,110 @@
+/*************************************************************************/
+/* FBXCommon.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+copyright notice, this list of conditions and the
+following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the
+following disclaimer in the documentation and/or other
+materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+contributors may be used to endorse or promote products
+derived from this software without specific prior
+written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXCommon.h
+* Some useful constants and enums for dealing with FBX files.
+*/
+#ifndef FBX_COMMON_H
+#define FBX_COMMON_H
+
+#include <string>
+
+namespace FBXDocParser {
+const std::string NULL_RECORD = { // 13 null bytes
+ '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
+}; // who knows why
+const std::string SEPARATOR = { '\x00', '\x01' }; // for use inside strings
+const std::string MAGIC_NODE_TAG = "_$AssimpFbx$"; // from import
+const int64_t SECOND = 46186158000; // FBX's kTime unit
+
+// rotation order. We'll probably use EulerXYZ for everything
+enum RotOrder {
+ RotOrder_EulerXYZ = 0,
+ RotOrder_EulerXZY,
+ RotOrder_EulerYZX,
+ RotOrder_EulerYXZ,
+ RotOrder_EulerZXY,
+ RotOrder_EulerZYX,
+
+ RotOrder_SphericXYZ,
+
+ RotOrder_MAX // end-of-enum sentinel
+};
+
+enum TransformInheritance {
+ Transform_RrSs = 0,
+ Transform_RSrs = 1,
+ Transform_Rrs = 2,
+ TransformInheritance_MAX // end-of-enum sentinel
+};
+} // namespace FBXDocParser
+
+#endif // FBX_COMMON_H
diff --git a/modules/fbx/fbx_parser/FBXDeformer.cpp b/modules/fbx/fbx_parser/FBXDeformer.cpp
new file mode 100644
index 0000000000..4b774e6b2a
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXDeformer.cpp
@@ -0,0 +1,279 @@
+/*************************************************************************/
+/* FBXDeformer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXNoteAttribute.cpp
+ * @brief Assimp::FBX::NodeAttribute (and subclasses) implementation
+ */
+
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXMeshGeometry.h"
+#include "FBXParser.h"
+#include "core/math/math_funcs.h"
+#include "core/math/transform.h"
+
+#include <iostream>
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+Deformer::Deformer(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ const std::string &classname = ParseTokenAsString(GetRequiredToken(element, 2));
+ props = GetPropertyTable(doc, "Deformer.Fbx" + classname, element, sc, true);
+}
+
+// ------------------------------------------------------------------------------------------------
+Deformer::~Deformer() {
+}
+
+Constraint::Constraint(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+ const std::string &classname = ParseTokenAsString(GetRequiredToken(element, 2));
+ // used something.fbx as this is a cache name.
+ props = GetPropertyTable(doc, "Something.Fbx" + classname, element, sc, true);
+}
+
+Constraint::~Constraint() {
+}
+
+// ------------------------------------------------------------------------------------------------
+Cluster::Cluster(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Deformer(id, element, doc, name), valid_transformAssociateModel(false) {
+ const ScopePtr sc = GetRequiredScope(element);
+ // for( auto element : sc.Elements())
+ // {
+ // std::cout << "cluster element: " << element.first << std::endl;
+ // }
+ //
+ // element: Indexes
+ // element: Transform
+ // element: TransformAssociateModel
+ // element: TransformLink
+ // element: UserData
+ // element: Version
+ // element: Weights
+
+ const ElementPtr Indexes = sc->GetElement("Indexes");
+ const ElementPtr Weights = sc->GetElement("Weights");
+
+ const ElementPtr TransformAssociateModel = sc->GetElement("TransformAssociateModel");
+ if (TransformAssociateModel != nullptr) {
+ //Transform t = ReadMatrix(*TransformAssociateModel);
+ link_mode = SkinLinkMode_Additive;
+ valid_transformAssociateModel = true;
+ } else {
+ link_mode = SkinLinkMode_Normalized;
+ valid_transformAssociateModel = false;
+ }
+
+ const ElementPtr Transform = GetRequiredElement(sc, "Transform", element);
+ const ElementPtr TransformLink = GetRequiredElement(sc, "TransformLink", element);
+
+ // todo: check if we need this
+ //const Element& TransformAssociateModel = GetRequiredElement(sc, "TransformAssociateModel", &element);
+
+ transform = ReadMatrix(Transform);
+ transformLink = ReadMatrix(TransformLink);
+
+ // it is actually possible that there be Deformer's with no weights
+ if (!!Indexes != !!Weights) {
+ DOMError("either Indexes or Weights are missing from Cluster", element);
+ }
+
+ if (Indexes) {
+ ParseVectorDataArray(indices, Indexes);
+ ParseVectorDataArray(weights, Weights);
+ }
+
+ if (indices.size() != weights.size()) {
+ DOMError("sizes of index and weight array don't match up", element);
+ }
+
+ // read assigned node
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Model");
+ for (const Connection *con : conns) {
+ const Model *mod = ProcessSimpleConnection<Model>(*con, false, "Model -> Cluster", element);
+ if (mod) {
+ node = mod;
+ break;
+ }
+ }
+
+ if (!node) {
+ DOMError("failed to read target Node for Cluster", element);
+ node = nullptr;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Cluster::~Cluster() {
+}
+
+// ------------------------------------------------------------------------------------------------
+Skin::Skin(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Deformer(id, element, doc, name), accuracy(0.0f) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ // keep this it is used for debugging and any FBX format changes
+ // for (auto element : sc.Elements()) {
+ // std::cout << "skin element: " << element.first << std::endl;
+ // }
+
+ const ElementPtr Link_DeformAcuracy = sc->GetElement("Link_DeformAcuracy");
+ if (Link_DeformAcuracy) {
+ accuracy = ParseTokenAsFloat(GetRequiredToken(Link_DeformAcuracy, 0));
+ }
+
+ const ElementPtr SkinType = sc->GetElement("SkinningType");
+
+ if (SkinType) {
+ std::string skin_type = ParseTokenAsString(GetRequiredToken(SkinType, 0));
+
+ if (skin_type == "Linear") {
+ skinType = Skin_Linear;
+ } else if (skin_type == "Rigid") {
+ skinType = Skin_Rigid;
+ } else if (skin_type == "DualQuaternion") {
+ skinType = Skin_DualQuaternion;
+ } else if (skin_type == "Blend") {
+ skinType = Skin_Blend;
+ } else {
+ print_error("[doc:skin] could not find valid skin type: " + String(skin_type.c_str()));
+ }
+ }
+
+ // resolve assigned clusters
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Deformer");
+
+ //
+
+ clusters.reserve(conns.size());
+ for (const Connection *con : conns) {
+ const Cluster *cluster = ProcessSimpleConnection<Cluster>(*con, false, "Cluster -> Skin", element);
+ if (cluster) {
+ clusters.push_back(cluster);
+ continue;
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Skin::~Skin() {
+}
+// ------------------------------------------------------------------------------------------------
+BlendShape::BlendShape(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Deformer(id, element, doc, name) {
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Deformer");
+ blendShapeChannels.reserve(conns.size());
+ for (const Connection *con : conns) {
+ const BlendShapeChannel *bspc = ProcessSimpleConnection<BlendShapeChannel>(*con, false, "BlendShapeChannel -> BlendShape", element);
+ if (bspc) {
+ blendShapeChannels.push_back(bspc);
+ continue;
+ }
+ }
+}
+// ------------------------------------------------------------------------------------------------
+BlendShape::~BlendShape() {
+}
+// ------------------------------------------------------------------------------------------------
+BlendShapeChannel::BlendShapeChannel(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Deformer(id, element, doc, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+ const ElementPtr DeformPercent = sc->GetElement("DeformPercent");
+ if (DeformPercent) {
+ percent = ParseTokenAsFloat(GetRequiredToken(DeformPercent, 0));
+ }
+ const ElementPtr FullWeights = sc->GetElement("FullWeights");
+ if (FullWeights) {
+ ParseVectorDataArray(fullWeights, FullWeights);
+ }
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Geometry");
+ shapeGeometries.reserve(conns.size());
+ for (const Connection *con : conns) {
+ const ShapeGeometry *const sg = ProcessSimpleConnection<ShapeGeometry>(*con, false, "Shape -> BlendShapeChannel", element);
+ if (sg) {
+ shapeGeometries.push_back(sg);
+ continue;
+ }
+ }
+}
+// ------------------------------------------------------------------------------------------------
+BlendShapeChannel::~BlendShapeChannel() {
+}
+// ------------------------------------------------------------------------------------------------
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXDocument.cpp b/modules/fbx/fbx_parser/FBXDocument.cpp
new file mode 100644
index 0000000000..bcf7fa1565
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXDocument.cpp
@@ -0,0 +1,713 @@
+/*************************************************************************/
+/* FBXDocument.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the*
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXDocument.cpp
+ * @brief Implementation of the FBX DOM classes
+ */
+
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXImportSettings.h"
+#include "FBXMeshGeometry.h"
+#include "FBXParser.h"
+#include "FBXProperties.h"
+#include "FBXUtil.h"
+
+#include <algorithm>
+#include <functional>
+#include <iostream>
+#include <map>
+#include <memory>
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+LazyObject::LazyObject(uint64_t id, const ElementPtr element, const Document &doc) :
+ doc(doc), element(element), id(id), flags() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+LazyObject::~LazyObject() {
+ object.reset();
+}
+
+ObjectPtr LazyObject::LoadObject() {
+ if (IsBeingConstructed() || FailedToConstruct()) {
+ return nullptr;
+ }
+
+ if (object) {
+ return object.get();
+ }
+
+ TokenPtr key = element->KeyToken();
+ ERR_FAIL_COND_V(!key, nullptr);
+ const TokenList &tokens = element->Tokens();
+
+ if (tokens.size() < 3) {
+ //DOMError("expected at least 3 tokens: id, name and class tag",&element);
+ return nullptr;
+ }
+
+ const char *err = nullptr;
+ std::string name = ParseTokenAsString(tokens[1], err);
+ if (err) {
+ DOMError(err, element);
+ }
+
+ // small fix for binary reading: binary fbx files don't use
+ // prefixes such as Model:: in front of their names. The
+ // loading code expects this at many places, though!
+ // so convert the binary representation (a 0x0001) to the
+ // double colon notation.
+ if (tokens[1]->IsBinary()) {
+ for (size_t i = 0; i < name.length(); ++i) {
+ if (name[i] == 0x0 && name[i + 1] == 0x1) {
+ name = name.substr(i + 2) + "::" + name.substr(0, i);
+ }
+ }
+ }
+
+ const std::string classtag = ParseTokenAsString(tokens[2], err);
+ if (err) {
+ DOMError(err, element);
+ }
+
+ // prevent recursive calls
+ flags |= BEING_CONSTRUCTED;
+
+ // this needs to be relatively fast since it happens a lot,
+ // so avoid constructing strings all the time.
+ const char *obtype = key->begin();
+ const size_t length = static_cast<size_t>(key->end() - key->begin());
+
+ if (!strncmp(obtype, "Pose", length)) {
+ object.reset(new FbxPose(id, element, doc, name));
+ } else if (!strncmp(obtype, "Geometry", length)) {
+ if (!strcmp(classtag.c_str(), "Mesh")) {
+ object.reset(new MeshGeometry(id, element, name, doc));
+ }
+ if (!strcmp(classtag.c_str(), "Shape")) {
+ object.reset(new ShapeGeometry(id, element, name, doc));
+ }
+ if (!strcmp(classtag.c_str(), "Line")) {
+ object.reset(new LineGeometry(id, element, name, doc));
+ }
+ } else if (!strncmp(obtype, "NodeAttribute", length)) {
+ if (!strcmp(classtag.c_str(), "Camera")) {
+ object.reset(new Camera(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "CameraSwitcher")) {
+ object.reset(new CameraSwitcher(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "Light")) {
+ object.reset(new Light(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "Null")) {
+ object.reset(new Null(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "LimbNode")) {
+ // This is an older format for bones
+ // this is what blender uses I believe
+ object.reset(new LimbNode(id, element, doc, name));
+ }
+ } else if (!strncmp(obtype, "Constraint", length)) {
+ object.reset(new Constraint(id, element, doc, name));
+ } else if (!strncmp(obtype, "Deformer", length)) {
+ if (!strcmp(classtag.c_str(), "Cluster")) {
+ object.reset(new Cluster(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "Skin")) {
+ object.reset(new Skin(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "BlendShape")) {
+ object.reset(new BlendShape(id, element, doc, name));
+ } else if (!strcmp(classtag.c_str(), "BlendShapeChannel")) {
+ object.reset(new BlendShapeChannel(id, element, doc, name));
+ }
+ } else if (!strncmp(obtype, "Model", length)) {
+ // Model is normal node
+
+ // LimbNode model is a 'bone' node.
+ if (!strcmp(classtag.c_str(), "LimbNode")) {
+ object.reset(new ModelLimbNode(id, element, doc, name));
+
+ } else if (strcmp(classtag.c_str(), "IKEffector") && strcmp(classtag.c_str(), "FKEffector")) {
+ // FK and IK effectors are not supporte
+ object.reset(new Model(id, element, doc, name));
+ }
+ } else if (!strncmp(obtype, "Material", length)) {
+ object.reset(new Material(id, element, doc, name));
+ } else if (!strncmp(obtype, "Texture", length)) {
+ object.reset(new Texture(id, element, doc, name));
+ } else if (!strncmp(obtype, "LayeredTexture", length)) {
+ object.reset(new LayeredTexture(id, element, doc, name));
+ } else if (!strncmp(obtype, "Video", length)) {
+ object.reset(new Video(id, element, doc, name));
+ } else if (!strncmp(obtype, "AnimationStack", length)) {
+ object.reset(new AnimationStack(id, element, name, doc));
+ } else if (!strncmp(obtype, "AnimationLayer", length)) {
+ object.reset(new AnimationLayer(id, element, name, doc));
+ } else if (!strncmp(obtype, "AnimationCurve", length)) {
+ object.reset(new AnimationCurve(id, element, name, doc));
+ } else if (!strncmp(obtype, "AnimationCurveNode", length)) {
+ object.reset(new AnimationCurveNode(id, element, name, doc));
+ } else {
+ ERR_FAIL_V_MSG(nullptr, "FBX contains unsupported object: " + String(obtype));
+ }
+
+ flags &= ~BEING_CONSTRUCTED;
+
+ return object.get();
+}
+
+// ------------------------------------------------------------------------------------------------
+Object::Object(uint64_t id, const ElementPtr element, const std::string &name) :
+ element(element), name(name), id(id) {
+}
+
+// ------------------------------------------------------------------------------------------------
+Object::~Object() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+FileGlobalSettings::FileGlobalSettings(const Document &doc, const PropertyTable *props) :
+ props(props), doc(doc) {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+FileGlobalSettings::~FileGlobalSettings() {
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Document::Document(const Parser &parser, const ImportSettings &settings) :
+ settings(settings), parser(parser), SafeToImport(false) {
+ // Cannot use array default initialization syntax because vc8 fails on it
+ for (unsigned int &timeStamp : creationTimeStamp) {
+ timeStamp = 0;
+ }
+
+ // we must check if we can read the header version safely, if its outdated then drop it.
+ if (ReadHeader()) {
+ SafeToImport = true;
+ ReadPropertyTemplates();
+
+ ReadGlobalSettings();
+
+ // This order is important, connections need parsed objects to check
+ // whether connections are ok or not. Objects may not be evaluated yet,
+ // though, since this may require valid connections.
+ ReadObjects();
+ ReadConnections();
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Document::~Document() {
+ for (PropertyTemplateMap::value_type v : templates) {
+ delete v.second;
+ }
+
+ for (ObjectMap::value_type &v : objects) {
+ delete v.second;
+ }
+
+ for (ConnectionMap::value_type &v : src_connections) {
+ delete v.second;
+ }
+
+ if (metadata_properties != nullptr) {
+ delete metadata_properties;
+ }
+ // clear globals import pointer
+ globals.reset();
+}
+
+// ------------------------------------------------------------------------------------------------
+static const unsigned int LowerSupportedVersion = 7300;
+static const unsigned int UpperSupportedVersion = 7700;
+
+bool Document::ReadHeader() {
+ // Read ID objects from "Objects" section
+ ScopePtr sc = parser.GetRootScope();
+ ElementPtr ehead = sc->GetElement("FBXHeaderExtension");
+ if (!ehead || !ehead->Compound()) {
+ DOMError("no FBXHeaderExtension dictionary found");
+ }
+
+ const ScopePtr shead = ehead->Compound();
+ fbxVersion = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(shead, "FBXVersion", ehead), 0));
+
+ // While we may have some success with newer files, we don't support
+ // the older 6.n fbx format
+ if (fbxVersion < LowerSupportedVersion) {
+ DOMWarning("unsupported, old format version, FBX 2015-2020, you must re-export in a more modern version of your original modelling application");
+ return false;
+ }
+ if (fbxVersion > UpperSupportedVersion) {
+ DOMWarning("unsupported, newer format version, supported are only FBX 2015, up to FBX 2020"
+ " trying to read it nevertheless");
+ }
+
+ const ElementPtr ecreator = shead->GetElement("Creator");
+ if (ecreator) {
+ creator = ParseTokenAsString(GetRequiredToken(ecreator, 0));
+ }
+
+ //
+ // Scene Info
+ //
+
+ const ElementPtr scene_info = shead->GetElement("SceneInfo");
+
+ if (scene_info) {
+ PropertyTable *fileExportProps = const_cast<PropertyTable *>(GetPropertyTable(*this, "", scene_info, scene_info->Compound(), true));
+
+ if (fileExportProps) {
+ metadata_properties = fileExportProps;
+ }
+ }
+
+ const ElementPtr etimestamp = shead->GetElement("CreationTimeStamp");
+ if (etimestamp && etimestamp->Compound()) {
+ const ScopePtr stimestamp = etimestamp->Compound();
+ creationTimeStamp[0] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Year"), 0));
+ creationTimeStamp[1] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Month"), 0));
+ creationTimeStamp[2] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Day"), 0));
+ creationTimeStamp[3] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Hour"), 0));
+ creationTimeStamp[4] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Minute"), 0));
+ creationTimeStamp[5] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Second"), 0));
+ creationTimeStamp[6] = ParseTokenAsInt(GetRequiredToken(GetRequiredElement(stimestamp, "Millisecond"), 0));
+ }
+
+ return true;
+}
+
+// ------------------------------------------------------------------------------------------------
+void Document::ReadGlobalSettings() {
+ ERR_FAIL_COND_MSG(globals != nullptr, "Global settings is already setup this is a serious error and should be reported");
+
+ const ScopePtr sc = parser.GetRootScope();
+ const ElementPtr ehead = sc->GetElement("GlobalSettings");
+ if (nullptr == ehead || !ehead->Compound()) {
+ DOMWarning("no GlobalSettings dictionary found");
+ globals = std::make_shared<FileGlobalSettings>(*this, new PropertyTable());
+ return;
+ }
+
+ const PropertyTable *props = GetPropertyTable(*this, "", ehead, ehead->Compound(), true);
+
+ //double v = PropertyGet<float>( *props, std::string("UnitScaleFactor"), 1.0 );
+
+ if (!props) {
+ DOMError("GlobalSettings dictionary contains no property table");
+ }
+
+ globals = std::make_shared<FileGlobalSettings>(*this, props);
+}
+
+// ------------------------------------------------------------------------------------------------
+void Document::ReadObjects() {
+ // read ID objects from "Objects" section
+ const ScopePtr sc = parser.GetRootScope();
+ const ElementPtr eobjects = sc->GetElement("Objects");
+ if (!eobjects || !eobjects->Compound()) {
+ DOMError("no Objects dictionary found");
+ }
+
+ // add a dummy entry to represent the Model::RootNode object (id 0),
+ // which is only indirectly defined in the input file
+ objects[0] = new LazyObject(0L, eobjects, *this);
+
+ const ScopePtr sobjects = eobjects->Compound();
+ for (const ElementMap::value_type &iter : sobjects->Elements()) {
+ // extract ID
+ const TokenList &tok = iter.second->Tokens();
+
+ if (tok.empty()) {
+ DOMError("expected ID after object key", iter.second);
+ }
+
+ const char *err;
+ const uint64_t id = ParseTokenAsID(tok[0], err);
+ if (err) {
+ DOMError(err, iter.second);
+ }
+
+ // id=0 is normally implicit
+ if (id == 0L) {
+ DOMError("encountered object with implicitly defined id 0", iter.second);
+ }
+
+ if (objects.find(id) != objects.end()) {
+ DOMWarning("encountered duplicate object id, ignoring first occurrence", iter.second);
+ }
+
+ objects[id] = new LazyObject(id, iter.second, *this);
+
+ // grab all animation stacks upfront since there is no listing of them
+ if (!strcmp(iter.first.c_str(), "AnimationStack")) {
+ animationStacks.push_back(id);
+ } else if (!strcmp(iter.first.c_str(), "Constraint")) {
+ constraints.push_back(id);
+ } else if (!strcmp(iter.first.c_str(), "Pose")) {
+ bind_poses.push_back(id);
+ } else if (!strcmp(iter.first.c_str(), "Material")) {
+ materials.push_back(id);
+ } else if (!strcmp(iter.first.c_str(), "Deformer")) {
+ TokenPtr key = iter.second->KeyToken();
+ ERR_CONTINUE_MSG(!key, "[parser bug] invalid token key for deformer");
+ const TokenList &tokens = iter.second->Tokens();
+ const std::string class_tag = ParseTokenAsString(tokens[2], err);
+
+ if (err) {
+ DOMError(err, iter.second);
+ }
+
+ if (class_tag == "Skin") {
+ //print_verbose("registered skin:" + itos(id));
+ skins.push_back(id);
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+void Document::ReadPropertyTemplates() {
+ const ScopePtr sc = parser.GetRootScope();
+ // read property templates from "Definitions" section
+ const ElementPtr edefs = sc->GetElement("Definitions");
+ if (!edefs || !edefs->Compound()) {
+ DOMWarning("no Definitions dictionary found");
+ return;
+ }
+
+ const ScopePtr sdefs = edefs->Compound();
+ const ElementCollection otypes = sdefs->GetCollection("ObjectType");
+ for (ElementMap::const_iterator it = otypes.first; it != otypes.second; ++it) {
+ const ElementPtr el = (*it).second;
+ const ScopePtr sc_2 = el->Compound();
+ if (!sc_2) {
+ DOMWarning("expected nested scope in ObjectType, ignoring", el);
+ continue;
+ }
+
+ const TokenList &tok = el->Tokens();
+ if (tok.empty()) {
+ DOMWarning("expected name for ObjectType element, ignoring", el);
+ continue;
+ }
+
+ const std::string &oname = ParseTokenAsString(tok[0]);
+
+ const ElementCollection templs = sc_2->GetCollection("PropertyTemplate");
+ for (ElementMap::const_iterator iter = templs.first; iter != templs.second; ++iter) {
+ const ElementPtr el_2 = (*iter).second;
+ const ScopePtr sc_3 = el_2->Compound();
+ if (!sc_3) {
+ DOMWarning("expected nested scope in PropertyTemplate, ignoring", el);
+ continue;
+ }
+
+ const TokenList &tok_2 = el_2->Tokens();
+ if (tok_2.empty()) {
+ DOMWarning("expected name for PropertyTemplate element, ignoring", el);
+ continue;
+ }
+
+ const std::string &pname = ParseTokenAsString(tok_2[0]);
+
+ const ElementPtr Properties70 = sc_3->GetElement("Properties70");
+ if (Properties70) {
+ // PropertyTable(const ElementPtr element, const PropertyTable* templateProps);
+ const PropertyTable *props = new PropertyTable(Properties70, nullptr);
+
+ templates[oname + "." + pname] = props;
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+void Document::ReadConnections() {
+ const ScopePtr sc = parser.GetRootScope();
+
+ // read property templates from "Definitions" section
+ const ElementPtr econns = sc->GetElement("Connections");
+ if (!econns || !econns->Compound()) {
+ DOMError("no Connections dictionary found");
+ }
+
+ uint64_t insertionOrder = 0l;
+ const ScopePtr sconns = econns->Compound();
+ const ElementCollection conns = sconns->GetCollection("C");
+ for (ElementMap::const_iterator it = conns.first; it != conns.second; ++it) {
+ const ElementPtr el = (*it).second;
+ const std::string &type = ParseTokenAsString(GetRequiredToken(el, 0));
+
+ // PP = property-property connection, ignored for now
+ // (tokens: "PP", ID1, "Property1", ID2, "Property2")
+ if (type == "PP") {
+ continue;
+ }
+
+ const uint64_t src = ParseTokenAsID(GetRequiredToken(el, 1));
+ const uint64_t dest = ParseTokenAsID(GetRequiredToken(el, 2));
+
+ // OO = object-object connection
+ // OP = object-property connection, in which case the destination property follows the object ID
+ const std::string &prop = (type == "OP" ? ParseTokenAsString(GetRequiredToken(el, 3)) : "");
+
+ if (objects.find(src) == objects.end()) {
+ DOMWarning("source object for connection does not exist", el);
+ continue;
+ }
+
+ // dest may be 0 (root node) but we added a dummy object before
+ if (objects.find(dest) == objects.end()) {
+ DOMWarning("destination object for connection does not exist", el);
+ continue;
+ }
+
+ // add new connection
+ const Connection *const c = new Connection(insertionOrder++, src, dest, prop, *this);
+ src_connections.insert(ConnectionMap::value_type(src, c));
+ dest_connections.insert(ConnectionMap::value_type(dest, c));
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+const std::vector<const AnimationStack *> &Document::AnimationStacks() const {
+ if (!animationStacksResolved.empty() || animationStacks.empty()) {
+ return animationStacksResolved;
+ }
+
+ animationStacksResolved.reserve(animationStacks.size());
+ for (uint64_t id : animationStacks) {
+ LazyObject *lazy = GetObject(id);
+
+ // Two things happen here:
+ // We cast internally an Object PTR to an Animation Stack PTR
+ // We return invalid weak_ptrs for objects which are invalid
+
+ const AnimationStack *stack = lazy->Get<AnimationStack>();
+ ERR_CONTINUE_MSG(!stack, "invalid ptr to AnimationStack - conversion failure");
+
+ // We push back the weak reference :) to keep things simple, as ownership is on the parser side so it wont be cleaned up.
+ animationStacksResolved.push_back(stack);
+ }
+
+ return animationStacksResolved;
+}
+
+// ------------------------------------------------------------------------------------------------
+LazyObject *Document::GetObject(uint64_t id) const {
+ ObjectMap::const_iterator it = objects.find(id);
+ return it == objects.end() ? nullptr : (*it).second;
+}
+
+#define MAX_CLASSNAMES 6
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsSequenced(uint64_t id, const ConnectionMap &conns) const {
+ std::vector<const Connection *> temp;
+
+ const std::pair<ConnectionMap::const_iterator, ConnectionMap::const_iterator> range =
+ conns.equal_range(id);
+
+ temp.reserve(std::distance(range.first, range.second));
+ for (ConnectionMap::const_iterator it = range.first; it != range.second; ++it) {
+ temp.push_back((*it).second);
+ }
+
+ std::sort(temp.begin(), temp.end(), std::mem_fn(&Connection::Compare));
+
+ return temp; // NRVO should handle this
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsSequenced(uint64_t id, bool is_src,
+ const ConnectionMap &conns,
+ const char *const *classnames,
+ size_t count) const
+
+{
+ size_t lengths[MAX_CLASSNAMES];
+
+ const size_t c = count;
+ for (size_t i = 0; i < c; ++i) {
+ lengths[i] = strlen(classnames[i]);
+ }
+
+ std::vector<const Connection *> temp;
+ const std::pair<ConnectionMap::const_iterator, ConnectionMap::const_iterator> range =
+ conns.equal_range(id);
+
+ temp.reserve(std::distance(range.first, range.second));
+ for (ConnectionMap::const_iterator it = range.first; it != range.second; ++it) {
+ TokenPtr key = (is_src ? (*it).second->LazyDestinationObject() : (*it).second->LazySourceObject())->GetElement()->KeyToken();
+
+ const char *obtype = key->begin();
+
+ for (size_t i = 0; i < c; ++i) {
+ //ai_assert(classnames[i]);
+ if (static_cast<size_t>(std::distance(key->begin(), key->end())) == lengths[i] && !strncmp(classnames[i], obtype, lengths[i])) {
+ obtype = nullptr;
+ break;
+ }
+ }
+
+ if (obtype) {
+ continue;
+ }
+
+ temp.push_back((*it).second);
+ }
+
+ std::sort(temp.begin(), temp.end(), std::mem_fn(&Connection::Compare));
+ return temp; // NRVO should handle this
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsBySourceSequenced(uint64_t source) const {
+ return GetConnectionsSequenced(source, ConnectionsBySource());
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsBySourceSequenced(uint64_t src, const char *classname) const {
+ const char *arr[] = { classname };
+ return GetConnectionsBySourceSequenced(src, arr, 1);
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsBySourceSequenced(uint64_t source,
+ const char *const *classnames, size_t count) const {
+ return GetConnectionsSequenced(source, true, ConnectionsBySource(), classnames, count);
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsByDestinationSequenced(uint64_t dest,
+ const char *classname) const {
+ const char *arr[] = { classname };
+ return GetConnectionsByDestinationSequenced(dest, arr, 1);
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsByDestinationSequenced(uint64_t dest) const {
+ return GetConnectionsSequenced(dest, ConnectionsByDestination());
+}
+
+// ------------------------------------------------------------------------------------------------
+std::vector<const Connection *> Document::GetConnectionsByDestinationSequenced(uint64_t dest,
+ const char *const *classnames, size_t count) const {
+ return GetConnectionsSequenced(dest, false, ConnectionsByDestination(), classnames, count);
+}
+
+// ------------------------------------------------------------------------------------------------
+Connection::Connection(uint64_t insertionOrder, uint64_t src, uint64_t dest, const std::string &prop,
+ const Document &doc) :
+ insertionOrder(insertionOrder), prop(prop), src(src), dest(dest), doc(doc) {
+}
+
+// ------------------------------------------------------------------------------------------------
+Connection::~Connection() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+LazyObject *Connection::LazySourceObject() const {
+ LazyObject *const lazy = doc.GetObject(src);
+ return lazy;
+}
+
+// ------------------------------------------------------------------------------------------------
+LazyObject *Connection::LazyDestinationObject() const {
+ LazyObject *const lazy = doc.GetObject(dest);
+ return lazy;
+}
+
+// ------------------------------------------------------------------------------------------------
+Object *Connection::SourceObject() const {
+ LazyObject *lazy = doc.GetObject(src);
+ //ai_assert(lazy);
+ return lazy->LoadObject();
+}
+
+// ------------------------------------------------------------------------------------------------
+Object *Connection::DestinationObject() const {
+ LazyObject *lazy = doc.GetObject(dest);
+ //ai_assert(lazy);
+ return lazy->LoadObject();
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXDocument.h b/modules/fbx/fbx_parser/FBXDocument.h
new file mode 100644
index 0000000000..b810197d7e
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXDocument.h
@@ -0,0 +1,1319 @@
+/*************************************************************************/
+/* FBXDocument.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/** @file FBXDocument.h
+ * @brief FBX DOM
+ */
+#ifndef FBX_DOCUMENT_H
+#define FBX_DOCUMENT_H
+
+#include "FBXCommon.h"
+#include "FBXParser.h"
+#include "FBXProperties.h"
+#include "core/math/transform.h"
+#include "core/math/vector2.h"
+#include "core/math/vector3.h"
+#include "core/string/print_string.h"
+#include <stdint.h>
+#include <numeric>
+
+#define _AI_CONCAT(a, b) a##b
+#define AI_CONCAT(a, b) _AI_CONCAT(a, b)
+
+namespace FBXDocParser {
+
+class Parser;
+class Object;
+struct ImportSettings;
+class Connection;
+
+class PropertyTable;
+class Document;
+class Material;
+class ShapeGeometry;
+class LineGeometry;
+class Geometry;
+
+class Video;
+
+class AnimationCurve;
+class AnimationCurveNode;
+class AnimationLayer;
+class AnimationStack;
+
+class BlendShapeChannel;
+class BlendShape;
+class Skin;
+class Cluster;
+
+typedef Object *ObjectPtr;
+#define new_Object new Object
+
+/** Represents a delay-parsed FBX objects. Many objects in the scene
+ * are not needed by assimp, so it makes no sense to parse them
+ * upfront. */
+class LazyObject {
+public:
+ LazyObject(uint64_t id, const ElementPtr element, const Document &doc);
+ ~LazyObject();
+
+ ObjectPtr LoadObject();
+
+ /* Casting weak pointers to their templated type safely and preserving ref counting and safety
+ * with lock() keyword to prevent leaking memory
+ */
+ template <typename T>
+ const T *Get() {
+ ObjectPtr ob = LoadObject();
+ return dynamic_cast<const T *>(ob);
+ }
+
+ uint64_t ID() const {
+ return id;
+ }
+
+ bool IsBeingConstructed() const {
+ return (flags & BEING_CONSTRUCTED) != 0;
+ }
+
+ bool FailedToConstruct() const {
+ return (flags & FAILED_TO_CONSTRUCT) != 0;
+ }
+
+ ElementPtr GetElement() const {
+ return element;
+ }
+
+ const Document &GetDocument() const {
+ return doc;
+ }
+
+private:
+ const Document &doc;
+ ElementPtr element = nullptr;
+ std::shared_ptr<Object> object = nullptr;
+ const uint64_t id = 0;
+
+ enum Flags {
+ BEING_CONSTRUCTED = 0x1,
+ FAILED_TO_CONSTRUCT = 0x2
+ };
+
+ unsigned int flags = 0;
+};
+
+/** Base class for in-memory (DOM) representations of FBX objects */
+class Object {
+public:
+ Object(uint64_t id, const ElementPtr element, const std::string &name);
+
+ virtual ~Object();
+
+ ElementPtr SourceElement() const {
+ return element;
+ }
+
+ const std::string &Name() const {
+ return name;
+ }
+
+ uint64_t ID() const {
+ return id;
+ }
+
+protected:
+ const ElementPtr element;
+ const std::string name;
+ const uint64_t id = 0;
+};
+
+/** DOM class for generic FBX NoteAttribute blocks. NoteAttribute's just hold a property table,
+ * fixed members are added by deriving classes. */
+class NodeAttribute : public Object {
+public:
+ NodeAttribute(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~NodeAttribute();
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+private:
+ const PropertyTable *props;
+};
+
+/** DOM base class for FBX camera settings attached to a node */
+class CameraSwitcher : public NodeAttribute {
+public:
+ CameraSwitcher(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~CameraSwitcher();
+
+ int CameraID() const {
+ return cameraId;
+ }
+
+ const std::string &CameraName() const {
+ return cameraName;
+ }
+
+ const std::string &CameraIndexName() const {
+ return cameraIndexName;
+ }
+
+private:
+ int cameraId;
+ std::string cameraName;
+ std::string cameraIndexName;
+};
+
+#define fbx_stringize(a) #a
+
+#define fbx_simple_property(name, type, default_value) \
+ type name() const { \
+ return PropertyGet<type>(Props(), fbx_stringize(name), (default_value)); \
+ }
+
+// XXX improve logging
+#define fbx_simple_enum_property(name, type, default_value) \
+ type name() const { \
+ const int ival = PropertyGet<int>(Props(), fbx_stringize(name), static_cast<int>(default_value)); \
+ if (ival < 0 || ival >= AI_CONCAT(type, _MAX)) { \
+ return static_cast<type>(default_value); \
+ } \
+ return static_cast<type>(ival); \
+ }
+
+class FbxPoseNode;
+class FbxPose : public Object {
+public:
+ FbxPose(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ const std::vector<FbxPoseNode *> &GetBindPoses() const {
+ return pose_nodes;
+ }
+
+ virtual ~FbxPose();
+
+private:
+ std::vector<FbxPoseNode *> pose_nodes;
+};
+
+class FbxPoseNode {
+public:
+ FbxPoseNode(const ElementPtr element, const Document &doc, const std::string &name) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ // get pose node transform
+ const ElementPtr Transform = GetRequiredElement(sc, "Matrix", element);
+ transform = ReadMatrix(Transform);
+
+ // get node id this pose node is for
+ const ElementPtr NodeId = sc->GetElement("Node3D");
+ if (NodeId) {
+ target_id = ParseTokenAsInt64(GetRequiredToken(NodeId, 0));
+ }
+
+ print_verbose("added posenode " + itos(target_id) + " transform: " + transform);
+ }
+ virtual ~FbxPoseNode() {
+ }
+
+ uint64_t GetNodeID() const {
+ return target_id;
+ }
+
+ Transform GetBindPose() const {
+ return transform;
+ }
+
+private:
+ uint64_t target_id;
+ Transform transform;
+};
+
+/** DOM base class for FBX cameras attached to a node */
+class Camera : public NodeAttribute {
+public:
+ Camera(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Camera();
+
+ fbx_simple_property(Position, Vector3, Vector3(0, 0, 0));
+ fbx_simple_property(UpVector, Vector3, Vector3(0, 1, 0));
+ fbx_simple_property(InterestPosition, Vector3, Vector3(0, 0, 0));
+
+ fbx_simple_property(AspectWidth, float, 1.0f);
+ fbx_simple_property(AspectHeight, float, 1.0f);
+ fbx_simple_property(FilmWidth, float, 1.0f);
+ fbx_simple_property(FilmHeight, float, 1.0f);
+
+ fbx_simple_property(NearPlane, float, 0.1f);
+ fbx_simple_property(FarPlane, float, 100.0f);
+
+ fbx_simple_property(FilmAspectRatio, float, 1.0f);
+ fbx_simple_property(ApertureMode, int, 0);
+
+ fbx_simple_property(FieldOfView, float, 1.0f);
+ fbx_simple_property(FocalLength, float, 1.0f);
+};
+
+/** DOM base class for FBX null markers attached to a node */
+class Null : public NodeAttribute {
+public:
+ Null(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~Null();
+};
+
+/** DOM base class for FBX limb node markers attached to a node */
+class LimbNode : public NodeAttribute {
+public:
+ LimbNode(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~LimbNode();
+};
+
+/** DOM base class for FBX lights attached to a node */
+class Light : public NodeAttribute {
+public:
+ Light(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~Light();
+
+ enum Type {
+ Type_Point,
+ Type_Directional,
+ Type_Spot,
+ Type_Area,
+ Type_Volume,
+
+ Type_MAX // end-of-enum sentinel
+ };
+
+ enum Decay {
+ Decay_None,
+ Decay_Linear,
+ Decay_Quadratic,
+ Decay_Cubic,
+
+ Decay_MAX // end-of-enum sentinel
+ };
+
+ fbx_simple_property(Color, Vector3, Vector3(1, 1, 1));
+ fbx_simple_enum_property(LightType, Type, 0);
+ fbx_simple_property(CastLightOnObject, bool, false);
+ fbx_simple_property(DrawVolumetricLight, bool, true);
+ fbx_simple_property(DrawGroundProjection, bool, true);
+ fbx_simple_property(DrawFrontFacingVolumetricLight, bool, false);
+ fbx_simple_property(Intensity, float, 100.0f);
+ fbx_simple_property(InnerAngle, float, 0.0f);
+ fbx_simple_property(OuterAngle, float, 45.0f);
+ fbx_simple_property(Fog, int, 50);
+ fbx_simple_enum_property(DecayType, Decay, 2);
+ fbx_simple_property(DecayStart, float, 1.0f);
+ fbx_simple_property(FileName, std::string, "");
+
+ fbx_simple_property(EnableNearAttenuation, bool, false);
+ fbx_simple_property(NearAttenuationStart, float, 0.0f);
+ fbx_simple_property(NearAttenuationEnd, float, 0.0f);
+ fbx_simple_property(EnableFarAttenuation, bool, false);
+ fbx_simple_property(FarAttenuationStart, float, 0.0f);
+ fbx_simple_property(FarAttenuationEnd, float, 0.0f);
+
+ fbx_simple_property(CastShadows, bool, true);
+ fbx_simple_property(ShadowColor, Vector3, Vector3(0, 0, 0));
+
+ fbx_simple_property(AreaLightShape, int, 0);
+
+ fbx_simple_property(LeftBarnDoor, float, 20.0f);
+ fbx_simple_property(RightBarnDoor, float, 20.0f);
+ fbx_simple_property(TopBarnDoor, float, 20.0f);
+ fbx_simple_property(BottomBarnDoor, float, 20.0f);
+ fbx_simple_property(EnableBarnDoor, bool, true);
+};
+
+class Model;
+
+typedef Model *ModelPtr;
+#define new_Model new Model
+
+/** DOM base class for FBX models (even though its semantics are more "node" than "model" */
+class Model : public Object {
+public:
+ enum RotOrder {
+ RotOrder_EulerXYZ = 0,
+ RotOrder_EulerXZY,
+ RotOrder_EulerYZX,
+ RotOrder_EulerYXZ,
+ RotOrder_EulerZXY,
+ RotOrder_EulerZYX,
+
+ RotOrder_SphericXYZ,
+
+ RotOrder_MAX // end-of-enum sentinel
+ };
+
+ Model(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Model();
+
+ fbx_simple_property(QuaternionInterpolate, int, 0);
+
+ fbx_simple_property(RotationOffset, Vector3, Vector3());
+ fbx_simple_property(RotationPivot, Vector3, Vector3());
+ fbx_simple_property(ScalingOffset, Vector3, Vector3());
+ fbx_simple_property(ScalingPivot, Vector3, Vector3());
+ fbx_simple_property(TranslationActive, bool, false);
+ fbx_simple_property(TranslationMin, Vector3, Vector3());
+ fbx_simple_property(TranslationMax, Vector3, Vector3());
+
+ fbx_simple_property(TranslationMinX, bool, false);
+ fbx_simple_property(TranslationMaxX, bool, false);
+ fbx_simple_property(TranslationMinY, bool, false);
+ fbx_simple_property(TranslationMaxY, bool, false);
+ fbx_simple_property(TranslationMinZ, bool, false);
+ fbx_simple_property(TranslationMaxZ, bool, false);
+
+ fbx_simple_enum_property(RotationOrder, RotOrder, 0);
+ fbx_simple_property(RotationSpaceForLimitOnly, bool, false);
+ fbx_simple_property(RotationStiffnessX, float, 0.0f);
+ fbx_simple_property(RotationStiffnessY, float, 0.0f);
+ fbx_simple_property(RotationStiffnessZ, float, 0.0f);
+ fbx_simple_property(AxisLen, float, 0.0f);
+
+ fbx_simple_property(PreRotation, Vector3, Vector3());
+ fbx_simple_property(PostRotation, Vector3, Vector3());
+ fbx_simple_property(RotationActive, bool, false);
+
+ fbx_simple_property(RotationMin, Vector3, Vector3());
+ fbx_simple_property(RotationMax, Vector3, Vector3());
+
+ fbx_simple_property(RotationMinX, bool, false);
+ fbx_simple_property(RotationMaxX, bool, false);
+ fbx_simple_property(RotationMinY, bool, false);
+ fbx_simple_property(RotationMaxY, bool, false);
+ fbx_simple_property(RotationMinZ, bool, false);
+ fbx_simple_property(RotationMaxZ, bool, false);
+ fbx_simple_enum_property(InheritType, TransformInheritance, 0);
+
+ fbx_simple_property(ScalingActive, bool, false);
+ fbx_simple_property(ScalingMin, Vector3, Vector3());
+ fbx_simple_property(ScalingMax, Vector3, Vector3(1, 1, 1));
+ fbx_simple_property(ScalingMinX, bool, false);
+ fbx_simple_property(ScalingMaxX, bool, false);
+ fbx_simple_property(ScalingMinY, bool, false);
+ fbx_simple_property(ScalingMaxY, bool, false);
+ fbx_simple_property(ScalingMinZ, bool, false);
+ fbx_simple_property(ScalingMaxZ, bool, false);
+
+ fbx_simple_property(GeometricTranslation, Vector3, Vector3());
+ fbx_simple_property(GeometricRotation, Vector3, Vector3());
+ fbx_simple_property(GeometricScaling, Vector3, Vector3(1, 1, 1));
+
+ fbx_simple_property(MinDampRangeX, float, 0.0f);
+ fbx_simple_property(MinDampRangeY, float, 0.0f);
+ fbx_simple_property(MinDampRangeZ, float, 0.0f);
+ fbx_simple_property(MaxDampRangeX, float, 0.0f);
+ fbx_simple_property(MaxDampRangeY, float, 0.0f);
+ fbx_simple_property(MaxDampRangeZ, float, 0.0f);
+
+ fbx_simple_property(MinDampStrengthX, float, 0.0f);
+ fbx_simple_property(MinDampStrengthY, float, 0.0f);
+ fbx_simple_property(MinDampStrengthZ, float, 0.0f);
+ fbx_simple_property(MaxDampStrengthX, float, 0.0f);
+ fbx_simple_property(MaxDampStrengthY, float, 0.0f);
+ fbx_simple_property(MaxDampStrengthZ, float, 0.0f);
+
+ fbx_simple_property(PreferredAngleX, float, 0.0f);
+ fbx_simple_property(PreferredAngleY, float, 0.0f);
+ fbx_simple_property(PreferredAngleZ, float, 0.0f);
+
+ fbx_simple_property(Show, bool, true);
+ fbx_simple_property(LODBox, bool, false);
+ fbx_simple_property(Freeze, bool, false);
+
+ const std::string &Shading() const {
+ return shading;
+ }
+
+ const std::string &Culling() const {
+ return culling;
+ }
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ /** Get material links */
+ const std::vector<const Material *> &GetMaterials() const {
+ return materials;
+ }
+
+ /** Get geometry links */
+ const std::vector<const Geometry *> &GetGeometry() const {
+ return geometry;
+ }
+
+ /** Get node attachments */
+ const std::vector<const NodeAttribute *> &GetAttributes() const {
+ return attributes;
+ }
+
+ /** convenience method to check if the node has a Null node marker */
+ bool IsNull() const;
+
+private:
+ void ResolveLinks(const ElementPtr element, const Document &doc);
+
+private:
+ std::vector<const Material *> materials;
+ std::vector<const Geometry *> geometry;
+ std::vector<const NodeAttribute *> attributes;
+
+ std::string shading;
+ std::string culling;
+ const PropertyTable *props = nullptr;
+};
+
+class ModelLimbNode : public Model {
+public:
+ ModelLimbNode(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~ModelLimbNode();
+};
+
+/** DOM class for generic FBX textures */
+class Texture : public Object {
+public:
+ Texture(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Texture();
+
+ const std::string &Type() const {
+ return type;
+ }
+
+ const std::string &FileName() const {
+ return fileName;
+ }
+
+ const std::string &RelativeFilename() const {
+ return relativeFileName;
+ }
+
+ const std::string &AlphaSource() const {
+ return alphaSource;
+ }
+
+ const Vector2 &UVTranslation() const {
+ return uvTrans;
+ }
+
+ const Vector2 &UVScaling() const {
+ return uvScaling;
+ }
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ // return a 4-tuple
+ const unsigned int *Crop() const {
+ return crop;
+ }
+
+ const Video *Media() const {
+ return media;
+ }
+
+private:
+ Vector2 uvTrans;
+ Vector2 uvScaling;
+
+ std::string type;
+ std::string relativeFileName;
+ std::string fileName;
+ std::string alphaSource;
+ const PropertyTable *props = nullptr;
+
+ unsigned int crop[4] = { 0 };
+
+ const Video *media = nullptr;
+};
+
+/** DOM class for layered FBX textures */
+class LayeredTexture : public Object {
+public:
+ LayeredTexture(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~LayeredTexture();
+
+ // Can only be called after construction of the layered texture object due to construction flag.
+ void fillTexture(const Document &doc);
+
+ enum BlendMode {
+ BlendMode_Translucent,
+ BlendMode_Additive,
+ BlendMode_Modulate,
+ BlendMode_Modulate2,
+ BlendMode_Over,
+ BlendMode_Normal,
+ BlendMode_Dissolve,
+ BlendMode_Darken,
+ BlendMode_ColorBurn,
+ BlendMode_LinearBurn,
+ BlendMode_DarkerColor,
+ BlendMode_Lighten,
+ BlendMode_Screen,
+ BlendMode_ColorDodge,
+ BlendMode_LinearDodge,
+ BlendMode_LighterColor,
+ BlendMode_SoftLight,
+ BlendMode_HardLight,
+ BlendMode_VividLight,
+ BlendMode_LinearLight,
+ BlendMode_PinLight,
+ BlendMode_HardMix,
+ BlendMode_Difference,
+ BlendMode_Exclusion,
+ BlendMode_Subtract,
+ BlendMode_Divide,
+ BlendMode_Hue,
+ BlendMode_Saturation,
+ BlendMode_Color,
+ BlendMode_Luminosity,
+ BlendMode_Overlay,
+ BlendMode_BlendModeCount
+ };
+
+ const Texture *getTexture(int index = 0) const {
+ return textures[index];
+ }
+ int textureCount() const {
+ return static_cast<int>(textures.size());
+ }
+ BlendMode GetBlendMode() const {
+ return blendMode;
+ }
+ float Alpha() {
+ return alpha;
+ }
+
+private:
+ std::vector<const Texture *> textures;
+ BlendMode blendMode;
+ float alpha;
+};
+
+typedef std::map<std::string, const Texture *> TextureMap;
+typedef std::map<std::string, const LayeredTexture *> LayeredTextureMap;
+
+/** DOM class for generic FBX videos */
+class Video : public Object {
+public:
+ Video(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Video();
+
+ const std::string &Type() const {
+ return type;
+ }
+
+ bool IsEmbedded() const {
+ return contentLength > 0;
+ }
+
+ const std::string &FileName() const {
+ return fileName;
+ }
+
+ const std::string &RelativeFilename() const {
+ return relativeFileName;
+ }
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ const uint8_t *Content() const {
+ return content;
+ }
+
+ uint64_t ContentLength() const {
+ return contentLength;
+ }
+
+ uint8_t *RelinquishContent() {
+ uint8_t *ptr = content;
+ content = 0;
+ return ptr;
+ }
+
+ bool operator==(const Video &other) const {
+ return (
+ type == other.type && relativeFileName == other.relativeFileName && fileName == other.fileName);
+ }
+
+ bool operator<(const Video &other) const {
+ return std::tie(type, relativeFileName, fileName) < std::tie(other.type, other.relativeFileName, other.fileName);
+ }
+
+private:
+ std::string type;
+ std::string relativeFileName;
+ std::string fileName;
+ const PropertyTable *props = nullptr;
+
+ uint64_t contentLength = 0;
+ uint8_t *content = nullptr;
+};
+
+/** DOM class for generic FBX materials */
+class Material : public Object {
+public:
+ Material(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Material();
+
+ const std::string &GetShadingModel() const {
+ return shading;
+ }
+
+ bool IsMultilayer() const {
+ return multilayer;
+ }
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ const TextureMap &Textures() const {
+ return textures;
+ }
+
+ const LayeredTextureMap &LayeredTextures() const {
+ return layeredTextures;
+ }
+
+private:
+ std::string shading;
+ bool multilayer;
+ const PropertyTable *props;
+
+ TextureMap textures;
+ LayeredTextureMap layeredTextures;
+};
+
+// signed int keys (this can happen!)
+typedef std::vector<int64_t> KeyTimeList;
+typedef std::vector<float> KeyValueList;
+
+/** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefor) */
+class AnimationCurve : public Object {
+public:
+ AnimationCurve(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+ virtual ~AnimationCurve();
+
+ /** get list of keyframe positions (time).
+ * Invariant: |GetKeys()| > 0 */
+ const KeyTimeList &GetKeys() const {
+ return keys;
+ }
+
+ /** get list of keyframe values.
+ * Invariant: |GetKeys()| == |GetValues()| && |GetKeys()| > 0*/
+ const KeyValueList &GetValues() const {
+ return values;
+ }
+
+ const std::map<int64_t, float> &GetValueTimeTrack() const {
+ return keyvalues;
+ }
+
+ const std::vector<float> &GetAttributes() const {
+ return attributes;
+ }
+
+ const std::vector<unsigned int> &GetFlags() const {
+ return flags;
+ }
+
+private:
+ KeyTimeList keys;
+ KeyValueList values;
+ std::vector<float> attributes;
+ std::map<int64_t, float> keyvalues;
+ std::vector<unsigned int> flags;
+};
+
+/* Typedef for pointers for the animation handler */
+typedef std::shared_ptr<AnimationCurve> AnimationCurvePtr;
+typedef std::weak_ptr<AnimationCurve> AnimationCurveWeakPtr;
+typedef std::map<std::string, const AnimationCurve *> AnimationMap;
+
+/* Animation Curve node ptr */
+typedef std::shared_ptr<AnimationCurveNode> AnimationCurveNodePtr;
+typedef std::weak_ptr<AnimationCurveNode> AnimationCurveNodeWeakPtr;
+
+/** Represents a FBX animation curve (i.e. a mapping from single animation curves to nodes) */
+class AnimationCurveNode : public Object {
+public:
+ /* the optional white list specifies a list of property names for which the caller
+ wants animations for. If the curve node does not match one of these, std::range_error
+ will be thrown. */
+ AnimationCurveNode(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc,
+ const char *const *target_prop_whitelist = nullptr, size_t whitelist_size = 0);
+
+ virtual ~AnimationCurveNode();
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ const AnimationMap &Curves() const;
+
+ /** Object the curve is assigned to, this can be NULL if the
+ * target object has no DOM representation or could not
+ * be read for other reasons.*/
+ Object *Target() const {
+ return target;
+ }
+
+ Model *TargetAsModel() const {
+ return dynamic_cast<Model *>(target);
+ }
+
+ NodeAttribute *TargetAsNodeAttribute() const {
+ return dynamic_cast<NodeAttribute *>(target);
+ }
+
+ /** Property of Target() that is being animated*/
+ const std::string &TargetProperty() const {
+ return prop;
+ }
+
+private:
+ Object *target = nullptr;
+ const PropertyTable *props;
+ mutable AnimationMap curves;
+ std::string prop;
+ const Document &doc;
+};
+
+typedef std::vector<const AnimationCurveNode *> AnimationCurveNodeList;
+
+typedef std::shared_ptr<AnimationLayer> AnimationLayerPtr;
+typedef std::weak_ptr<AnimationLayer> AnimationLayerWeakPtr;
+typedef std::vector<const AnimationLayer *> AnimationLayerList;
+
+/** Represents a FBX animation layer (i.e. a list of node animations) */
+class AnimationLayer : public Object {
+public:
+ AnimationLayer(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+ virtual ~AnimationLayer();
+
+ const PropertyTable *Props() const {
+ //ai_assert(props.get());
+ return props;
+ }
+
+ /* the optional white list specifies a list of property names for which the caller
+ wants animations for. Curves not matching this list will not be added to the
+ animation layer. */
+ const AnimationCurveNodeList Nodes(const char *const *target_prop_whitelist = nullptr, size_t whitelist_size = 0) const;
+
+private:
+ const PropertyTable *props;
+ const Document &doc;
+};
+
+/** Represents a FBX animation stack (i.e. a list of animation layers) */
+class AnimationStack : public Object {
+public:
+ AnimationStack(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+ virtual ~AnimationStack();
+
+ fbx_simple_property(LocalStart, int64_t, 0L);
+ fbx_simple_property(LocalStop, int64_t, 0L);
+ fbx_simple_property(ReferenceStart, int64_t, 0L);
+ fbx_simple_property(ReferenceStop, int64_t, 0L);
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ const AnimationLayerList &Layers() const {
+ return layers;
+ }
+
+private:
+ const PropertyTable *props = nullptr;
+ AnimationLayerList layers;
+};
+
+/** DOM class for deformers */
+class Deformer : public Object {
+public:
+ Deformer(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~Deformer();
+
+ const PropertyTable *Props() const {
+ //ai_assert(props.get());
+ return props;
+ }
+
+private:
+ const PropertyTable *props;
+};
+
+/** Constraints are from Maya they can help us with BoneAttachments :) **/
+class Constraint : public Object {
+public:
+ Constraint(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+ virtual ~Constraint();
+
+private:
+ const PropertyTable *props;
+};
+
+typedef std::vector<float> WeightArray;
+typedef std::vector<unsigned int> WeightIndexArray;
+
+/** DOM class for BlendShapeChannel deformers */
+class BlendShapeChannel : public Deformer {
+public:
+ BlendShapeChannel(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~BlendShapeChannel();
+
+ float DeformPercent() const {
+ return percent;
+ }
+
+ const WeightArray &GetFullWeights() const {
+ return fullWeights;
+ }
+
+ const std::vector<const ShapeGeometry *> &GetShapeGeometries() const {
+ return shapeGeometries;
+ }
+
+private:
+ float percent;
+ WeightArray fullWeights;
+ std::vector<const ShapeGeometry *> shapeGeometries;
+};
+
+/** DOM class for BlendShape deformers */
+class BlendShape : public Deformer {
+public:
+ BlendShape(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~BlendShape();
+
+ const std::vector<const BlendShapeChannel *> &BlendShapeChannels() const {
+ return blendShapeChannels;
+ }
+
+private:
+ std::vector<const BlendShapeChannel *> blendShapeChannels;
+};
+
+/** DOM class for skin deformer clusters (aka sub-deformers) */
+class Cluster : public Deformer {
+public:
+ Cluster(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Cluster();
+
+ /** get the list of deformer weights associated with this cluster.
+ * Use #GetIndices() to get the associated vertices. Both arrays
+ * have the same size (and may also be empty). */
+ const std::vector<float> &GetWeights() const {
+ return weights;
+ }
+
+ /** get indices into the vertex data of the geometry associated
+ * with this cluster. Use #GetWeights() to get the associated weights.
+ * Both arrays have the same size (and may also be empty). */
+ const std::vector<unsigned int> &GetIndices() const {
+ return indices;
+ }
+
+ /** */
+ const Transform &GetTransform() const {
+ return transform;
+ }
+
+ const Transform &TransformLink() const {
+ return transformLink;
+ }
+
+ const Model *TargetNode() const {
+ return node;
+ }
+
+ const Transform &TransformAssociateModel() const {
+ return transformAssociateModel;
+ }
+
+ bool TransformAssociateModelValid() const {
+ return valid_transformAssociateModel;
+ }
+
+ // property is not in the fbx file
+ // if the cluster has an associate model
+ // we then have an additive type
+ enum SkinLinkMode {
+ SkinLinkMode_Normalized = 0,
+ SkinLinkMode_Additive = 1
+ };
+
+ SkinLinkMode GetLinkMode() {
+ return link_mode;
+ }
+
+private:
+ std::vector<float> weights;
+ std::vector<unsigned int> indices;
+
+ Transform transform;
+ Transform transformLink;
+ Transform transformAssociateModel;
+ SkinLinkMode link_mode;
+ bool valid_transformAssociateModel;
+ const Model *node = nullptr;
+};
+
+/** DOM class for skin deformers */
+class Skin : public Deformer {
+public:
+ Skin(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name);
+
+ virtual ~Skin();
+
+ float DeformAccuracy() const {
+ return accuracy;
+ }
+
+ const std::vector<const Cluster *> &Clusters() const {
+ return clusters;
+ }
+
+ enum SkinType {
+ Skin_Rigid = 0,
+ Skin_Linear,
+ Skin_DualQuaternion,
+ Skin_Blend
+ };
+
+ const SkinType &GetSkinType() const {
+ return skinType;
+ }
+
+private:
+ float accuracy;
+ SkinType skinType;
+ std::vector<const Cluster *> clusters;
+};
+
+/** Represents a link between two FBX objects. */
+class Connection {
+public:
+ Connection(uint64_t insertionOrder, uint64_t src, uint64_t dest, const std::string &prop, const Document &doc);
+ ~Connection();
+
+ // note: a connection ensures that the source and dest objects exist, but
+ // not that they have DOM representations, so the return value of one of
+ // these functions can still be NULL.
+ Object *SourceObject() const;
+ Object *DestinationObject() const;
+
+ // these, however, are always guaranteed to be valid
+ LazyObject *LazySourceObject() const;
+ LazyObject *LazyDestinationObject() const;
+
+ /** return the name of the property the connection is attached to.
+ * this is an empty string for object to object (OO) connections. */
+ const std::string &PropertyName() const {
+ return prop;
+ }
+
+ uint64_t InsertionOrder() const {
+ return insertionOrder;
+ }
+
+ int CompareTo(const Connection *c) const {
+ //ai_assert(nullptr != c);
+
+ // note: can't subtract because this would overflow uint64_t
+ if (InsertionOrder() > c->InsertionOrder()) {
+ return 1;
+ } else if (InsertionOrder() < c->InsertionOrder()) {
+ return -1;
+ }
+ return 0;
+ }
+
+ bool Compare(const Connection *c) const {
+ //ai_assert(nullptr != c);
+
+ return InsertionOrder() < c->InsertionOrder();
+ }
+
+public:
+ uint64_t insertionOrder;
+ const std::string prop;
+
+ uint64_t src, dest;
+ const Document &doc;
+};
+
+// XXX again, unique_ptr would be useful. shared_ptr is too
+// bloated since the objects have a well-defined single owner
+// during their entire lifetime (Document). FBX files have
+// up to many thousands of objects (most of which we never use),
+// so the memory overhead for them should be kept at a minimum.
+typedef std::map<uint64_t, LazyObject *> ObjectMap;
+typedef std::map<std::string, const PropertyTable *> PropertyTemplateMap;
+typedef std::multimap<uint64_t, const Connection *> ConnectionMap;
+
+/** DOM class for global document settings, a single instance per document can
+ * be accessed via Document.Globals(). */
+class FileGlobalSettings {
+public:
+ FileGlobalSettings(const Document &doc, const PropertyTable *props);
+
+ ~FileGlobalSettings();
+
+ const PropertyTable *Props() const {
+ return props;
+ }
+
+ const Document &GetDocument() const {
+ return doc;
+ }
+
+ fbx_simple_property(UpAxis, int, 1);
+ fbx_simple_property(UpAxisSign, int, 1);
+ fbx_simple_property(FrontAxis, int, 2);
+ fbx_simple_property(FrontAxisSign, int, 1);
+ fbx_simple_property(CoordAxis, int, 0);
+ fbx_simple_property(CoordAxisSign, int, 1);
+ fbx_simple_property(OriginalUpAxis, int, 0);
+ fbx_simple_property(OriginalUpAxisSign, int, 1);
+ fbx_simple_property(UnitScaleFactor, float, 1);
+ fbx_simple_property(OriginalUnitScaleFactor, float, 1);
+ fbx_simple_property(AmbientColor, Vector3, Vector3(0, 0, 0));
+ fbx_simple_property(DefaultCamera, std::string, "");
+
+ enum FrameRate {
+ FrameRate_DEFAULT = 0,
+ FrameRate_120 = 1,
+ FrameRate_100 = 2,
+ FrameRate_60 = 3,
+ FrameRate_50 = 4,
+ FrameRate_48 = 5,
+ FrameRate_30 = 6,
+ FrameRate_30_DROP = 7,
+ FrameRate_NTSC_DROP_FRAME = 8,
+ FrameRate_NTSC_FULL_FRAME = 9,
+ FrameRate_PAL = 10,
+ FrameRate_CINEMA = 11,
+ FrameRate_1000 = 12,
+ FrameRate_CINEMA_ND = 13,
+ FrameRate_CUSTOM = 14,
+
+ FrameRate_MAX // end-of-enum sentinel
+ };
+
+ fbx_simple_enum_property(TimeMode, FrameRate, FrameRate_DEFAULT);
+ fbx_simple_property(TimeSpanStart, uint64_t, 0L);
+ fbx_simple_property(TimeSpanStop, uint64_t, 0L);
+ fbx_simple_property(CustomFrameRate, float, -1.0f);
+
+private:
+ const PropertyTable *props = nullptr;
+ const Document &doc;
+};
+
+/** DOM root for a FBX file */
+class Document {
+public:
+ Document(const Parser &parser, const ImportSettings &settings);
+
+ ~Document();
+
+ LazyObject *GetObject(uint64_t id) const;
+
+ bool IsSafeToImport() const {
+ return SafeToImport;
+ }
+
+ bool IsBinary() const {
+ return parser.IsBinary();
+ }
+
+ unsigned int FBXVersion() const {
+ return fbxVersion;
+ }
+
+ const std::string &Creator() const {
+ return creator;
+ }
+
+ // elements (in this order): Year, Month, Day, Hour, Second, Millisecond
+ const unsigned int *CreationTimeStamp() const {
+ return creationTimeStamp;
+ }
+
+ const FileGlobalSettings *GlobalSettingsPtr() const {
+ return globals.get();
+ }
+
+ const PropertyTable *GetMetadataProperties() const {
+ return metadata_properties;
+ }
+
+ const PropertyTemplateMap &Templates() const {
+ return templates;
+ }
+
+ const ObjectMap &Objects() const {
+ return objects;
+ }
+
+ const ImportSettings &Settings() const {
+ return settings;
+ }
+
+ const ConnectionMap &ConnectionsBySource() const {
+ return src_connections;
+ }
+
+ const ConnectionMap &ConnectionsByDestination() const {
+ return dest_connections;
+ }
+
+ // note: the implicit rule in all DOM classes is to always resolve
+ // from destination to source (since the FBX object hierarchy is,
+ // with very few exceptions, a DAG, this avoids cycles). In all
+ // cases that may involve back-facing edges in the object graph,
+ // use LazyObject::IsBeingConstructed() to check.
+
+ std::vector<const Connection *> GetConnectionsBySourceSequenced(uint64_t source) const;
+ std::vector<const Connection *> GetConnectionsByDestinationSequenced(uint64_t dest) const;
+
+ std::vector<const Connection *> GetConnectionsBySourceSequenced(uint64_t source, const char *classname) const;
+ std::vector<const Connection *> GetConnectionsByDestinationSequenced(uint64_t dest, const char *classname) const;
+
+ std::vector<const Connection *> GetConnectionsBySourceSequenced(uint64_t source,
+ const char *const *classnames, size_t count) const;
+ std::vector<const Connection *> GetConnectionsByDestinationSequenced(uint64_t dest,
+ const char *const *classnames,
+ size_t count) const;
+
+ const std::vector<const AnimationStack *> &AnimationStacks() const;
+ const std::vector<uint64_t> &GetAnimationStackIDs() const {
+ return animationStacks;
+ }
+
+ const std::vector<uint64_t> &GetConstraintStackIDs() const {
+ return constraints;
+ }
+
+ const std::vector<uint64_t> &GetBindPoseIDs() const {
+ return bind_poses;
+ };
+
+ const std::vector<uint64_t> &GetMaterialIDs() const {
+ return materials;
+ };
+
+ const std::vector<uint64_t> &GetSkinIDs() const {
+ return skins;
+ }
+
+private:
+ std::vector<const Connection *> GetConnectionsSequenced(uint64_t id, const ConnectionMap &) const;
+ std::vector<const Connection *> GetConnectionsSequenced(uint64_t id, bool is_src,
+ const ConnectionMap &,
+ const char *const *classnames,
+ size_t count) const;
+ bool ReadHeader();
+ void ReadObjects();
+ void ReadPropertyTemplates();
+ void ReadConnections();
+ void ReadGlobalSettings();
+
+private:
+ const ImportSettings &settings;
+
+ ObjectMap objects;
+ const Parser &parser;
+ bool SafeToImport = false;
+
+ PropertyTemplateMap templates;
+ ConnectionMap src_connections;
+ ConnectionMap dest_connections;
+
+ unsigned int fbxVersion = 0;
+ std::string creator;
+ unsigned int creationTimeStamp[7] = { 0 };
+
+ std::vector<uint64_t> animationStacks;
+ std::vector<uint64_t> bind_poses;
+ // constraints aren't in the tree / at least they are not easy to access.
+ std::vector<uint64_t> constraints;
+ std::vector<uint64_t> materials;
+ std::vector<uint64_t> skins;
+ mutable std::vector<const AnimationStack *> animationStacksResolved;
+ PropertyTable *metadata_properties = nullptr;
+ std::shared_ptr<FileGlobalSettings> globals = nullptr;
+};
+} // namespace FBXDocParser
+
+namespace std {
+template <>
+struct hash<const FBXDocParser::Video> {
+ std::size_t operator()(const FBXDocParser::Video &video) const {
+ using std::hash;
+ using std::size_t;
+ using std::string;
+
+ size_t res = 17;
+ res = res * 31 + hash<string>()(video.Name());
+ res = res * 31 + hash<string>()(video.RelativeFilename());
+ res = res * 31 + hash<string>()(video.Type());
+
+ return res;
+ }
+};
+} // namespace std
+
+#endif // FBX_DOCUMENT_H
diff --git a/modules/fbx/fbx_parser/FBXDocumentUtil.cpp b/modules/fbx/fbx_parser/FBXDocumentUtil.cpp
new file mode 100644
index 0000000000..835b66ab23
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXDocumentUtil.cpp
@@ -0,0 +1,172 @@
+/*************************************************************************/
+/* FBXDocumentUtil.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXDocumentUtil.cpp
+ * @brief Implementation of the FBX DOM utility functions declared in FBXDocumentUtil.h
+ */
+
+#include "FBXDocumentUtil.h"
+#include "FBXDocument.h"
+#include "FBXParser.h"
+#include "FBXProperties.h"
+#include "FBXUtil.h"
+#include "core/string/print_string.h"
+
+namespace FBXDocParser {
+namespace Util {
+
+void DOMError(const std::string &message) {
+ print_error("[FBX-DOM]" + String(message.c_str()));
+}
+
+void DOMError(const std::string &message, const Token *token) {
+ print_error("[FBX-DOM]" + String(message.c_str()) + ";" + String(token->StringContents().c_str()));
+}
+
+void DOMError(const std::string &message, const std::shared_ptr<Token> token) {
+ print_error("[FBX-DOM]" + String(message.c_str()) + ";" + String(token->StringContents().c_str()));
+}
+
+void DOMError(const std::string &message, const Element *element /*= NULL*/) {
+ if (element) {
+ DOMError(message, element->KeyToken());
+ }
+ print_error("[FBX-DOM] " + String(message.c_str()));
+}
+
+void DOMError(const std::string &message, const std::shared_ptr<Element> element /*= NULL*/) {
+ if (element) {
+ DOMError(message, element->KeyToken());
+ }
+ print_error("[FBX-DOM] " + String(message.c_str()));
+}
+
+void DOMWarning(const std::string &message) {
+ print_verbose("[FBX-DOM] warning:" + String(message.c_str()));
+}
+
+void DOMWarning(const std::string &message, const Token *token) {
+ print_verbose("[FBX-DOM] warning:" + String(message.c_str()) + ";" + String(token->StringContents().c_str()));
+}
+
+void DOMWarning(const std::string &message, const Element *element /*= NULL*/) {
+ if (element) {
+ DOMWarning(message, element->KeyToken());
+ return;
+ }
+ print_verbose("[FBX-DOM] warning:" + String(message.c_str()));
+}
+
+void DOMWarning(const std::string &message, const std::shared_ptr<Token> token) {
+ print_verbose("[FBX-DOM] warning:" + String(message.c_str()) + ";" + String(token->StringContents().c_str()));
+}
+
+void DOMWarning(const std::string &message, const std::shared_ptr<Element> element /*= NULL*/) {
+ if (element) {
+ DOMWarning(message, element->KeyToken());
+ return;
+ }
+ print_verbose("[FBX-DOM] warning:" + String(message.c_str()));
+}
+
+// ------------------------------------------------------------------------------------------------
+// fetch a property table and the corresponding property template
+const PropertyTable *GetPropertyTable(const Document &doc,
+ const std::string &templateName,
+ const ElementPtr element,
+ const ScopePtr sc,
+ bool no_warn /*= false*/) {
+ // todo: make this an abstraction
+ const ElementPtr Properties70 = sc->GetElement("Properties70");
+ const PropertyTable *templateProps = static_cast<const PropertyTable *>(nullptr);
+
+ if (templateName.length()) {
+ PropertyTemplateMap::const_iterator it = doc.Templates().find(templateName);
+ if (it != doc.Templates().end()) {
+ templateProps = (*it).second;
+ }
+ }
+
+ if (!Properties70 || !Properties70->Compound()) {
+ if (!no_warn) {
+ DOMWarning("property table (Properties70) not found", element);
+ }
+ if (templateProps) {
+ return templateProps;
+ } else {
+ return new const PropertyTable();
+ }
+ }
+
+ return new PropertyTable(Properties70, templateProps);
+}
+} // namespace Util
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXDocumentUtil.h b/modules/fbx/fbx_parser/FBXDocumentUtil.h
new file mode 100644
index 0000000000..daa9de4a33
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXDocumentUtil.h
@@ -0,0 +1,141 @@
+/*************************************************************************/
+/* FBXDocumentUtil.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2012, assimp team
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXDocumentUtil.h
+ * @brief FBX internal utilities used by the DOM reading code
+ */
+#ifndef FBX_DOCUMENT_UTIL_H
+#define FBX_DOCUMENT_UTIL_H
+
+#include "FBXDocument.h"
+#include <memory>
+#include <string>
+
+struct Token;
+struct Element;
+
+namespace FBXDocParser {
+namespace Util {
+
+// Parser errors
+void DOMError(const std::string &message);
+void DOMError(const std::string &message, const Token *token);
+void DOMError(const std::string &message, const Element *element);
+void DOMError(const std::string &message, const std::shared_ptr<Element> element);
+void DOMError(const std::string &message, const std::shared_ptr<Token> token);
+
+// Parser warnings
+void DOMWarning(const std::string &message);
+void DOMWarning(const std::string &message, const Token *token);
+void DOMWarning(const std::string &message, const Element *element);
+void DOMWarning(const std::string &message, const std::shared_ptr<Token> token);
+void DOMWarning(const std::string &message, const std::shared_ptr<Element> element);
+
+// fetch a property table and the corresponding property template
+const PropertyTable *GetPropertyTable(const Document &doc,
+ const std::string &templateName,
+ const ElementPtr element,
+ const ScopePtr sc,
+ bool no_warn = false);
+
+// ------------------------------------------------------------------------------------------------
+template <typename T>
+const T *ProcessSimpleConnection(const Connection &con,
+ bool is_object_property_conn,
+ const char *name,
+ const ElementPtr element,
+ const char **propNameOut = nullptr) {
+ if (is_object_property_conn && !con.PropertyName().length()) {
+ DOMWarning("expected incoming " + std::string(name) +
+ " link to be an object-object connection, ignoring",
+ element);
+ return nullptr;
+ } else if (!is_object_property_conn && con.PropertyName().length()) {
+ DOMWarning("expected incoming " + std::string(name) +
+ " link to be an object-property connection, ignoring",
+ element);
+ return nullptr;
+ }
+
+ if (is_object_property_conn && propNameOut) {
+ // note: this is ok, the return value of PropertyValue() is guaranteed to
+ // remain valid and unchanged as long as the document exists.
+ *propNameOut = con.PropertyName().c_str();
+ }
+
+ // Cast Object to AnimationPlayer for example using safe functions, which return nullptr etc
+ Object *ob = con.SourceObject();
+ ERR_FAIL_COND_V_MSG(!ob, nullptr, "Failed to load object from SourceObject ptr");
+ return dynamic_cast<const T *>(ob);
+}
+} // namespace Util
+} // namespace FBXDocParser
+
+#endif // FBX_DOCUMENT_UTIL_H
diff --git a/modules/fbx/fbx_parser/FBXImportSettings.h b/modules/fbx/fbx_parser/FBXImportSettings.h
new file mode 100644
index 0000000000..97ce496eaf
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXImportSettings.h
@@ -0,0 +1,173 @@
+/*************************************************************************/
+/* FBXImportSettings.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXImportSettings.h
+ * @brief FBX importer runtime configuration
+ */
+#ifndef FBX_IMPORT_SETTINGS_H
+#define FBX_IMPORT_SETTINGS_H
+
+namespace FBXDocParser {
+
+/** FBX import settings, parts of which are publicly accessible via their corresponding AI_CONFIG constants */
+struct ImportSettings {
+ ImportSettings() :
+ strictMode(true), readAllLayers(true), readAllMaterials(true), readMaterials(true), readTextures(true), readCameras(true), readLights(true), readAnimations(true), readWeights(true), preservePivots(true), optimizeEmptyAnimationCurves(true), useLegacyEmbeddedTextureNaming(false), removeEmptyBones(true), convertToMeters(false) {
+ // empty
+ }
+
+ /** enable strict mode:
+ * - only accept fbx 2012, 2013 files
+ * - on the slightest error, give up.
+ *
+ * Basically, strict mode means that the fbx file will actually
+ * be validated. Strict mode is off by default. */
+ bool strictMode;
+
+ /** specifies whether all geometry layers are read and scanned for
+ * usable data channels. The FBX spec indicates that many readers
+ * will only read the first channel and that this is in some way
+ * the recommended way- in reality, however, it happens a lot that
+ * vertex data is spread among multiple layers. The default
+ * value for this option is true.*/
+ bool readAllLayers;
+
+ /** specifies whether all materials are read, or only those that
+ * are referenced by at least one mesh. Reading all materials
+ * may make FBX reading a lot slower since all objects
+ * need to be processed .
+ * This bit is ignored unless readMaterials=true*/
+ bool readAllMaterials;
+
+ /** import materials (true) or skip them and assign a default
+ * material. The default value is true.*/
+ bool readMaterials;
+
+ /** import embedded textures? Default value is true.*/
+ bool readTextures;
+
+ /** import cameras? Default value is true.*/
+ bool readCameras;
+
+ /** import light sources? Default value is true.*/
+ bool readLights;
+
+ /** import animations (i.e. animation curves, the node
+ * skeleton is always imported). Default value is true. */
+ bool readAnimations;
+
+ /** read bones (vertex weights and deform info).
+ * Default value is true. */
+ bool readWeights;
+
+ /** preserve transformation pivots and offsets. Since these can
+ * not directly be represented in assimp, additional dummy
+ * nodes will be generated. Note that settings this to false
+ * can make animation import a lot slower. The default value
+ * is true.
+ *
+ * The naming scheme for the generated nodes is:
+ * <OriginalName>_$AssimpFbx$_<TransformName>
+ *
+ * where <TransformName> is one of
+ * RotationPivot
+ * RotationOffset
+ * PreRotation
+ * PostRotation
+ * ScalingPivot
+ * ScalingOffset
+ * Translation
+ * Scaling
+ * Rotation
+ **/
+ bool preservePivots;
+
+ /** do not import animation curves that specify a constant
+ * values matching the corresponding node transformation.
+ * The default value is true. */
+ bool optimizeEmptyAnimationCurves;
+
+ /** use legacy naming for embedded textures eg: (*0, *1, *2)
+ */
+ bool useLegacyEmbeddedTextureNaming;
+
+ /** Empty bones shall be removed
+ */
+ bool removeEmptyBones;
+
+ /** Set to true to perform a conversion from cm to meter after the import
+ */
+ bool convertToMeters;
+};
+} // namespace FBXDocParser
+
+#endif // FBX_IMPORT_SETTINGS_H
diff --git a/modules/fbx/fbx_parser/FBXMaterial.cpp b/modules/fbx/fbx_parser/FBXMaterial.cpp
new file mode 100644
index 0000000000..9970a2b0b1
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXMaterial.cpp
@@ -0,0 +1,407 @@
+/*************************************************************************/
+/* FBXMaterial.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2020, assimp team
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXMaterial.cpp
+ * @brief Assimp::FBX::Material and Assimp::FBX::Texture implementation
+ */
+
+#include "ByteSwapper.h"
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXImportSettings.h"
+#include "FBXParser.h"
+#include "FBXProperties.h"
+
+#include "FBXUtil.h"
+#include <algorithm> // std::transform
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+Material::Material(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ const ElementPtr ShadingModel = sc->GetElement("ShadingModel");
+ const ElementPtr MultiLayer = sc->GetElement("MultiLayer");
+
+ if (MultiLayer) {
+ multilayer = !!ParseTokenAsInt(GetRequiredToken(MultiLayer, 0));
+ }
+
+ if (ShadingModel) {
+ shading = ParseTokenAsString(GetRequiredToken(ShadingModel, 0));
+ } else {
+ DOMWarning("shading mode not specified, assuming phong", element);
+ shading = "phong";
+ }
+
+ std::string templateName;
+
+ if (shading == "phong") {
+ templateName = "Material.Phong";
+ } else if (shading == "lambert") {
+ templateName = "Material.Lambert";
+ } else if (shading == "unknown") {
+ templateName = "Material.StingRay";
+ } else {
+ DOMWarning("shading mode not recognized: " + shading, element);
+ }
+
+ props = GetPropertyTable(doc, templateName, element, sc);
+
+ // resolve texture links
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID());
+ for (const Connection *con : conns) {
+ // texture link to properties, not objects
+ if (!con->PropertyName().length()) {
+ continue;
+ }
+
+ Object *ob = con->SourceObject();
+ if (!ob) {
+ DOMWarning("failed to read source object for texture link, ignoring", element);
+ continue;
+ }
+
+ const Texture *tex = dynamic_cast<const Texture *>(ob);
+ if (!tex) {
+ LayeredTexture *layeredTexture = dynamic_cast<LayeredTexture *>(ob);
+
+ if (!layeredTexture) {
+ DOMWarning("source object for texture link is not a texture or layered texture, ignoring", element);
+ continue;
+ }
+
+ const std::string &prop = con->PropertyName();
+ if (layeredTextures.find(prop) != layeredTextures.end()) {
+ DOMWarning("duplicate layered texture link: " + prop, element);
+ }
+
+ layeredTextures[prop] = layeredTexture;
+ layeredTexture->fillTexture(doc);
+ } else {
+ const std::string &prop = con->PropertyName();
+ if (textures.find(prop) != textures.end()) {
+ DOMWarning("duplicate texture link: " + prop, element);
+ }
+
+ textures[prop] = tex;
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Material::~Material() {
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Texture::Texture(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name), uvScaling(1.0f, 1.0f), media(nullptr) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ const ElementPtr Type = sc->GetElement("Type");
+ const ElementPtr FileName = sc->GetElement("FileName");
+ const ElementPtr RelativeFilename = sc->GetElement("RelativeFilename");
+ const ElementPtr ModelUVTranslation = sc->GetElement("ModelUVTranslation");
+ const ElementPtr ModelUVScaling = sc->GetElement("ModelUVScaling");
+ const ElementPtr Texture_Alpha_Source = sc->GetElement("Texture_Alpha_Source");
+ const ElementPtr Cropping = sc->GetElement("Cropping");
+
+ if (Type) {
+ type = ParseTokenAsString(GetRequiredToken(Type, 0));
+ }
+
+ if (FileName) {
+ fileName = ParseTokenAsString(GetRequiredToken(FileName, 0));
+ }
+
+ if (RelativeFilename) {
+ relativeFileName = ParseTokenAsString(GetRequiredToken(RelativeFilename, 0));
+ }
+
+ if (ModelUVTranslation) {
+ uvTrans = Vector2(ParseTokenAsFloat(GetRequiredToken(ModelUVTranslation, 0)),
+ ParseTokenAsFloat(GetRequiredToken(ModelUVTranslation, 1)));
+ }
+
+ if (ModelUVScaling) {
+ uvScaling = Vector2(ParseTokenAsFloat(GetRequiredToken(ModelUVScaling, 0)),
+ ParseTokenAsFloat(GetRequiredToken(ModelUVScaling, 1)));
+ }
+
+ if (Cropping) {
+ crop[0] = ParseTokenAsInt(GetRequiredToken(Cropping, 0));
+ crop[1] = ParseTokenAsInt(GetRequiredToken(Cropping, 1));
+ crop[2] = ParseTokenAsInt(GetRequiredToken(Cropping, 2));
+ crop[3] = ParseTokenAsInt(GetRequiredToken(Cropping, 3));
+ } else {
+ // vc8 doesn't support the crop() syntax in initialization lists
+ // (and vc9 WARNS about the new (i.e. compliant) behaviour).
+ crop[0] = crop[1] = crop[2] = crop[3] = 0;
+ }
+
+ if (Texture_Alpha_Source) {
+ alphaSource = ParseTokenAsString(GetRequiredToken(Texture_Alpha_Source, 0));
+ }
+
+ props = GetPropertyTable(doc, "Texture.FbxFileTexture", element, sc);
+
+ // 3DS Max and FBX SDK use "Scaling" and "Translation" instead of "ModelUVScaling" and "ModelUVTranslation". Use these properties if available.
+ bool ok;
+ const Vector3 &scaling = PropertyGet<Vector3>(props, "Scaling", ok);
+ if (ok) {
+ uvScaling.x = scaling.x;
+ uvScaling.y = scaling.y;
+ }
+
+ const Vector3 &trans = PropertyGet<Vector3>(props, "Translation", ok);
+ if (ok) {
+ uvTrans.x = trans.x;
+ uvTrans.y = trans.y;
+ }
+
+ // resolve video links
+ if (doc.Settings().readTextures) {
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID());
+ for (const Connection *con : conns) {
+ const Object *const ob = con->SourceObject();
+ if (!ob) {
+ DOMWarning("failed to read source object for texture link, ignoring", element);
+ continue;
+ }
+
+ const Video *const video = dynamic_cast<const Video *>(ob);
+ if (video) {
+ media = video;
+ }
+ }
+ }
+}
+
+Texture::~Texture() {
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+
+LayeredTexture::LayeredTexture(uint64_t id, const ElementPtr element, const Document & /*doc*/, const std::string &name) :
+ Object(id, element, name), blendMode(BlendMode_Modulate), alpha(1) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ ElementPtr BlendModes = sc->GetElement("BlendModes");
+ ElementPtr Alphas = sc->GetElement("Alphas");
+
+ if (BlendModes != 0) {
+ blendMode = (BlendMode)ParseTokenAsInt(GetRequiredToken(BlendModes, 0));
+ }
+ if (Alphas != 0) {
+ alpha = ParseTokenAsFloat(GetRequiredToken(Alphas, 0));
+ }
+}
+
+LayeredTexture::~LayeredTexture() {
+}
+
+void LayeredTexture::fillTexture(const Document &doc) {
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID());
+ for (size_t i = 0; i < conns.size(); ++i) {
+ const Connection *con = conns.at(i);
+
+ const Object *const ob = con->SourceObject();
+ if (!ob) {
+ DOMWarning("failed to read source object for texture link, ignoring", element);
+ continue;
+ }
+
+ const Texture *const tex = dynamic_cast<const Texture *>(ob);
+
+ textures.push_back(tex);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Video::Video(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name), contentLength(0), content(0) {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ const ElementPtr Type = sc->GetElement("Type");
+ // File Version 7500 Crashes if this is not checked fully.
+ // As of writing this comment 7700 exists, in August 2020
+ ElementPtr FileName = nullptr;
+ if (HasElement(sc, "Filename")) {
+ FileName = (ElementPtr)sc->GetElement("Filename");
+ } else if (HasElement(sc, "FileName")) {
+ FileName = (ElementPtr)sc->GetElement("FileName");
+ } else {
+ print_error("file has invalid video material returning...");
+ return;
+ }
+ const ElementPtr RelativeFilename = sc->GetElement("RelativeFilename");
+ const ElementPtr Content = sc->GetElement("Content");
+
+ if (Type) {
+ type = ParseTokenAsString(GetRequiredToken(Type, 0));
+ }
+
+ if (FileName) {
+ fileName = ParseTokenAsString(GetRequiredToken(FileName, 0));
+ }
+
+ if (RelativeFilename) {
+ relativeFileName = ParseTokenAsString(GetRequiredToken(RelativeFilename, 0));
+ }
+
+ if (Content && !Content->Tokens().empty()) {
+ //this field is omitted when the embedded texture is already loaded, let's ignore if it's not found
+ try {
+ const Token *token = GetRequiredToken(Content, 0);
+ const char *data = token->begin();
+ if (!token->IsBinary()) {
+ if (*data != '"') {
+ DOMError("embedded content is not surrounded by quotation marks", element);
+ } else {
+ size_t targetLength = 0;
+ auto numTokens = Content->Tokens().size();
+ // First time compute size (it could be large like 64Gb and it is good to allocate it once)
+ for (uint32_t tokenIdx = 0; tokenIdx < numTokens; ++tokenIdx) {
+ const Token *dataToken = GetRequiredToken(Content, tokenIdx);
+ size_t tokenLength = dataToken->end() - dataToken->begin() - 2; // ignore double quotes
+ const char *base64data = dataToken->begin() + 1;
+ const size_t outLength = Util::ComputeDecodedSizeBase64(base64data, tokenLength);
+ if (outLength == 0) {
+ DOMError("Corrupted embedded content found", element);
+ }
+ targetLength += outLength;
+ }
+ if (targetLength == 0) {
+ DOMError("Corrupted embedded content found", element);
+ } else {
+ content = new uint8_t[targetLength];
+ contentLength = static_cast<uint64_t>(targetLength);
+ size_t dst_offset = 0;
+ for (uint32_t tokenIdx = 0; tokenIdx < numTokens; ++tokenIdx) {
+ const Token *dataToken = GetRequiredToken(Content, tokenIdx);
+ ERR_FAIL_COND(!dataToken);
+ size_t tokenLength = dataToken->end() - dataToken->begin() - 2; // ignore double quotes
+ const char *base64data = dataToken->begin() + 1;
+ dst_offset += Util::DecodeBase64(base64data, tokenLength, content + dst_offset, targetLength - dst_offset);
+ }
+ if (targetLength != dst_offset) {
+ delete[] content;
+ contentLength = 0;
+ DOMError("Corrupted embedded content found", element);
+ }
+ }
+ }
+ } else if (static_cast<size_t>(token->end() - data) < 5) {
+ DOMError("binary data array is too short, need five (5) bytes for type signature and element count", element);
+ } else if (*data != 'R') {
+ DOMWarning("video content is not raw binary data, ignoring", element);
+ } else {
+ // read number of elements
+ uint32_t len = 0;
+ ::memcpy(&len, data + 1, sizeof(len));
+ AI_SWAP4(len);
+
+ contentLength = len;
+
+ content = new uint8_t[len];
+ ::memcpy(content, data + 5, len);
+ }
+ } catch (...) {
+ // //we don't need the content data for contents that has already been loaded
+ // ASSIMP_LOG_VERBOSE_DEBUG_F("Caught exception in FBXMaterial (likely because content was already loaded): ",
+ // runtimeError.what());
+ }
+ }
+
+ props = GetPropertyTable(doc, "Video.FbxVideo", element, sc);
+}
+
+Video::~Video() {
+ if (content) {
+ delete[] content;
+ }
+
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXMeshGeometry.cpp b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp
new file mode 100644
index 0000000000..ccc06550fe
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp
@@ -0,0 +1,485 @@
+/*************************************************************************/
+/* FBXMeshGeometry.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXMeshGeometry.cpp
+ * @brief Assimp::FBX::MeshGeometry implementation
+ */
+
+#include <functional>
+
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXImportSettings.h"
+#include "FBXMeshGeometry.h"
+#include "core/math/vector3.h"
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+Geometry::Geometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Object(id, element, name), skin() {
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Deformer");
+ for (const Connection *con : conns) {
+ const Skin *sk = ProcessSimpleConnection<Skin>(*con, false, "Skin -> Geometry", element);
+ if (sk) {
+ skin = sk;
+ }
+ const BlendShape *bsp = ProcessSimpleConnection<BlendShape>(*con, false, "BlendShape -> Geometry",
+ element);
+ if (bsp) {
+ blendShapes.push_back(bsp);
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Geometry::~Geometry() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+const std::vector<const BlendShape *> &Geometry::get_blend_shapes() const {
+ return blendShapes;
+}
+
+// ------------------------------------------------------------------------------------------------
+const Skin *Geometry::DeformerSkin() const {
+ return skin;
+}
+
+// ------------------------------------------------------------------------------------------------
+MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Geometry(id, element, name, doc) {
+ print_verbose("mesh name: " + String(name.c_str()));
+
+ ScopePtr sc = element->Compound();
+ ERR_FAIL_COND_MSG(sc == nullptr, "failed to read geometry, prevented crash");
+ ERR_FAIL_COND_MSG(!HasElement(sc, "Vertices"), "Detected mesh with no vertexes, didn't populate the mesh");
+
+ // must have Mesh elements:
+ const ElementPtr Vertices = GetRequiredElement(sc, "Vertices", element);
+ const ElementPtr PolygonVertexIndex = GetRequiredElement(sc, "PolygonVertexIndex", element);
+
+ if (HasElement(sc, "Edges")) {
+ const ElementPtr element_edges = GetRequiredElement(sc, "Edges", element);
+ ParseVectorDataArray(m_edges, element_edges);
+ }
+
+ // read mesh data into arrays
+ ParseVectorDataArray(m_vertices, Vertices);
+ ParseVectorDataArray(m_face_indices, PolygonVertexIndex);
+
+ ERR_FAIL_COND_MSG(m_vertices.empty(), "mesh with no vertexes in FBX file, did you mean to delete it?");
+ ERR_FAIL_COND_MSG(m_face_indices.empty(), "mesh has no faces, was this intended?");
+
+ // Retrieve layer elements, for all of the mesh
+ const ElementCollection &Layer = sc->GetCollection("Layer");
+
+ // Store all layers
+ std::vector<std::tuple<int, std::string>> valid_layers;
+
+ // now read the sub mesh information from the geometry (normals, uvs, etc)
+ for (ElementMap::const_iterator it = Layer.first; it != Layer.second; ++it) {
+ const ScopePtr layer = GetRequiredScope(it->second);
+ const ElementCollection &LayerElement = layer->GetCollection("LayerElement");
+ for (ElementMap::const_iterator eit = LayerElement.first; eit != LayerElement.second; ++eit) {
+ std::string layer_name = eit->first;
+ ElementPtr element_layer = eit->second;
+ const ScopePtr layer_element = GetRequiredScope(element_layer);
+
+ // Actual usable 'type' LayerElementUV, LayerElementNormal, etc
+ const ElementPtr Type = GetRequiredElement(layer_element, "Type");
+ const ElementPtr TypedIndex = GetRequiredElement(layer_element, "TypedIndex");
+ const std::string &type = ParseTokenAsString(GetRequiredToken(Type, 0));
+ const int typedIndex = ParseTokenAsInt(GetRequiredToken(TypedIndex, 0));
+
+ // we only need the layer name and the typed index.
+ valid_layers.push_back(std::tuple<int, std::string>(typedIndex, type));
+ }
+ }
+
+ // get object / mesh directly from the FBX by the element ID.
+ const ScopePtr top = GetRequiredScope(element);
+
+ // iterate over all layers for the mesh (uvs, normals, smoothing groups, colors, etc)
+ for (size_t x = 0; x < valid_layers.size(); x++) {
+ const int layer_id = std::get<0>(valid_layers[x]);
+ const std::string &layer_type_name = std::get<1>(valid_layers[x]);
+
+ // Get collection of elements from the XLayerMap (example: LayerElementUV)
+ // this must contain our proper elements.
+
+ // This is stupid, because it means we select them ALL not just the one we want.
+ // but it's fine we can match by id.
+
+ const ElementCollection &candidates = top->GetCollection(layer_type_name);
+
+ ElementMap::const_iterator iter;
+ for (iter = candidates.first; iter != candidates.second; ++iter) {
+ const ScopePtr layer_scope = GetRequiredScope(iter->second);
+ TokenPtr layer_token = GetRequiredToken(iter->second, 0);
+ const int index = ParseTokenAsInt(layer_token);
+
+ ERR_FAIL_COND_MSG(layer_scope == nullptr, "prevented crash, layer scope is invalid");
+
+ if (index == layer_id) {
+ const std::string &MappingInformationType = ParseTokenAsString(GetRequiredToken(
+ GetRequiredElement(layer_scope, "MappingInformationType"), 0));
+
+ const std::string &ReferenceInformationType = ParseTokenAsString(GetRequiredToken(
+ GetRequiredElement(layer_scope, "ReferenceInformationType"), 0));
+
+ if (layer_type_name == "LayerElementUV") {
+ if (index == 0) {
+ m_uv_0 = resolve_vertex_data_array<Vector2>(layer_scope, MappingInformationType, ReferenceInformationType, "UV");
+ } else if (index == 1) {
+ m_uv_1 = resolve_vertex_data_array<Vector2>(layer_scope, MappingInformationType, ReferenceInformationType, "UV");
+ }
+ } else if (layer_type_name == "LayerElementMaterial") {
+ m_material_allocation_ids = resolve_vertex_data_array<int>(layer_scope, MappingInformationType, ReferenceInformationType, "Materials");
+ } else if (layer_type_name == "LayerElementNormal") {
+ m_normals = resolve_vertex_data_array<Vector3>(layer_scope, MappingInformationType, ReferenceInformationType, "Normals");
+ } else if (layer_type_name == "LayerElementColor") {
+ m_colors = resolve_vertex_data_array<Color>(layer_scope, MappingInformationType, ReferenceInformationType, "Colors", "ColorIndex");
+ // NOTE: this is a useful sanity check to ensure you're getting any color data which is not default.
+ // const Color first_color_check = m_colors.data[0];
+ // bool colors_are_all_the_same = true;
+ // size_t i = 1;
+ // for(i = 1; i < m_colors.data.size(); i++)
+ // {
+ // const Color current_color = m_colors.data[i];
+ // if(current_color.is_equal_approx(first_color_check))
+ // {
+ // continue;
+ // }
+ // else
+ // {
+ // colors_are_all_the_same = false;
+ // break;
+ // }
+ // }
+ //
+ // if(colors_are_all_the_same)
+ // {
+ // print_error("Color serialisation is not working for vertex colors some should be different in the test asset.");
+ // }
+ // else
+ // {
+ // print_verbose("Color array has unique colors at index: " + itos(i));
+ // }
+ }
+ }
+ }
+ }
+
+ print_verbose("Mesh statistics \nuv_0: " + m_uv_0.debug_info() + "\nuv_1: " + m_uv_1.debug_info() + "\nvertices: " + itos(m_vertices.size()));
+
+ // Compose the edge of the mesh.
+ // You can see how the edges are stored into the FBX here: https://gist.github.com/AndreaCatania/da81840f5aa3b2feedf189e26c5a87e6
+ for (size_t i = 0; i < m_edges.size(); i += 1) {
+ ERR_FAIL_INDEX_MSG((size_t)m_edges[i], m_face_indices.size(), "The edge is pointing to a weird location in the face indices. The FBX is corrupted.");
+ int polygon_vertex_0 = m_face_indices[m_edges[i]];
+ int polygon_vertex_1;
+ if (polygon_vertex_0 < 0) {
+ // The polygon_vertex_0 points to the end of a polygon, so it's
+ // connected with the beginning of polygon in the edge list.
+
+ // Fist invert the vertex.
+ polygon_vertex_0 = ~polygon_vertex_0;
+
+ // Search the start vertex of the polygon.
+ // Iterate from the polygon_vertex_index backward till the start of
+ // the polygon is found.
+ ERR_FAIL_COND_MSG(m_edges[i] - 1 < 0, "The polygon is not yet started and we already need the final vertex. This FBX is corrupted.");
+ bool found_it = false;
+ for (int x = m_edges[i] - 1; x >= 0; x -= 1) {
+ if (x == 0) {
+ // This for sure is the start.
+ polygon_vertex_1 = m_face_indices[x];
+ found_it = true;
+ break;
+ } else if (m_face_indices[x] < 0) {
+ // This is the end of the previous polygon, so the next is
+ // the start of the polygon we need.
+ polygon_vertex_1 = m_face_indices[x + 1];
+ found_it = true;
+ break;
+ }
+ }
+ // As the algorithm above, this check is useless. Because the first
+ // ever vertex is always considered the begining of a polygon.
+ ERR_FAIL_COND_MSG(found_it == false, "Was not possible to find the first vertex of this polygon. FBX file is corrupted.");
+
+ } else {
+ ERR_FAIL_INDEX_MSG((size_t)(m_edges[i] + 1), m_face_indices.size(), "FBX The other FBX edge seems to point to an invalid vertices. This FBX file is corrupted.");
+ // Take the next vertex
+ polygon_vertex_1 = m_face_indices[m_edges[i] + 1];
+ }
+
+ if (polygon_vertex_1 < 0) {
+ // We don't care if the `polygon_vertex_1` is the end of the polygon,
+ // for `polygon_vertex_1` so we can just invert it.
+ polygon_vertex_1 = ~polygon_vertex_1;
+ }
+
+ ERR_FAIL_COND_MSG(polygon_vertex_0 == polygon_vertex_1, "The vertices of this edge can't be the same, Is this a point???. This FBX file is corrupted.");
+
+ // Just create the edge.
+ edge_map.push_back({ polygon_vertex_0, polygon_vertex_1 });
+ }
+}
+
+MeshGeometry::~MeshGeometry() {
+ // empty
+}
+
+const std::vector<Vector3> &MeshGeometry::get_vertices() const {
+ return m_vertices;
+}
+
+const std::vector<MeshGeometry::Edge> &MeshGeometry::get_edge_map() const {
+ return edge_map;
+}
+
+const std::vector<int> &MeshGeometry::get_polygon_indices() const {
+ return m_face_indices;
+}
+
+const std::vector<int> &MeshGeometry::get_edges() const {
+ return m_edges;
+}
+
+const MeshGeometry::MappingData<Vector3> &MeshGeometry::get_normals() const {
+ return m_normals;
+}
+
+const MeshGeometry::MappingData<Vector2> &MeshGeometry::get_uv_0() const {
+ //print_verbose("get uv_0 " + m_uv_0.debug_info() );
+ return m_uv_0;
+}
+
+const MeshGeometry::MappingData<Vector2> &MeshGeometry::get_uv_1() const {
+ //print_verbose("get uv_1 " + m_uv_1.debug_info() );
+ return m_uv_1;
+}
+
+const MeshGeometry::MappingData<Color> &MeshGeometry::get_colors() const {
+ return m_colors;
+}
+
+const MeshGeometry::MappingData<int> &MeshGeometry::get_material_allocation_id() const {
+ return m_material_allocation_ids;
+}
+
+int MeshGeometry::get_edge_id(const std::vector<Edge> &p_map, int p_vertex_a, int p_vertex_b) {
+ for (size_t i = 0; i < p_map.size(); i += 1) {
+ if ((p_map[i].vertex_0 == p_vertex_a && p_map[i].vertex_1 == p_vertex_b) || (p_map[i].vertex_1 == p_vertex_a && p_map[i].vertex_0 == p_vertex_b)) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+MeshGeometry::Edge MeshGeometry::get_edge(const std::vector<Edge> &p_map, int p_id) {
+ ERR_FAIL_INDEX_V_MSG((size_t)p_id, p_map.size(), Edge({ -1, -1 }), "ID not found.");
+ return p_map[p_id];
+}
+
+template <class T>
+MeshGeometry::MappingData<T> MeshGeometry::resolve_vertex_data_array(
+ const ScopePtr source,
+ const std::string &MappingInformationType,
+ const std::string &ReferenceInformationType,
+ const std::string &dataElementName,
+ const std::string &indexOverride) {
+ ERR_FAIL_COND_V_MSG(source == nullptr, MappingData<T>(), "Invalid scope operator preventing memory corruption");
+
+ // UVIndex, MaterialIndex, NormalIndex, etc..
+ std::string indexDataElementName;
+
+ if (indexOverride != "") {
+ // Colors should become ColorIndex
+ indexDataElementName = indexOverride;
+ } else {
+ // Some indexes will exist.
+ indexDataElementName = dataElementName + "Index";
+ }
+
+ // goal: expand everything to be per vertex
+
+ ReferenceType l_ref_type = ReferenceType::direct;
+
+ // Read the reference type into the enumeration
+ if (ReferenceInformationType == "IndexToDirect") {
+ l_ref_type = ReferenceType::index_to_direct;
+ } else if (ReferenceInformationType == "Index") {
+ // set non legacy index to direct mapping
+ l_ref_type = ReferenceType::index;
+ } else if (ReferenceInformationType == "Direct") {
+ l_ref_type = ReferenceType::direct;
+ } else {
+ ERR_FAIL_V_MSG(MappingData<T>(), "invalid reference type has the FBX format changed?");
+ }
+
+ MapType l_map_type = MapType::none;
+
+ if (MappingInformationType == "None") {
+ l_map_type = MapType::none;
+ } else if (MappingInformationType == "ByVertice") {
+ l_map_type = MapType::vertex;
+ } else if (MappingInformationType == "ByPolygonVertex") {
+ l_map_type = MapType::polygon_vertex;
+ } else if (MappingInformationType == "ByPolygon") {
+ l_map_type = MapType::polygon;
+ } else if (MappingInformationType == "ByEdge") {
+ l_map_type = MapType::edge;
+ } else if (MappingInformationType == "AllSame") {
+ l_map_type = MapType::all_the_same;
+ } else {
+ print_error("invalid mapping type: " + String(MappingInformationType.c_str()));
+ }
+
+ // create mapping data
+ MeshGeometry::MappingData<T> tempData;
+ tempData.map_type = l_map_type;
+ tempData.ref_type = l_ref_type;
+
+ // parse data into array
+ ParseVectorDataArray(tempData.data, GetRequiredElement(source, dataElementName));
+
+ // index array wont always exist
+ const ElementPtr element = GetOptionalElement(source, indexDataElementName);
+ if (element) {
+ ParseVectorDataArray(tempData.index, element);
+ }
+
+ return tempData;
+}
+// ------------------------------------------------------------------------------------------------
+ShapeGeometry::ShapeGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Geometry(id, element, name, doc) {
+ const ScopePtr sc = element->Compound();
+ if (nullptr == sc) {
+ DOMError("failed to read Geometry object (class: Shape), no data scope found");
+ }
+ const ElementPtr Indexes = GetRequiredElement(sc, "Indexes", element);
+ const ElementPtr Normals = GetRequiredElement(sc, "Normals", element);
+ const ElementPtr Vertices = GetRequiredElement(sc, "Vertices", element);
+ ParseVectorDataArray(m_indices, Indexes);
+ ParseVectorDataArray(m_vertices, Vertices);
+ ParseVectorDataArray(m_normals, Normals);
+}
+
+// ------------------------------------------------------------------------------------------------
+ShapeGeometry::~ShapeGeometry() {
+ // empty
+}
+// ------------------------------------------------------------------------------------------------
+const std::vector<Vector3> &ShapeGeometry::GetVertices() const {
+ return m_vertices;
+}
+// ------------------------------------------------------------------------------------------------
+const std::vector<Vector3> &ShapeGeometry::GetNormals() const {
+ return m_normals;
+}
+// ------------------------------------------------------------------------------------------------
+const std::vector<unsigned int> &ShapeGeometry::GetIndices() const {
+ return m_indices;
+}
+// ------------------------------------------------------------------------------------------------
+LineGeometry::LineGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
+ Geometry(id, element, name, doc) {
+ const ScopePtr sc = element->Compound();
+ if (!sc) {
+ DOMError("failed to read Geometry object (class: Line), no data scope found");
+ }
+ const ElementPtr Points = GetRequiredElement(sc, "Points", element);
+ const ElementPtr PointsIndex = GetRequiredElement(sc, "PointsIndex", element);
+ ParseVectorDataArray(m_vertices, Points);
+ ParseVectorDataArray(m_indices, PointsIndex);
+}
+
+// ------------------------------------------------------------------------------------------------
+LineGeometry::~LineGeometry() {
+ // empty
+}
+// ------------------------------------------------------------------------------------------------
+const std::vector<Vector3> &LineGeometry::GetVertices() const {
+ return m_vertices;
+}
+// ------------------------------------------------------------------------------------------------
+const std::vector<int> &LineGeometry::GetIndices() const {
+ return m_indices;
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXMeshGeometry.h b/modules/fbx/fbx_parser/FBXMeshGeometry.h
new file mode 100644
index 0000000000..710e644c68
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXMeshGeometry.h
@@ -0,0 +1,263 @@
+/*************************************************************************/
+/* FBXMeshGeometry.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+copyright notice, this list of conditions and the
+following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the
+following disclaimer in the documentation and/or other
+materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+contributors may be used to endorse or promote products
+derived from this software without specific prior
+written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+#ifndef FBX_MESH_GEOMETRY_H
+#define FBX_MESH_GEOMETRY_H
+
+#include "core/math/color.h"
+#include "core/math/vector2.h"
+#include "core/math/vector3.h"
+#include "core/templates/vector.h"
+
+#include "FBXDocument.h"
+#include "FBXParser.h"
+
+#include <iostream>
+
+#define AI_MAX_NUMBER_OF_TEXTURECOORDS 4
+#define AI_MAX_NUMBER_OF_COLOR_SETS 8
+
+namespace FBXDocParser {
+
+/*
+ * DOM base class for all kinds of FBX geometry
+ */
+class Geometry : public Object {
+public:
+ Geometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+ virtual ~Geometry();
+
+ /** Get the Skin attached to this geometry or NULL */
+ const Skin *DeformerSkin() const;
+
+ const std::vector<const BlendShape *> &get_blend_shapes() const;
+
+ size_t get_blend_shape_count() const {
+ return blendShapes.size();
+ }
+
+private:
+ const Skin *skin = nullptr;
+ std::vector<const BlendShape *> blendShapes;
+};
+
+typedef std::vector<int> MatIndexArray;
+
+/// Map Geometry stores the FBX file information.
+///
+/// # FBX doc.
+/// ## Reference type declared:
+/// - Direct (directly related to the mapping information type)
+/// - IndexToDirect (Map with key value, meaning depends on the MappingInformationType)
+///
+/// ## Map Type:
+/// * None The mapping is undetermined.
+/// * ByVertex There will be one mapping coordinate for each surface control point/vertex (ControlPoint is a vertex).
+/// * If you have direct reference type verticies[x]
+/// * If you have IndexToDirect reference type the UV
+/// * ByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part. (Sorted by polygon, referencing vertex)
+/// * ByPolygon There can be only one mapping coordinate for the whole polygon.
+/// * One mapping per polygon polygon x has this normal x
+/// * For each vertex of the polygon then set the normal to x
+/// * ByEdge There will be one mapping coordinate for each unique edge in the mesh. This is meant to be used with smoothing layer elements. (Mapping is referencing the edge id)
+/// * AllSame There can be only one mapping coordinate for the whole surface.
+class MeshGeometry : public Geometry {
+public:
+ enum class MapType {
+ none = 0, // No mapping type. Stored as "None".
+ vertex, // Maps per vertex. Stored as "ByVertice".
+ polygon_vertex, // Maps per polygon vertex. Stored as "ByPolygonVertex".
+ polygon, // Maps per polygon. Stored as "ByPolygon".
+ edge, // Maps per edge. Stored as "ByEdge".
+ all_the_same // Uaps to everything. Stored as "AllSame".
+ };
+
+ enum class ReferenceType {
+ direct = 0,
+ index = 1,
+ index_to_direct = 2
+ };
+
+ template <class T>
+ struct MappingData {
+ MapType map_type = MapType::none;
+ ReferenceType ref_type = ReferenceType::direct;
+ std::vector<T> data;
+ /// The meaning of the indices depends from the `MapType`.
+ /// If `ref_type` is `direct` this map is hollow.
+ std::vector<int> index;
+
+ String debug_info() const {
+ return "indexes: " + itos(index.size()) + " data: " + itos(data.size());
+ }
+ };
+
+ struct Edge {
+ int vertex_0 = 0, vertex_1 = 0;
+ Edge(int v0, int v1) :
+ vertex_0(v0), vertex_1(v1) {}
+ Edge() {}
+ };
+
+public:
+ MeshGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+
+ virtual ~MeshGeometry();
+
+ const std::vector<Vector3> &get_vertices() const;
+ const std::vector<Edge> &get_edge_map() const;
+ const std::vector<int> &get_polygon_indices() const;
+ const std::vector<int> &get_edges() const;
+ const MappingData<Vector3> &get_normals() const;
+ const MappingData<Vector2> &get_uv_0() const;
+ const MappingData<Vector2> &get_uv_1() const;
+ const MappingData<Color> &get_colors() const;
+ const MappingData<int> &get_material_allocation_id() const;
+
+ /// Returns -1 if the vertices doesn't form an edge. Vertex order, doesn't
+ // matter.
+ static int get_edge_id(const std::vector<Edge> &p_map, int p_vertex_a, int p_vertex_b);
+ // Retuns the edge point bu that ID, or the edge with -1 vertices if the
+ // id is not valid.
+ static Edge get_edge(const std::vector<Edge> &p_map, int p_id);
+
+private:
+ // Read directly from the FBX file.
+ std::vector<Vector3> m_vertices;
+ std::vector<Edge> edge_map;
+ std::vector<int> m_face_indices;
+ std::vector<int> m_edges;
+ MappingData<Vector3> m_normals;
+ MappingData<Vector2> m_uv_0; // first uv coordinates
+ MappingData<Vector2> m_uv_1; // second uv coordinates
+ MappingData<Color> m_colors; // colors for the mesh
+ MappingData<int> m_material_allocation_ids; // slot of material used
+
+ template <class T>
+ MappingData<T> resolve_vertex_data_array(
+ const ScopePtr source,
+ const std::string &MappingInformationType,
+ const std::string &ReferenceInformationType,
+ const std::string &dataElementName,
+ const std::string &indexOverride = "");
+};
+
+/*
+ * DOM class for FBX geometry of type "Shape"
+ */
+class ShapeGeometry : public Geometry {
+public:
+ /** The class constructor */
+ ShapeGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+
+ /** The class destructor */
+ virtual ~ShapeGeometry();
+
+ /** Get a list of all vertex points, non-unique*/
+ const std::vector<Vector3> &GetVertices() const;
+
+ /** Get a list of all vertex normals or an empty array if
+ * no normals are specified. */
+ const std::vector<Vector3> &GetNormals() const;
+
+ /** Return list of vertex indices. */
+ const std::vector<unsigned int> &GetIndices() const;
+
+private:
+ std::vector<Vector3> m_vertices;
+ std::vector<Vector3> m_normals;
+ std::vector<unsigned int> m_indices;
+};
+/**
+* DOM class for FBX geometry of type "Line"
+*/
+class LineGeometry : public Geometry {
+public:
+ /** The class constructor */
+ LineGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc);
+
+ /** The class destructor */
+ virtual ~LineGeometry();
+
+ /** Get a list of all vertex points, non-unique*/
+ const std::vector<Vector3> &GetVertices() const;
+
+ /** Return list of vertex indices. */
+ const std::vector<int> &GetIndices() const;
+
+private:
+ std::vector<Vector3> m_vertices;
+ std::vector<int> m_indices;
+};
+} // namespace FBXDocParser
+
+#endif // FBX_MESH_GEOMETRY_H
diff --git a/modules/fbx/fbx_parser/FBXModel.cpp b/modules/fbx/fbx_parser/FBXModel.cpp
new file mode 100644
index 0000000000..767994441f
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXModel.cpp
@@ -0,0 +1,176 @@
+/*************************************************************************/
+/* FBXModel.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXModel.cpp
+ * @brief Assimp::FBX::Model implementation
+ */
+
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXMeshGeometry.h"
+#include "FBXParser.h"
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+Model::Model(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name), shading("Y") {
+ const ScopePtr sc = GetRequiredScope(element);
+ const ElementPtr Shading = sc->GetElement("Shading");
+ const ElementPtr Culling = sc->GetElement("Culling");
+
+ if (Shading) {
+ shading = GetRequiredToken(Shading, 0)->StringContents();
+ }
+
+ if (Culling) {
+ culling = ParseTokenAsString(GetRequiredToken(Culling, 0));
+ }
+
+ props = GetPropertyTable(doc, "Model.FbxNode", element, sc);
+ ResolveLinks(element, doc);
+}
+
+// ------------------------------------------------------------------------------------------------
+Model::~Model() {
+ if (props != nullptr) {
+ delete props;
+ props = nullptr;
+ }
+}
+
+ModelLimbNode::ModelLimbNode(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Model(id, element, doc, name){};
+
+ModelLimbNode::~ModelLimbNode() {
+}
+
+// ------------------------------------------------------------------------------------------------
+void Model::ResolveLinks(const ElementPtr element, const Document &doc) {
+ const char *const arr[] = { "Geometry", "Material", "NodeAttribute" };
+
+ // resolve material
+ const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), arr, 3);
+
+ materials.reserve(conns.size());
+ geometry.reserve(conns.size());
+ attributes.reserve(conns.size());
+ for (const Connection *con : conns) {
+ // material and geometry links should be Object-Object connections
+ if (con->PropertyName().length()) {
+ continue;
+ }
+
+ const Object *const ob = con->SourceObject();
+ if (!ob) {
+ //DOMWarning("failed to read source object for incoming Model link, ignoring",&element);
+ continue;
+ }
+
+ const Material *const mat = dynamic_cast<const Material *>(ob);
+ if (mat) {
+ materials.push_back(mat);
+ continue;
+ }
+
+ const Geometry *const geo = dynamic_cast<const Geometry *>(ob);
+ if (geo) {
+ geometry.push_back(geo);
+ continue;
+ }
+
+ const NodeAttribute *const att = dynamic_cast<const NodeAttribute *>(ob);
+ if (att) {
+ attributes.push_back(att);
+ continue;
+ }
+
+ DOMWarning("source object for model link is neither Material, NodeAttribute nor Geometry, ignoring", element);
+ continue;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+bool Model::IsNull() const {
+ const std::vector<const NodeAttribute *> &attrs = GetAttributes();
+ for (const NodeAttribute *att : attrs) {
+ const Null *null_tag = dynamic_cast<const Null *>(att);
+ if (null_tag) {
+ return true;
+ }
+ }
+
+ return false;
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXNodeAttribute.cpp b/modules/fbx/fbx_parser/FBXNodeAttribute.cpp
new file mode 100644
index 0000000000..2749fc9f4d
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXNodeAttribute.cpp
@@ -0,0 +1,183 @@
+/*************************************************************************/
+/* FBXNodeAttribute.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXNoteAttribute.cpp
+ * @brief Assimp::FBX::NodeAttribute (and subclasses) implementation
+ */
+
+#include "FBXDocument.h"
+#include "FBXDocumentUtil.h"
+#include "FBXParser.h"
+#include <iostream>
+
+namespace FBXDocParser {
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+NodeAttribute::NodeAttribute(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name), props() {
+ const ScopePtr sc = GetRequiredScope(element);
+
+ const std::string &classname = ParseTokenAsString(GetRequiredToken(element, 2));
+
+ // hack on the deriving type but Null/LimbNode attributes are the only case in which
+ // the property table is by design absent and no warning should be generated
+ // for it.
+ const bool is_null_or_limb = !strcmp(classname.c_str(), "Null") || !strcmp(classname.c_str(), "LimbNode");
+ props = GetPropertyTable(doc, "NodeAttribute.Fbx" + classname, element, sc, is_null_or_limb);
+}
+
+// ------------------------------------------------------------------------------------------------
+NodeAttribute::~NodeAttribute() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+CameraSwitcher::CameraSwitcher(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ NodeAttribute(id, element, doc, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+ const ElementPtr CameraId = sc->GetElement("CameraId");
+ const ElementPtr CameraName = sc->GetElement("CameraName");
+ const ElementPtr CameraIndexName = sc->GetElement("CameraIndexName");
+
+ if (CameraId) {
+ cameraId = ParseTokenAsInt(GetRequiredToken(CameraId, 0));
+ }
+
+ if (CameraName) {
+ cameraName = GetRequiredToken(CameraName, 0)->StringContents();
+ }
+
+ if (CameraIndexName && CameraIndexName->Tokens().size()) {
+ cameraIndexName = GetRequiredToken(CameraIndexName, 0)->StringContents();
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+CameraSwitcher::~CameraSwitcher() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+Camera::Camera(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ NodeAttribute(id, element, doc, name) {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+Camera::~Camera() {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+Light::Light(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ NodeAttribute(id, element, doc, name) {
+ // empty
+}
+
+// ------------------------------------------------------------------------------------------------
+Light::~Light() {
+}
+
+// ------------------------------------------------------------------------------------------------
+Null::Null(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ NodeAttribute(id, element, doc, name) {
+}
+
+// ------------------------------------------------------------------------------------------------
+Null::~Null() {
+}
+
+// ------------------------------------------------------------------------------------------------
+LimbNode::LimbNode(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ NodeAttribute(id, element, doc, name) {
+ //std::cout << "limb node: " << name << std::endl;
+ //const Scope &sc = GetRequiredScope(element);
+
+ //const ElementPtr const TypeFlag = sc["TypeFlags"];
+
+ // keep this it can dump new properties for you
+ // for( auto element : sc.Elements())
+ // {
+ // std::cout << "limbnode element: " << element.first << std::endl;
+ // }
+
+ // if(TypeFlag)
+ // {
+ // // std::cout << "type flag: " << GetRequiredToken(*TypeFlag, 0).StringContents() << std::endl;
+ // }
+}
+
+// ------------------------------------------------------------------------------------------------
+LimbNode::~LimbNode() {
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXParseTools.h b/modules/fbx/fbx_parser/FBXParseTools.h
new file mode 100644
index 0000000000..21472f5b7b
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXParseTools.h
@@ -0,0 +1,111 @@
+/*************************************************************************/
+/* FBXParseTools.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_PARSE_TOOLS_H
+#define FBX_PARSE_TOOLS_H
+
+#include "core/error/error_macros.h"
+#include "core/string/ustring.h"
+
+#include <stdint.h>
+#include <algorithm>
+#include <locale>
+
+template <class char_t>
+inline bool IsNewLine(char_t c) {
+ return c == '\n' || c == '\r';
+}
+template <class char_t>
+inline bool IsSpace(char_t c) {
+ return (c == (char_t)' ' || c == (char_t)'\t');
+}
+
+template <class char_t>
+inline bool IsSpaceOrNewLine(char_t c) {
+ return IsNewLine(c) || IsSpace(c);
+}
+
+template <class char_t>
+inline bool IsLineEnd(char_t c) {
+ return (c == (char_t)'\r' || c == (char_t)'\n' || c == (char_t)'\0' || c == (char_t)'\f');
+}
+
+// ------------------------------------------------------------------------------------
+// Special version of the function, providing higher accuracy and safety
+// It is mainly used by fast_atof to prevent ugly and unwanted integer overflows.
+// ------------------------------------------------------------------------------------
+inline uint64_t strtoul10_64(const char *in, bool &errored, const char **out = 0, unsigned int *max_inout = 0) {
+ unsigned int cur = 0;
+ uint64_t value = 0;
+
+ errored = *in < '0' || *in > '9';
+ ERR_FAIL_COND_V_MSG(errored, 0, "The string cannot be converted parser error");
+
+ for (;;) {
+ if (*in < '0' || *in > '9') {
+ break;
+ }
+
+ const uint64_t new_value = (value * (uint64_t)10) + ((uint64_t)(*in - '0'));
+
+ // numeric overflow, we rely on you
+ if (new_value < value) {
+ //WARN_PRINT( "Converting the string \" " + in + " \" into a value resulted in overflow." );
+ return 0;
+ }
+
+ value = new_value;
+
+ ++in;
+ ++cur;
+
+ if (max_inout && *max_inout == cur) {
+ if (out) { /* skip to end */
+ while (*in >= '0' && *in <= '9') {
+ ++in;
+ }
+ *out = in;
+ }
+
+ return value;
+ }
+ }
+ if (out) {
+ *out = in;
+ }
+
+ if (max_inout) {
+ *max_inout = cur;
+ }
+
+ return value;
+}
+
+#endif // FBX_PARSE_TOOLS_H
diff --git a/modules/fbx/fbx_parser/FBXParser.cpp b/modules/fbx/fbx_parser/FBXParser.cpp
new file mode 100644
index 0000000000..44c24ff926
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXParser.cpp
@@ -0,0 +1,1295 @@
+/*************************************************************************/
+/* FBXParser.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXParser.cpp
+ * @brief Implementation of the FBX parser and the rudimentary DOM that we use
+ */
+
+#include "thirdparty/zlib/zlib.h"
+#include <stdlib.h> /* strtol */
+
+#include "ByteSwapper.h"
+#include "FBXParseTools.h"
+#include "FBXParser.h"
+#include "FBXTokenizer.h"
+#include "core/math/math_defs.h"
+#include "core/math/transform.h"
+#include "core/math/vector3.h"
+#include "core/string/print_string.h"
+
+using namespace FBXDocParser;
+namespace {
+
+// Initially, we did reinterpret_cast, breaking strict aliasing rules.
+// This actually caused trouble on Android, so let's be safe this time.
+// https://github.com/assimp/assimp/issues/24
+template <typename T>
+T SafeParse(const char *data, const char *end) {
+ // Actual size validation happens during Tokenization so
+ // this is valid as an assertion.
+ (void)(end);
+ //ai_assert(static_cast<size_t>(end - data) >= sizeof(T));
+ T result = static_cast<T>(0);
+ ::memcpy(&result, data, sizeof(T));
+ return result;
+}
+} // namespace
+
+namespace FBXDocParser {
+
+// ------------------------------------------------------------------------------------------------
+Element::Element(const TokenPtr key_token, Parser &parser) :
+ key_token(key_token) {
+ TokenPtr n = nullptr;
+ do {
+ n = parser.AdvanceToNextToken();
+ if (n == nullptr) {
+ continue;
+ }
+
+ if (!n) {
+ print_error("unexpected end of file, expected closing bracket" + String(parser.LastToken()->StringContents().c_str()));
+ }
+
+ if (n && n->Type() == TokenType_DATA) {
+ tokens.push_back(n);
+ TokenPtr prev = n;
+ n = parser.AdvanceToNextToken();
+
+ if (n == nullptr) {
+ break;
+ }
+
+ if (!n) {
+ print_error("unexpected end of file, expected bracket, comma or key" + String(parser.LastToken()->StringContents().c_str()));
+ }
+
+ const TokenType ty = n->Type();
+
+ // some exporters are missing a comma on the next line
+ if (ty == TokenType_DATA && prev->Type() == TokenType_DATA && (n->Line() == prev->Line() + 1)) {
+ tokens.push_back(n);
+ continue;
+ }
+
+ if (ty != TokenType_OPEN_BRACKET && ty != TokenType_CLOSE_BRACKET && ty != TokenType_COMMA && ty != TokenType_KEY) {
+ print_error("unexpected token; expected bracket, comma or key" + String(n->StringContents().c_str()));
+ }
+ }
+
+ if (n && n->Type() == TokenType_OPEN_BRACKET) {
+ compound = new_Scope(parser);
+ parser.scopes.push_back(compound);
+
+ // current token should be a TOK_CLOSE_BRACKET
+ n = parser.CurrentToken();
+
+ if (n && n->Type() != TokenType_CLOSE_BRACKET) {
+ print_error("expected closing bracket" + String(n->StringContents().c_str()));
+ }
+
+ parser.AdvanceToNextToken();
+ return;
+ }
+ } while (n && n->Type() != TokenType_KEY && n->Type() != TokenType_CLOSE_BRACKET);
+}
+
+// ------------------------------------------------------------------------------------------------
+Element::~Element() {
+}
+
+// ------------------------------------------------------------------------------------------------
+Scope::Scope(Parser &parser, bool topLevel) {
+ if (!topLevel) {
+ TokenPtr t = parser.CurrentToken();
+ if (t->Type() != TokenType_OPEN_BRACKET) {
+ print_error("expected open bracket" + String(t->StringContents().c_str()));
+ }
+ }
+
+ TokenPtr n = parser.AdvanceToNextToken();
+ if (n == nullptr) {
+ print_error("unexpected end of file");
+ }
+
+ // note: empty scopes are allowed
+ while (n && n->Type() != TokenType_CLOSE_BRACKET) {
+ if (n->Type() != TokenType_KEY) {
+ print_error("unexpected token, expected TOK_KEY" + String(n->StringContents().c_str()));
+ }
+
+ const std::string str = n->StringContents();
+
+ // std::multimap<std::string, ElementPtr> (key and value)
+ elements.insert(ElementMap::value_type(str, new_Element(n, parser)));
+
+ // Element() should stop at the next Key token (or right after a Close token)
+ n = parser.CurrentToken();
+ if (n == nullptr) {
+ if (topLevel) {
+ return;
+ }
+
+ //print_error("unexpected end of file" + String(parser.LastToken()->StringContents().c_str()));
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Scope::~Scope() {
+ for (ElementMap::value_type &v : elements) {
+ delete v.second;
+ v.second = nullptr;
+ }
+
+ elements.clear();
+}
+
+// ------------------------------------------------------------------------------------------------
+Parser::Parser(const TokenList &tokens, bool is_binary) :
+ tokens(tokens), last(), current(), cursor(tokens.begin()), is_binary(is_binary) {
+ root = new_Scope(*this, true);
+ scopes.push_back(root);
+}
+
+// ------------------------------------------------------------------------------------------------
+Parser::~Parser() {
+ for (ScopePtr scope : scopes) {
+ delete scope;
+ scope = nullptr;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+TokenPtr Parser::AdvanceToNextToken() {
+ last = current;
+ if (cursor == tokens.end()) {
+ current = nullptr;
+ } else {
+ current = *cursor++;
+ }
+ return current;
+}
+
+// ------------------------------------------------------------------------------------------------
+TokenPtr Parser::CurrentToken() const {
+ return current;
+}
+
+// ------------------------------------------------------------------------------------------------
+TokenPtr Parser::LastToken() const {
+ return last;
+}
+
+// ------------------------------------------------------------------------------------------------
+uint64_t ParseTokenAsID(const TokenPtr t, const char *&err_out) {
+ ERR_FAIL_COND_V_MSG(t == nullptr, 0L, "Invalid token passed to ParseTokenAsID");
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return 0L;
+ }
+
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'L') {
+ err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
+ return 0L;
+ }
+
+ uint64_t id = SafeParse<uint64_t>(data + 1, t->end());
+ return id;
+ }
+
+ // XXX: should use size_t here
+ unsigned int length = static_cast<unsigned int>(t->end() - t->begin());
+ //ai_assert(length > 0);
+
+ const char *out = nullptr;
+ bool errored = false;
+
+ const uint64_t id = strtoul10_64(t->begin(), errored, &out, &length);
+ if (errored || out > t->end()) {
+ err_out = "failed to parse ID (text)";
+ return 0L;
+ }
+
+ return id;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsID() with print_error handling
+uint64_t ParseTokenAsID(const TokenPtr t) {
+ const char *err = nullptr;
+ const uint64_t i = ParseTokenAsID(t, err);
+ if (err) {
+ print_error(String(err) + " " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+
+// ------------------------------------------------------------------------------------------------
+size_t ParseTokenAsDim(const TokenPtr t, const char *&err_out) {
+ // same as ID parsing, except there is a trailing asterisk
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return 0;
+ }
+
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'L') {
+ err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
+ return 0;
+ }
+
+ uint64_t id = SafeParse<uint64_t>(data + 1, t->end());
+ AI_SWAP8(id);
+ return static_cast<size_t>(id);
+ }
+
+ if (*t->begin() != '*') {
+ err_out = "expected asterisk before array dimension";
+ return 0;
+ }
+
+ // XXX: should use size_t here
+ unsigned int length = static_cast<unsigned int>(t->end() - t->begin());
+ if (length == 0) {
+ err_out = "expected valid integer number after asterisk";
+ return 0;
+ }
+
+ const char *out = nullptr;
+ bool errored = false;
+ const size_t id = static_cast<size_t>(strtoul10_64(t->begin() + 1, errored, &out, &length));
+ if (errored || out > t->end()) {
+ print_error("failed to parse id");
+ err_out = "failed to parse ID";
+ return 0;
+ }
+
+ return id;
+}
+
+// ------------------------------------------------------------------------------------------------
+float ParseTokenAsFloat(const TokenPtr t, const char *&err_out) {
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return 0.0f;
+ }
+
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'F' && data[0] != 'D') {
+ err_out = "failed to parse F(loat) or D(ouble), unexpected data type (binary)";
+ return 0.0f;
+ }
+
+ if (data[0] == 'F') {
+ return SafeParse<float>(data + 1, t->end());
+ } else {
+ return static_cast<float>(SafeParse<double>(data + 1, t->end()));
+ }
+ }
+
+// need to copy the input string to a temporary buffer
+// first - next in the fbx token stream comes ',',
+// which fast_atof could interpret as decimal point.
+#define MAX_FLOAT_LENGTH 31
+ char temp[MAX_FLOAT_LENGTH + 1];
+ const size_t length = static_cast<size_t>(t->end() - t->begin());
+ std::copy(t->begin(), t->end(), temp);
+ temp[std::min(static_cast<size_t>(MAX_FLOAT_LENGTH), length)] = '\0';
+
+ return atof(temp);
+}
+
+// ------------------------------------------------------------------------------------------------
+int ParseTokenAsInt(const TokenPtr t, const char *&err_out) {
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return 0;
+ }
+
+ // binary files are simple to parse
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'I') {
+ err_out = "failed to parse I(nt), unexpected data type (binary)";
+ return 0;
+ }
+
+ int32_t ival = SafeParse<int32_t>(data + 1, t->end());
+ AI_SWAP4(ival);
+ return static_cast<int>(ival);
+ }
+
+ // ASCII files are unsafe.
+ const size_t length = static_cast<size_t>(t->end() - t->begin());
+ if (length == 0) {
+ err_out = "expected valid integer number after asterisk";
+ ERR_FAIL_V_MSG(0, "expected valid integer number after asterisk");
+ }
+
+ // must not be null for strtol to work
+ char *out = (char *)t->end();
+ // string begin, end ptr ref, base 10
+ const int value = strtol(t->begin(), &out, 10);
+ if (out == nullptr || out != t->end()) {
+ err_out = "failed to parse ID";
+ ERR_FAIL_V_MSG(0, "failed to parse ID");
+ }
+
+ return value;
+}
+
+// ------------------------------------------------------------------------------------------------
+int64_t ParseTokenAsInt64(const TokenPtr t, const char *&err_out) {
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return 0L;
+ }
+
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'L') {
+ err_out = "failed to parse Int64, unexpected data type";
+ return 0L;
+ }
+
+ int64_t id = SafeParse<int64_t>(data + 1, t->end());
+ AI_SWAP8(id);
+ return id;
+ }
+
+ // XXX: should use size_t here
+ unsigned int length = static_cast<unsigned int>(t->end() - t->begin());
+ //ai_assert(length > 0);
+
+ char *out = nullptr;
+ const int64_t id = strtol(t->begin(), &out, length);
+ if (out > t->end()) {
+ err_out = "failed to parse Int64 (text)";
+ return 0L;
+ }
+
+ return id;
+}
+
+// ------------------------------------------------------------------------------------------------
+std::string ParseTokenAsString(const TokenPtr t, const char *&err_out) {
+ err_out = nullptr;
+
+ if (t->Type() != TokenType_DATA) {
+ err_out = "expected TOK_DATA token";
+ return "";
+ }
+
+ if (t->IsBinary()) {
+ const char *data = t->begin();
+ if (data[0] != 'S') {
+ err_out = "failed to parse String, unexpected data type (binary)";
+ return "";
+ }
+
+ // read string length
+ int32_t len = SafeParse<int32_t>(data + 1, t->end());
+ AI_SWAP4(len);
+
+ //ai_assert(t.end() - data == 5 + len);
+ return std::string(data + 5, len);
+ }
+
+ const size_t length = static_cast<size_t>(t->end() - t->begin());
+ if (length < 2) {
+ err_out = "token is too short to hold a string";
+ return "";
+ }
+
+ const char *s = t->begin(), *e = t->end() - 1;
+ if (*s != '\"' || *e != '\"') {
+ err_out = "expected double quoted string";
+ return "";
+ }
+
+ return std::string(s + 1, length - 2);
+}
+
+namespace {
+
+// ------------------------------------------------------------------------------------------------
+// read the type code and element count of a binary data array and stop there
+void ReadBinaryDataArrayHead(const char *&data, const char *end, char &type, uint32_t &count,
+ const ElementPtr el) {
+ TokenPtr token = el->KeyToken();
+ if (static_cast<size_t>(end - data) < 5) {
+ print_error("binary data array is too short, need five (5) bytes for type signature and element count: " + String(token->StringContents().c_str()));
+ }
+
+ // data type
+ type = *data;
+
+ // read number of elements
+ uint32_t len = SafeParse<uint32_t>(data + 1, end);
+ AI_SWAP4(len);
+
+ count = len;
+ data += 5;
+}
+
+// ------------------------------------------------------------------------------------------------
+// read binary data array, assume cursor points to the 'compression mode' field (i.e. behind the header)
+void ReadBinaryDataArray(char type, uint32_t count, const char *&data, const char *end,
+ std::vector<char> &buff,
+ const ElementPtr /*el*/) {
+ uint32_t encmode = SafeParse<uint32_t>(data, end);
+ AI_SWAP4(encmode);
+ data += 4;
+
+ // next comes the compressed length
+ uint32_t comp_len = SafeParse<uint32_t>(data, end);
+ AI_SWAP4(comp_len);
+ data += 4;
+
+ //ai_assert(data + comp_len == end);
+
+ // determine the length of the uncompressed data by looking at the type signature
+ uint32_t stride = 0;
+ switch (type) {
+ case 'f':
+ case 'i':
+ stride = 4;
+ break;
+
+ case 'd':
+ case 'l':
+ stride = 8;
+ break;
+ }
+
+ const uint32_t full_length = stride * count;
+ buff.resize(full_length);
+
+ if (encmode == 0) {
+ //ai_assert(full_length == comp_len);
+
+ // plain data, no compression
+ std::copy(data, end, buff.begin());
+ } else if (encmode == 1) {
+ // zlib/deflate, next comes ZIP head (0x78 0x01)
+ // see http://www.ietf.org/rfc/rfc1950.txt
+
+ z_stream zstream;
+ zstream.opaque = Z_NULL;
+ zstream.zalloc = Z_NULL;
+ zstream.zfree = Z_NULL;
+ zstream.data_type = Z_BINARY;
+
+ // http://hewgill.com/journal/entries/349-how-to-decompress-gzip-stream-with-zlib
+ if (Z_OK != inflateInit(&zstream)) {
+ print_error("failure initializing zlib");
+ }
+
+ zstream.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(data));
+ zstream.avail_in = comp_len;
+
+ zstream.avail_out = static_cast<uInt>(buff.size());
+ zstream.next_out = reinterpret_cast<Bytef *>(&*buff.begin());
+ const int ret = inflate(&zstream, Z_FINISH);
+
+ if (ret != Z_STREAM_END && ret != Z_OK) {
+ print_error("failure decompressing compressed data section");
+ }
+
+ // terminate zlib
+ inflateEnd(&zstream);
+ }
+#ifdef ASSIMP_BUILD_DEBUG
+ else {
+ // runtime check for this happens at tokenization stage
+ //ai_assert(false);
+ }
+#endif
+
+ data += comp_len;
+ //ai_assert(data == end);
+}
+} // namespace
+
+// ------------------------------------------------------------------------------------------------
+// read an array of float3 tuples
+void ParseVectorDataArray(std::vector<Vector3> &out, const ElementPtr el) {
+ out.resize(0);
+
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ if (tok.empty()) {
+ print_error("unexpected empty element" + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (count % 3 != 0) {
+ print_error("number of floats is not a multiple of three (3) (binary)" + String(token->StringContents().c_str()));
+ }
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'd' && type != 'f') {
+ print_error("expected float or double array (binary)" + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
+
+ const uint32_t count3 = count / 3;
+ out.reserve(count3);
+
+ if (type == 'd') {
+ const double *d = reinterpret_cast<const double *>(&buff[0]);
+ for (unsigned int i = 0; i < count3; ++i, d += 3) {
+ out.push_back(Vector3(static_cast<real_t>(d[0]),
+ static_cast<real_t>(d[1]),
+ static_cast<real_t>(d[2])));
+ }
+ // for debugging
+ /*for ( size_t i = 0; i < out.size(); i++ ) {
+ aiVector3D vec3( out[ i ] );
+ std::stringstream stream;
+ stream << " vec3.x = " << vec3.x << " vec3.y = " << vec3.y << " vec3.z = " << vec3.z << std::endl;
+ DefaultLogger::get()->info( stream.str() );
+ }*/
+ } else if (type == 'f') {
+ const float *f = reinterpret_cast<const float *>(&buff[0]);
+ for (unsigned int i = 0; i < count3; ++i, f += 3) {
+ out.push_back(Vector3(f[0], f[1], f[2]));
+ }
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // may throw bad_alloc if the input is rubbish, but this need
+ // not to be prevented - importing would fail but we wouldn't
+ // crash since assimp handles this case properly.
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ if (a->Tokens().size() % 3 != 0) {
+ print_error("number of floats is not a multiple of three (3)" + String(token->StringContents().c_str()));
+ } else {
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ Vector3 v;
+ v.x = ParseTokenAsFloat(*it++);
+ v.y = ParseTokenAsFloat(*it++);
+ v.z = ParseTokenAsFloat(*it++);
+
+ out.push_back(v);
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of color4 tuples
+void ParseVectorDataArray(std::vector<Color> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+
+ TokenPtr token = el->KeyToken();
+
+ if (tok.empty()) {
+ print_error("unexpected empty element" + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (count % 4 != 0) {
+ print_error("number of floats is not a multiple of four (4) (binary)" + String(token->StringContents().c_str()));
+ }
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'd' && type != 'f') {
+ print_error("expected float or double array (binary)" + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
+
+ const uint32_t count4 = count / 4;
+ out.reserve(count4);
+
+ if (type == 'd') {
+ const double *d = reinterpret_cast<const double *>(&buff[0]);
+ for (unsigned int i = 0; i < count4; ++i, d += 4) {
+ out.push_back(Color(static_cast<float>(d[0]),
+ static_cast<float>(d[1]),
+ static_cast<float>(d[2]),
+ static_cast<float>(d[3])));
+ }
+ } else if (type == 'f') {
+ const float *f = reinterpret_cast<const float *>(&buff[0]);
+ for (unsigned int i = 0; i < count4; ++i, f += 4) {
+ out.push_back(Color(f[0], f[1], f[2], f[3]));
+ }
+ }
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray() above
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ if (a->Tokens().size() % 4 != 0) {
+ print_error("number of floats is not a multiple of four (4)" + String(token->StringContents().c_str()));
+ }
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ Color v;
+ v.r = ParseTokenAsFloat(*it++);
+ v.g = ParseTokenAsFloat(*it++);
+ v.b = ParseTokenAsFloat(*it++);
+ v.a = ParseTokenAsFloat(*it++);
+
+ out.push_back(v);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of float2 tuples
+void ParseVectorDataArray(std::vector<Vector2> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ if (tok.empty()) {
+ print_error("unexpected empty element" + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (count % 2 != 0) {
+ print_error("number of floats is not a multiple of two (2) (binary)" + String(token->StringContents().c_str()));
+ }
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'd' && type != 'f') {
+ print_error("expected float or double array (binary)" + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
+
+ const uint32_t count2 = count / 2;
+ out.reserve(count2);
+
+ if (type == 'd') {
+ const double *d = reinterpret_cast<const double *>(&buff[0]);
+ for (unsigned int i = 0; i < count2; ++i, d += 2) {
+ out.push_back(Vector2(static_cast<float>(d[0]),
+ static_cast<float>(d[1])));
+ }
+ } else if (type == 'f') {
+ const float *f = reinterpret_cast<const float *>(&buff[0]);
+ for (unsigned int i = 0; i < count2; ++i, f += 2) {
+ out.push_back(Vector2(f[0], f[1]));
+ }
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray() above
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ if (a->Tokens().size() % 2 != 0) {
+ print_error("number of floats is not a multiple of two (2)" + String(token->StringContents().c_str()));
+ } else {
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ Vector2 v;
+ v.x = ParseTokenAsFloat(*it++);
+ v.y = ParseTokenAsFloat(*it++);
+ out.push_back(v);
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of ints
+void ParseVectorDataArray(std::vector<int> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ if (tok.empty()) {
+ print_error("unexpected empty element" + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'i') {
+ print_error("expected int array (binary)" + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * 4);
+
+ out.reserve(count);
+
+ const int32_t *ip = reinterpret_cast<const int32_t *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++ip) {
+ int32_t val = *ip;
+ AI_SWAP4(val);
+ out.push_back(val);
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray()
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ const int ival = ParseTokenAsInt(*it++);
+ out.push_back(ival);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of floats
+void ParseVectorDataArray(std::vector<float> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ if (tok.empty()) {
+ print_error("unexpected empty element: " + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'd' && type != 'f') {
+ print_error("expected float or double array (binary) " + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
+
+ if (type == 'd') {
+ const double *d = reinterpret_cast<const double *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++d) {
+ out.push_back(static_cast<float>(*d));
+ }
+ } else if (type == 'f') {
+ const float *f = reinterpret_cast<const float *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++f) {
+ out.push_back(*f);
+ }
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray()
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ const float ival = ParseTokenAsFloat(*it++);
+ out.push_back(ival);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of uints
+void ParseVectorDataArray(std::vector<unsigned int> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+ const TokenPtr token = el->KeyToken();
+
+ ERR_FAIL_COND_MSG(!token, "invalid ParseVectorDataArrat token invalid");
+
+ if (tok.empty()) {
+ print_error("unexpected empty element: " + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'i') {
+ print_error("expected (u)int array (binary)" + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * 4);
+
+ out.reserve(count);
+
+ const int32_t *ip = reinterpret_cast<const int32_t *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++ip) {
+ int32_t val = *ip;
+ if (val < 0) {
+ print_error("encountered negative integer index (binary)");
+ }
+
+ out.push_back(val);
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray()
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ const int ival = ParseTokenAsInt(*it++);
+ if (ival < 0) {
+ print_error("encountered negative integer index");
+ }
+ out.push_back(static_cast<unsigned int>(ival));
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of uint64_ts
+void ParseVectorDataArray(std::vector<uint64_t> &out, const ElementPtr el) {
+ out.resize(0);
+
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ ERR_FAIL_COND(!token);
+
+ if (tok.empty()) {
+ print_error("unexpected empty element " + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'l') {
+ print_error("expected long array (binary): " + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * 8);
+
+ out.reserve(count);
+
+ const uint64_t *ip = reinterpret_cast<const uint64_t *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++ip) {
+ uint64_t val = *ip;
+ AI_SWAP8(val);
+ out.push_back(val);
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray()
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ const uint64_t ival = ParseTokenAsID(*it++);
+
+ out.push_back(ival);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+// read an array of int64_ts
+void ParseVectorDataArray(std::vector<int64_t> &out, const ElementPtr el) {
+ out.resize(0);
+ const TokenList &tok = el->Tokens();
+ TokenPtr token = el->KeyToken();
+ ERR_FAIL_COND(!token);
+ if (tok.empty()) {
+ print_error("unexpected empty element: " + String(token->StringContents().c_str()));
+ }
+
+ if (tok[0]->IsBinary()) {
+ const char *data = tok[0]->begin(), *end = tok[0]->end();
+
+ char type;
+ uint32_t count;
+ ReadBinaryDataArrayHead(data, end, type, count, el);
+
+ if (!count) {
+ return;
+ }
+
+ if (type != 'l') {
+ print_error("expected long array (binary) " + String(token->StringContents().c_str()));
+ }
+
+ std::vector<char> buff;
+ ReadBinaryDataArray(type, count, data, end, buff, el);
+
+ //ai_assert(data == end);
+ //ai_assert(buff.size() == count * 8);
+
+ out.reserve(count);
+
+ const int64_t *ip = reinterpret_cast<const int64_t *>(&buff[0]);
+ for (unsigned int i = 0; i < count; ++i, ++ip) {
+ int64_t val = *ip;
+ AI_SWAP8(val);
+ out.push_back(val);
+ }
+
+ return;
+ }
+
+ const size_t dim = ParseTokenAsDim(tok[0]);
+
+ // see notes in ParseVectorDataArray()
+ out.reserve(dim);
+
+ const ScopePtr scope = GetRequiredScope(el);
+ const ElementPtr a = GetRequiredElement(scope, "a", el);
+
+ for (TokenList::const_iterator it = a->Tokens().begin(), end = a->Tokens().end(); it != end;) {
+ const int64_t val = ParseTokenAsInt64(*it++);
+ out.push_back(val);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+Transform ReadMatrix(const ElementPtr element) {
+ std::vector<float> values;
+ ParseVectorDataArray(values, element);
+
+ if (values.size() != 16) {
+ print_error("expected 16 matrix elements");
+ }
+
+ // clean values to prevent any IBM damage on inverse() / affine_inverse()
+ for (float &value : values) {
+ if (::Math::is_equal_approx(0, value)) {
+ value = 0;
+ }
+ }
+
+ Transform xform;
+ Basis basis;
+
+ basis.set(
+ Vector3(values[0], values[1], values[2]),
+ Vector3(values[4], values[5], values[6]),
+ Vector3(values[8], values[9], values[10]));
+
+ xform.basis = basis;
+ xform.origin = Vector3(values[12], values[13], values[14]);
+ // determine if we need to think about this with dynamic rotation order?
+ // for example:
+ // xform.basis = z_axis * y_axis * x_axis;
+ //xform.basis.transpose();
+
+ print_verbose("xform verbose basis: " + (xform.basis.get_euler() * (180 / Math_PI)) + " xform origin:" + xform.origin);
+
+ return xform;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsString() with print_error handling
+std::string ParseTokenAsString(const TokenPtr t) {
+ ERR_FAIL_COND_V(!t, "");
+ const char *err;
+ const std::string &i = ParseTokenAsString(t, err);
+ if (err) {
+ print_error(String(err) + ", " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+
+// ------------------------------------------------------------------------------------------------
+// extract a required element from a scope, abort if the element cannot be found
+ElementPtr GetRequiredElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= NULL*/) {
+ const ElementPtr el = sc->GetElement(index);
+ TokenPtr token = el->KeyToken();
+ ERR_FAIL_COND_V(!token, nullptr);
+ if (!el) {
+ print_error("did not find required element \"" + String(index.c_str()) + "\" " + String(token->StringContents().c_str()));
+ }
+ return el;
+}
+
+bool HasElement(const ScopePtr sc, const std::string &index) {
+ const ElementPtr el = sc->GetElement(index);
+ if (nullptr == el) {
+ return false;
+ }
+
+ return true;
+}
+
+// ------------------------------------------------------------------------------------------------
+// extract a required element from a scope, abort if the element cannot be found
+ElementPtr GetOptionalElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= NULL*/) {
+ const ElementPtr el = sc->GetElement(index);
+ return el;
+}
+
+// ------------------------------------------------------------------------------------------------
+// extract required compound scope
+ScopePtr GetRequiredScope(const ElementPtr el) {
+ if (el) {
+ ScopePtr s = el->Compound();
+ TokenPtr token = el->KeyToken();
+ ERR_FAIL_COND_V(!token, nullptr);
+ if (s) {
+ return s;
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "expected compound scope " + String(token->StringContents().c_str()));
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Invalid element supplied to parser");
+}
+
+// ------------------------------------------------------------------------------------------------
+// get token at a particular index
+TokenPtr GetRequiredToken(const ElementPtr el, unsigned int index) {
+ if (el) {
+ const TokenList &x = el->Tokens();
+ TokenPtr token = el->KeyToken();
+
+ ERR_FAIL_COND_V(!token, nullptr);
+
+ if (index >= x.size()) {
+ ERR_FAIL_V_MSG(nullptr, "missing token at index: " + itos(index) + " " + String(token->StringContents().c_str()));
+ }
+
+ return x[index];
+ }
+
+ return nullptr;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsDim() with print_error handling
+size_t ParseTokenAsDim(const TokenPtr t) {
+ const char *err;
+ const size_t i = ParseTokenAsDim(t, err);
+ if (err) {
+ print_error(String(err) + " " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsFloat() with print_error handling
+float ParseTokenAsFloat(const TokenPtr t) {
+ const char *err;
+ const float i = ParseTokenAsFloat(t, err);
+ if (err) {
+ print_error(String(err) + " " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsInt() with print_error handling
+int ParseTokenAsInt(const TokenPtr t) {
+ const char *err;
+ const int i = ParseTokenAsInt(t, err);
+ if (err) {
+ print_error(String(err) + " " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+
+// ------------------------------------------------------------------------------------------------
+// wrapper around ParseTokenAsInt64() with print_error handling
+int64_t ParseTokenAsInt64(const TokenPtr t) {
+ const char *err;
+ const int64_t i = ParseTokenAsInt64(t, err);
+ if (err) {
+ print_error(String(err) + " " + String(t->StringContents().c_str()));
+ }
+ return i;
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXParser.h b/modules/fbx/fbx_parser/FBXParser.h
new file mode 100644
index 0000000000..37d27d3dca
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXParser.h
@@ -0,0 +1,263 @@
+/*************************************************************************/
+/* FBXParser.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXParser.h
+ * @brief FBX parsing code
+ */
+#ifndef FBX_PARSER_H
+#define FBX_PARSER_H
+
+#include <stdint.h>
+#include <map>
+#include <memory>
+
+#include "core/math/color.h"
+#include "core/math/transform.h"
+#include "core/math/vector2.h"
+#include "core/math/vector3.h"
+
+#include "FBXTokenizer.h"
+
+namespace FBXDocParser {
+
+class Scope;
+class Parser;
+class Element;
+
+typedef Element *ElementPtr;
+typedef Scope *ScopePtr;
+
+typedef std::vector<ScopePtr> ScopeList;
+typedef std::multimap<std::string, ElementPtr> ElementMap;
+typedef std::pair<ElementMap::const_iterator, ElementMap::const_iterator> ElementCollection;
+
+#define new_Scope new Scope
+#define new_Element new Element
+
+/** FBX data entity that consists of a key:value tuple.
+ *
+ * Example:
+ * @verbatim
+ * AnimationCurve: 23, "AnimCurve::", "" {
+ * [..]
+ * }
+ * @endverbatim
+ *
+ * As can be seen in this sample, elements can contain nested #Scope
+ * as their trailing member. **/
+class Element {
+public:
+ Element(TokenPtr key_token, Parser &parser);
+ ~Element();
+
+ ScopePtr Compound() const {
+ return compound;
+ }
+
+ TokenPtr KeyToken() const {
+ return key_token;
+ }
+
+ const TokenList &Tokens() const {
+ return tokens;
+ }
+
+private:
+ TokenList tokens;
+ ScopePtr compound = nullptr;
+ std::vector<ScopePtr> compound_scope;
+ TokenPtr key_token = nullptr;
+};
+
+/** FBX data entity that consists of a 'scope', a collection
+ * of not necessarily unique #Element instances.
+ *
+ * Example:
+ * @verbatim
+ * GlobalSettings: {
+ * Version: 1000
+ * Properties70:
+ * [...]
+ * }
+ * @endverbatim */
+class Scope {
+public:
+ Scope(Parser &parser, bool topLevel = false);
+ ~Scope();
+
+ ElementPtr GetElement(const std::string &index) const {
+ ElementMap::const_iterator it = elements.find(index);
+ return it == elements.end() ? nullptr : (*it).second;
+ }
+
+ ElementPtr FindElementCaseInsensitive(const std::string &elementName) const {
+ for (auto element = elements.begin(); element != elements.end(); ++element) {
+ if (element->first.compare(elementName)) {
+ return element->second;
+ }
+ }
+
+ // nothing to reference / expired.
+ return nullptr;
+ }
+
+ ElementCollection GetCollection(const std::string &index) const {
+ return elements.equal_range(index);
+ }
+
+ const ElementMap &Elements() const {
+ return elements;
+ }
+
+private:
+ ElementMap elements;
+};
+
+/** FBX parsing class, takes a list of input tokens and generates a hierarchy
+ * of nested #Scope instances, representing the fbx DOM.*/
+class Parser {
+public:
+ /** Parse given a token list. Does not take ownership of the tokens -
+ * the objects must persist during the entire parser lifetime */
+ Parser(const TokenList &tokens, bool is_binary);
+ ~Parser();
+
+ ScopePtr GetRootScope() const {
+ return root;
+ }
+
+ bool IsBinary() const {
+ return is_binary;
+ }
+
+private:
+ friend class Scope;
+ friend class Element;
+
+ TokenPtr AdvanceToNextToken();
+ TokenPtr LastToken() const;
+ TokenPtr CurrentToken() const;
+
+private:
+ ScopeList scopes;
+ const TokenList &tokens;
+
+ TokenPtr last = nullptr, current = nullptr;
+ TokenList::const_iterator cursor;
+ ScopePtr root = nullptr;
+
+ const bool is_binary;
+};
+
+/* token parsing - this happens when building the DOM out of the parse-tree*/
+uint64_t ParseTokenAsID(const TokenPtr t, const char *&err_out);
+size_t ParseTokenAsDim(const TokenPtr t, const char *&err_out);
+float ParseTokenAsFloat(const TokenPtr t, const char *&err_out);
+int ParseTokenAsInt(const TokenPtr t, const char *&err_out);
+int64_t ParseTokenAsInt64(const TokenPtr t, const char *&err_out);
+std::string ParseTokenAsString(const TokenPtr t, const char *&err_out);
+
+/* wrapper around ParseTokenAsXXX() with DOMError handling */
+uint64_t ParseTokenAsID(const TokenPtr t);
+size_t ParseTokenAsDim(const TokenPtr t);
+float ParseTokenAsFloat(const TokenPtr t);
+int ParseTokenAsInt(const TokenPtr t);
+int64_t ParseTokenAsInt64(const TokenPtr t);
+std::string ParseTokenAsString(const TokenPtr t);
+
+/* read data arrays */
+void ParseVectorDataArray(std::vector<Vector3> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<Color> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<Vector2> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<int> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<float> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<float> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<unsigned int> &out, const ElementPtr el);
+void ParseVectorDataArray(std::vector<uint64_t> &out, const ElementPtr ep);
+void ParseVectorDataArray(std::vector<int64_t> &out, const ElementPtr el);
+bool HasElement(const ScopePtr sc, const std::string &index);
+
+// extract a required element from a scope, abort if the element cannot be found
+ElementPtr GetRequiredElement(const ScopePtr sc, const std::string &index, const ElementPtr element = nullptr);
+ScopePtr GetRequiredScope(const ElementPtr el); // New in 2020. (less likely to destroy application)
+ElementPtr GetOptionalElement(const ScopePtr sc, const std::string &index, const ElementPtr element = nullptr);
+// extract required compound scope
+ScopePtr GetRequiredScope(const ElementPtr el);
+// get token at a particular index
+TokenPtr GetRequiredToken(const ElementPtr el, unsigned int index);
+
+// ------------------------------------------------------------------------------------------------
+// read a 4x4 matrix from an array of 16 floats
+Transform ReadMatrix(const ElementPtr element);
+} // namespace FBXDocParser
+
+#endif // FBX_PARSER_H
diff --git a/modules/fbx/fbx_parser/FBXPose.cpp b/modules/fbx/fbx_parser/FBXPose.cpp
new file mode 100644
index 0000000000..6d80b85e38
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXPose.cpp
@@ -0,0 +1,104 @@
+/*************************************************************************/
+/* FBXPose.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXNoteAttribute.cpp
+ * @brief Assimp::FBX::NodeAttribute (and subclasses) implementation
+ */
+
+#include "FBXDocument.h"
+#include "FBXParser.h"
+#include <iostream>
+
+namespace FBXDocParser {
+
+class FbxPoseNode;
+// ------------------------------------------------------------------------------------------------
+FbxPose::FbxPose(uint64_t id, const ElementPtr element, const Document &doc, const std::string &name) :
+ Object(id, element, name) {
+ const ScopePtr sc = GetRequiredScope(element);
+ //const std::string &classname = ParseTokenAsString(GetRequiredToken(element, 2));
+
+ const ElementCollection &PoseNodes = sc->GetCollection("PoseNode");
+ for (ElementMap::const_iterator it = PoseNodes.first; it != PoseNodes.second; ++it) {
+ std::string entry_name = (*it).first;
+ ElementPtr some_element = (*it).second;
+ FbxPoseNode *pose_node = new FbxPoseNode(some_element, doc, entry_name);
+ pose_nodes.push_back(pose_node);
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+FbxPose::~FbxPose() {
+ pose_nodes.clear();
+ // empty
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXProperties.cpp b/modules/fbx/fbx_parser/FBXProperties.cpp
new file mode 100644
index 0000000000..8ab94e1ef4
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXProperties.cpp
@@ -0,0 +1,237 @@
+/*************************************************************************/
+/* FBXProperties.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXProperties.cpp
+ * @brief Implementation of the FBX dynamic properties system
+ */
+
+#include "FBXProperties.h"
+#include "FBXDocumentUtil.h"
+#include "FBXParser.h"
+#include "FBXTokenizer.h"
+
+namespace FBXDocParser {
+
+using namespace Util;
+
+// ------------------------------------------------------------------------------------------------
+Property::Property() {
+}
+
+// ------------------------------------------------------------------------------------------------
+Property::~Property() {
+}
+
+namespace {
+
+// ------------------------------------------------------------------------------------------------
+// read a typed property out of a FBX element. The return value is NULL if the property cannot be read.
+PropertyPtr ReadTypedProperty(const ElementPtr element) {
+ //ai_assert(element.KeyToken().StringContents() == "P");
+
+ const TokenList &tok = element->Tokens();
+ //ai_assert(tok.size() >= 5);
+
+ const std::string &s = ParseTokenAsString(tok[1]);
+ const char *const cs = s.c_str();
+ if (!strcmp(cs, "KString")) {
+ return new TypedProperty<std::string>(ParseTokenAsString(tok[4]));
+ } else if (!strcmp(cs, "bool") || !strcmp(cs, "Bool")) {
+ return new TypedProperty<bool>(ParseTokenAsInt(tok[4]) != 0);
+ } else if (!strcmp(cs, "int") || !strcmp(cs, "Int") || !strcmp(cs, "enum") || !strcmp(cs, "Enum")) {
+ return new TypedProperty<int>(ParseTokenAsInt(tok[4]));
+ } else if (!strcmp(cs, "ULongLong")) {
+ return new TypedProperty<uint64_t>(ParseTokenAsID(tok[4]));
+ } else if (!strcmp(cs, "KTime")) {
+ return new TypedProperty<int64_t>(ParseTokenAsInt64(tok[4]));
+ } else if (!strcmp(cs, "Vector3D") ||
+ !strcmp(cs, "ColorRGB") ||
+ !strcmp(cs, "Vector") ||
+ !strcmp(cs, "Color") ||
+ !strcmp(cs, "Lcl Translation") ||
+ !strcmp(cs, "Lcl Rotation") ||
+ !strcmp(cs, "Lcl Scaling")) {
+ return new TypedProperty<Vector3>(Vector3(
+ ParseTokenAsFloat(tok[4]),
+ ParseTokenAsFloat(tok[5]),
+ ParseTokenAsFloat(tok[6])));
+ } else if (!strcmp(cs, "double") || !strcmp(cs, "Number") || !strcmp(cs, "Float") || !strcmp(cs, "float") || !strcmp(cs, "FieldOfView") || !strcmp(cs, "UnitScaleFactor")) {
+ return new TypedProperty<float>(ParseTokenAsFloat(tok[4]));
+ }
+
+ return nullptr;
+}
+
+// ------------------------------------------------------------------------------------------------
+// peek into an element and check if it contains a FBX property, if so return its name.
+std::string PeekPropertyName(const Element &element) {
+ //ai_assert(element.KeyToken().StringContents() == "P");
+ const TokenList &tok = element.Tokens();
+ if (tok.size() < 4) {
+ return "";
+ }
+
+ return ParseTokenAsString(tok[0]);
+}
+} // namespace
+
+// ------------------------------------------------------------------------------------------------
+PropertyTable::PropertyTable() :
+ templateProps(), element() {
+}
+
+// ------------------------------------------------------------------------------------------------
+PropertyTable::PropertyTable(const ElementPtr element, const PropertyTable *templateProps) :
+ templateProps(templateProps), element(element) {
+ const ScopePtr scope = GetRequiredScope(element);
+ ERR_FAIL_COND(!scope);
+ for (const ElementMap::value_type &v : scope->Elements()) {
+ if (v.first != "P") {
+ DOMWarning("expected only P elements in property table", v.second);
+ continue;
+ }
+
+ const std::string &name = PeekPropertyName(*v.second);
+ if (!name.length()) {
+ DOMWarning("could not read property name", v.second);
+ continue;
+ }
+
+ LazyPropertyMap::const_iterator it = lazyProps.find(name);
+ if (it != lazyProps.end()) {
+ DOMWarning("duplicate property name, will hide previous value: " + name, v.second);
+ continue;
+ }
+
+ // since the above checks for duplicates we can be sure to insert the only match here.
+ lazyProps[name] = v.second;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+PropertyTable::~PropertyTable() {
+ for (PropertyMap::value_type &v : props) {
+ delete v.second;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+PropertyPtr PropertyTable::Get(const std::string &name) const {
+ PropertyMap::const_iterator it = props.find(name);
+ if (it == props.end()) {
+ // hasn't been parsed yet?
+ LazyPropertyMap::const_iterator lit = lazyProps.find(name);
+ if (lit != lazyProps.end()) {
+ props[name] = ReadTypedProperty(lit->second);
+ it = props.find(name);
+
+ //ai_assert(it != props.end());
+ }
+
+ if (it == props.end()) {
+ // check property template
+ if (templateProps) {
+ return templateProps->Get(name);
+ }
+
+ return nullptr;
+ }
+ }
+
+ return (*it).second;
+}
+
+DirectPropertyMap PropertyTable::GetUnparsedProperties() const {
+ DirectPropertyMap result;
+
+ // Loop through all the lazy properties (which is all the properties)
+ for (const LazyPropertyMap::value_type &element : lazyProps) {
+ // Skip parsed properties
+ if (props.end() != props.find(element.first))
+ continue;
+
+ // Read the element's value.
+ // Wrap the naked pointer (since the call site is required to acquire ownership)
+ // std::unique_ptr from C++11 would be preferred both as a wrapper and a return value.
+ Property *prop = ReadTypedProperty(element.second);
+
+ // Element could not be read. Skip it.
+ if (!prop)
+ continue;
+
+ // Add to result
+ result[element.first] = prop;
+ }
+
+ return result;
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXProperties.h b/modules/fbx/fbx_parser/FBXProperties.h
new file mode 100644
index 0000000000..27cacfaf76
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXProperties.h
@@ -0,0 +1,221 @@
+/*************************************************************************/
+/* FBXProperties.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXProperties.h
+ * @brief FBX dynamic properties
+ */
+#ifndef FBX_PROPERTIES_H
+#define FBX_PROPERTIES_H
+
+#include "FBXParser.h"
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace FBXDocParser {
+
+// Forward declarations
+class Element;
+
+/** Represents a dynamic property. Type info added by deriving classes,
+ * see #TypedProperty.
+ Example:
+ @verbatim
+ P: "ShininessExponent", "double", "Number", "",0.5
+ @endvebatim
+*/
+class Property {
+protected:
+ Property();
+
+public:
+ virtual ~Property();
+
+public:
+ template <typename T>
+ const T *As() const {
+ return dynamic_cast<const T *>(this);
+ }
+};
+
+template <typename T>
+class TypedProperty : public Property {
+public:
+ explicit TypedProperty(const T &value) :
+ value(value) {
+ // empty
+ }
+
+ const T &Value() const {
+ return value;
+ }
+
+private:
+ T value;
+};
+
+#define new_Property new Property
+typedef Property *PropertyPtr;
+typedef std::map<std::string, PropertyPtr> DirectPropertyMap;
+typedef std::map<std::string, PropertyPtr> PropertyMap;
+typedef std::map<std::string, ElementPtr> LazyPropertyMap;
+
+/**
+ * Represents a property table as can be found in the newer FBX files (Properties60, Properties70)
+ */
+class PropertyTable {
+public:
+ // in-memory property table with no source element
+ PropertyTable();
+ PropertyTable(const ElementPtr element, const PropertyTable *templateProps);
+ ~PropertyTable();
+
+ PropertyPtr Get(const std::string &name) const;
+
+ // PropertyTable's need not be coupled with FBX elements so this can be NULL
+ ElementPtr GetElement() const {
+ return element;
+ }
+
+ PropertyMap &GetProperties() const {
+ return props;
+ }
+
+ const LazyPropertyMap &GetLazyProperties() const {
+ return lazyProps;
+ }
+
+ const PropertyTable *TemplateProps() const {
+ return templateProps;
+ }
+
+ DirectPropertyMap GetUnparsedProperties() const;
+
+private:
+ LazyPropertyMap lazyProps;
+ mutable PropertyMap props;
+ const PropertyTable *templateProps = nullptr;
+ const ElementPtr element = nullptr;
+};
+
+// ------------------------------------------------------------------------------------------------
+template <typename T>
+inline T PropertyGet(const PropertyTable *in, const std::string &name, const T &defaultValue) {
+ PropertyPtr prop = in->Get(name);
+ if (nullptr == prop) {
+ return defaultValue;
+ }
+
+ // strong typing, no need to be lenient
+ const TypedProperty<T> *const tprop = prop->As<TypedProperty<T>>();
+ if (nullptr == tprop) {
+ return defaultValue;
+ }
+
+ return tprop->Value();
+}
+
+// ------------------------------------------------------------------------------------------------
+template <typename T>
+inline T PropertyGet(const PropertyTable *in, const std::string &name, bool &result, bool useTemplate = false) {
+ PropertyPtr prop = in->Get(name);
+ if (nullptr == prop) {
+ if (!useTemplate) {
+ result = false;
+ return T();
+ }
+ const PropertyTable *templ = in->TemplateProps();
+ if (nullptr == templ) {
+ result = false;
+ return T();
+ }
+ prop = templ->Get(name);
+ if (nullptr == prop) {
+ result = false;
+ return T();
+ }
+ }
+
+ // strong typing, no need to be lenient
+ const TypedProperty<T> *const tprop = prop->As<TypedProperty<T>>();
+ if (nullptr == tprop) {
+ result = false;
+ return T();
+ }
+
+ result = true;
+ return tprop->Value();
+}
+} // namespace FBXDocParser
+
+#endif // FBX_PROPERTIES_H
diff --git a/modules/fbx/fbx_parser/FBXTokenizer.cpp b/modules/fbx/fbx_parser/FBXTokenizer.cpp
new file mode 100644
index 0000000000..ea4568fe32
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXTokenizer.cpp
@@ -0,0 +1,251 @@
+/*************************************************************************/
+/* FBXTokenizer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXTokenizer.cpp
+ * @brief Implementation of the FBX broadphase lexer
+ */
+
+// tab width for logging columns
+#define ASSIMP_FBX_TAB_WIDTH 4
+
+#include "FBXTokenizer.h"
+#include "core/string/print_string.h"
+
+namespace FBXDocParser {
+
+// ------------------------------------------------------------------------------------------------
+Token::Token(const char *p_sbegin, const char *p_send, TokenType p_type, unsigned int p_line, unsigned int p_column) :
+ sbegin(p_sbegin),
+ send(p_send),
+ type(p_type),
+ line(p_line),
+ column(p_column) {
+#ifdef DEBUG_ENABLED
+ contents = std::string(sbegin, static_cast<size_t>(send - sbegin));
+#endif
+}
+
+// ------------------------------------------------------------------------------------------------
+Token::~Token() {
+}
+
+namespace {
+
+// ------------------------------------------------------------------------------------------------
+void TokenizeError(const std::string &message, unsigned int line, unsigned int column) {
+ print_error("[FBX-Tokenize]" + String(message.c_str()) + " " + itos(line) + ":" + itos(column));
+}
+
+// process a potential data token up to 'cur', adding it to 'output_tokens'.
+// ------------------------------------------------------------------------------------------------
+void ProcessDataToken(TokenList &output_tokens, const char *&start, const char *&end,
+ unsigned int line,
+ unsigned int column,
+ TokenType type = TokenType_DATA,
+ bool must_have_token = false) {
+ if (start && end) {
+ // sanity check:
+ // tokens should have no whitespace outside quoted text and [start,end] should
+ // properly delimit the valid range.
+ bool in_double_quotes = false;
+ for (const char *c = start; c != end + 1; ++c) {
+ if (*c == '\"') {
+ in_double_quotes = !in_double_quotes;
+ }
+
+ if (!in_double_quotes && IsSpaceOrNewLine(*c)) {
+ TokenizeError("unexpected whitespace in token", line, column);
+ }
+ }
+
+ if (in_double_quotes) {
+ TokenizeError("non-terminated double quotes", line, column);
+ }
+
+ output_tokens.push_back(new_Token(start, end + 1, type, line, column));
+ } else if (must_have_token) {
+ TokenizeError("unexpected character, expected data token", line, column);
+ }
+
+ start = end = nullptr;
+}
+} // namespace
+
+// ------------------------------------------------------------------------------------------------
+void Tokenize(TokenList &output_tokens, const char *input, size_t length) {
+ // line and column numbers numbers are one-based
+ unsigned int line = 1;
+ unsigned int column = 1;
+
+ bool comment = false;
+ bool in_double_quotes = false;
+ bool pending_data_token = false;
+
+ const char *token_begin = nullptr, *token_end = nullptr;
+
+ // input (starting string), *cur the current string, column +=
+ // modified to fix strlen() and stop buffer overflow
+ for (size_t x = 0; x < length; x++) {
+ const char c = input[x];
+ const char *cur = &input[x];
+ column += (c == '\t' ? ASSIMP_FBX_TAB_WIDTH : 1);
+
+ if (IsLineEnd(c)) {
+ comment = false;
+
+ column = 0;
+ ++line;
+ }
+
+ if (comment) {
+ continue;
+ }
+
+ if (in_double_quotes) {
+ if (c == '\"') {
+ in_double_quotes = false;
+ token_end = cur;
+
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column);
+ pending_data_token = false;
+ }
+ continue;
+ }
+
+ switch (c) {
+ case '\"':
+ if (token_begin) {
+ TokenizeError("unexpected double-quote", line, column);
+ }
+ token_begin = cur;
+ in_double_quotes = true;
+ continue;
+
+ case ';':
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column);
+ comment = true;
+ continue;
+
+ case '{':
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column);
+ output_tokens.push_back(new_Token(cur, cur + 1, TokenType_OPEN_BRACKET, line, column));
+ continue;
+
+ case '}':
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column);
+ output_tokens.push_back(new_Token(cur, cur + 1, TokenType_CLOSE_BRACKET, line, column));
+ continue;
+
+ case ',':
+ if (pending_data_token) {
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column, TokenType_DATA, true);
+ }
+ output_tokens.push_back(new_Token(cur, cur + 1, TokenType_COMMA, line, column));
+ continue;
+
+ case ':':
+ if (pending_data_token) {
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column, TokenType_KEY, true);
+ } else {
+ TokenizeError("unexpected colon", line, column);
+ }
+ continue;
+ }
+
+ if (IsSpaceOrNewLine(c)) {
+ if (token_begin) {
+ // peek ahead and check if the next token is a colon in which
+ // case this counts as KEY token.
+ TokenType type = TokenType_DATA;
+ for (const char *peek = cur; *peek && IsSpaceOrNewLine(*peek); ++peek) {
+ if (*peek == ':') {
+ type = TokenType_KEY;
+ cur = peek;
+ break;
+ }
+ }
+
+ ProcessDataToken(output_tokens, token_begin, token_end, line, column, type);
+ }
+
+ pending_data_token = false;
+ } else {
+ token_end = cur;
+ if (!token_begin) {
+ token_begin = cur;
+ }
+
+ pending_data_token = true;
+ }
+ }
+}
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXTokenizer.h b/modules/fbx/fbx_parser/FBXTokenizer.h
new file mode 100644
index 0000000000..1e7e5e6535
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXTokenizer.h
@@ -0,0 +1,203 @@
+/*************************************************************************/
+/* FBXTokenizer.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXTokenizer.h
+ * @brief FBX lexer
+ */
+#ifndef FBX_TOKENIZER_H
+#define FBX_TOKENIZER_H
+
+#include "FBXParseTools.h"
+#include "core/string/ustring.h"
+#include <iostream>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace FBXDocParser {
+/** Rough classification for text FBX tokens used for constructing the
+ * basic scope hierarchy. */
+enum TokenType {
+ // {
+ TokenType_OPEN_BRACKET = 0,
+
+ // }
+ TokenType_CLOSE_BRACKET,
+
+ // '"blablubb"', '2', '*14' - very general token class,
+ // further processing happens at a later stage.
+ TokenType_DATA,
+
+ //
+ TokenType_BINARY_DATA,
+
+ // ,
+ TokenType_COMMA,
+
+ // blubb:
+ TokenType_KEY
+};
+
+/** Represents a single token in a FBX file. Tokens are
+ * classified by the #TokenType enumerated types.
+ *
+ * Offers iterator protocol. Tokens are immutable. */
+class Token {
+private:
+ static const unsigned int BINARY_MARKER = static_cast<unsigned int>(-1);
+
+public:
+ /** construct a textual token */
+ Token(const char *p_sbegin, const char *p_send, TokenType p_type, unsigned int p_line, unsigned int p_column);
+
+ /** construct a binary token */
+ Token(const char *p_sbegin, const char *p_send, TokenType p_type, size_t p_offset);
+ ~Token();
+
+public:
+ std::string StringContents() const {
+ return std::string(begin(), end());
+ }
+
+ bool IsBinary() const {
+ return column == BINARY_MARKER;
+ }
+
+ const char *begin() const {
+ return sbegin;
+ }
+
+ const char *end() const {
+ return send;
+ }
+
+ TokenType Type() const {
+ return type;
+ }
+
+ size_t Offset() const {
+ return offset;
+ }
+
+ unsigned int Line() const {
+ return static_cast<unsigned int>(line);
+ }
+
+ unsigned int Column() const {
+ return column;
+ }
+
+private:
+#ifdef DEBUG_ENABLED
+ // full string copy for the sole purpose that it nicely appears
+ // in msvc's debugger window.
+ std::string contents;
+#endif
+
+ const char *sbegin = nullptr;
+ const char *send = nullptr;
+ const TokenType type;
+
+ union {
+ size_t line;
+ size_t offset;
+ };
+ const unsigned int column = 0;
+};
+
+// Fixed leak by using shared_ptr for tokens
+typedef Token *TokenPtr;
+typedef std::vector<TokenPtr> TokenList;
+
+#define new_Token new Token
+
+/** Main FBX tokenizer function. Transform input buffer into a list of preprocessed tokens.
+ *
+ * Skips over comments and generates line and column numbers.
+ *
+ * @param output_tokens Receives a list of all tokens in the input data.
+ * @param input_buffer Textual input buffer to be processed, 0-terminated.
+ * @print_error if something goes wrong */
+void Tokenize(TokenList &output_tokens, const char *input, size_t length);
+
+/** Tokenizer function for binary FBX files.
+ *
+ * Emits a token list suitable for direct parsing.
+ *
+ * @param output_tokens Receives a list of all tokens in the input data.
+ * @param input_buffer Binary input buffer to be processed.
+ * @param length Length of input buffer, in bytes. There is no 0-terminal.
+ * @print_error if something goes wrong */
+void TokenizeBinary(TokenList &output_tokens, const char *input, size_t length);
+} // namespace FBXDocParser
+
+#endif // FBX_TOKENIZER_H
diff --git a/modules/fbx/fbx_parser/FBXUtil.cpp b/modules/fbx/fbx_parser/FBXUtil.cpp
new file mode 100644
index 0000000000..80ea5fab4c
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXUtil.cpp
@@ -0,0 +1,220 @@
+/*************************************************************************/
+/* FBXUtil.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXUtil.cpp
+ * @brief Implementation of internal FBX utility functions
+ */
+
+#include "FBXUtil.h"
+#include "FBXTokenizer.h"
+#include <cstring>
+#include <string>
+
+namespace FBXDocParser {
+namespace Util {
+
+// ------------------------------------------------------------------------------------------------
+const char *TokenTypeString(TokenType t) {
+ switch (t) {
+ case TokenType_OPEN_BRACKET:
+ return "TOK_OPEN_BRACKET";
+
+ case TokenType_CLOSE_BRACKET:
+ return "TOK_CLOSE_BRACKET";
+
+ case TokenType_DATA:
+ return "TOK_DATA";
+
+ case TokenType_COMMA:
+ return "TOK_COMMA";
+
+ case TokenType_KEY:
+ return "TOK_KEY";
+
+ case TokenType_BINARY_DATA:
+ return "TOK_BINARY_DATA";
+ }
+
+ //ai_assert(false);
+ return "";
+}
+
+// Generated by this formula: T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;
+static const uint8_t base64DecodeTable[128] = {
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,
+ 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
+ 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255
+};
+
+uint8_t DecodeBase64(char ch) {
+ const auto idx = static_cast<uint8_t>(ch);
+ if (idx > 127)
+ return 255;
+ return base64DecodeTable[idx];
+}
+
+size_t ComputeDecodedSizeBase64(const char *in, size_t inLength) {
+ if (inLength < 2) {
+ return 0;
+ }
+ const size_t equals = size_t(in[inLength - 1] == '=') + size_t(in[inLength - 2] == '=');
+ const size_t full_length = (inLength * 3) >> 2; // div by 4
+ if (full_length < equals) {
+ return 0;
+ }
+ return full_length - equals;
+}
+
+size_t DecodeBase64(const char *in, size_t inLength, uint8_t *out, size_t maxOutLength) {
+ if (maxOutLength == 0 || inLength < 2) {
+ return 0;
+ }
+ const size_t realLength = inLength - size_t(in[inLength - 1] == '=') - size_t(in[inLength - 2] == '=');
+ size_t dst_offset = 0;
+ int val = 0, valb = -8;
+ for (size_t src_offset = 0; src_offset < realLength; ++src_offset) {
+ const uint8_t table_value = Util::DecodeBase64(in[src_offset]);
+ if (table_value == 255) {
+ return 0;
+ }
+ val = (val << 6) + table_value;
+ valb += 6;
+ if (valb >= 0) {
+ out[dst_offset++] = static_cast<uint8_t>((val >> valb) & 0xFF);
+ valb -= 8;
+ val &= 0xFFF;
+ }
+ }
+ return dst_offset;
+}
+
+static const char to_base64_string[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+char EncodeBase64(char byte) {
+ return to_base64_string[(size_t)byte];
+}
+
+/** Encodes a block of 4 bytes to base64 encoding
+* @param bytes Bytes to encode.
+* @param out_string String to write encoded values to.
+* @param string_pos Position in out_string.
+*/
+void EncodeByteBlock(const char *bytes, std::string &out_string, size_t string_pos) {
+ char b0 = (bytes[0] & 0xFC) >> 2;
+ char b1 = (bytes[0] & 0x03) << 4 | ((bytes[1] & 0xF0) >> 4);
+ char b2 = (bytes[1] & 0x0F) << 2 | ((bytes[2] & 0xC0) >> 6);
+ char b3 = (bytes[2] & 0x3F);
+
+ out_string[string_pos + 0] = EncodeBase64(b0);
+ out_string[string_pos + 1] = EncodeBase64(b1);
+ out_string[string_pos + 2] = EncodeBase64(b2);
+ out_string[string_pos + 3] = EncodeBase64(b3);
+}
+
+std::string EncodeBase64(const char *data, size_t length) {
+ // calculate extra bytes needed to get a multiple of 3
+ size_t extraBytes = 3 - length % 3;
+
+ // number of base64 bytes
+ size_t encodedBytes = 4 * (length + extraBytes) / 3;
+
+ std::string encoded_string(encodedBytes, '=');
+
+ // read blocks of 3 bytes
+ for (size_t ib3 = 0; ib3 < length / 3; ib3++) {
+ const size_t iByte = ib3 * 3;
+ const size_t iEncodedByte = ib3 * 4;
+ const char *currData = &data[iByte];
+
+ EncodeByteBlock(currData, encoded_string, iEncodedByte);
+ }
+
+ // if size of data is not a multiple of 3, also encode the final bytes (and add zeros where needed)
+ if (extraBytes > 0) {
+ char finalBytes[4] = { 0, 0, 0, 0 };
+ memcpy(&finalBytes[0], &data[length - length % 3], length % 3);
+
+ const size_t iEncodedByte = encodedBytes - 4;
+ EncodeByteBlock(&finalBytes[0], encoded_string, iEncodedByte);
+
+ // add '=' at the end
+ for (size_t i = 0; i < 4 * extraBytes / 3; i++)
+ encoded_string[encodedBytes - i - 1] = '=';
+ }
+ return encoded_string;
+}
+} // namespace Util
+} // namespace FBXDocParser
diff --git a/modules/fbx/fbx_parser/FBXUtil.h b/modules/fbx/fbx_parser/FBXUtil.h
new file mode 100644
index 0000000000..efc131831b
--- /dev/null
+++ b/modules/fbx/fbx_parser/FBXUtil.h
@@ -0,0 +1,122 @@
+/*************************************************************************/
+/* FBXUtil.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+/*
+Open Asset Import Library (assimp)
+----------------------------------------------------------------------
+
+Copyright (c) 2006-2019, assimp team
+
+
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+----------------------------------------------------------------------
+*/
+
+/** @file FBXUtil.h
+ * @brief FBX utility functions for internal use
+ */
+#ifndef FBX_UTIL_H
+#define FBX_UTIL_H
+
+#include "FBXTokenizer.h"
+#include <stdint.h>
+
+namespace FBXDocParser {
+
+namespace Util {
+
+/** Get a string representation for a #TokenType. */
+const char *TokenTypeString(TokenType t);
+
+/** Decode a single Base64-encoded character.
+*
+* @param ch Character to decode (from base64 to binary).
+* @return decoded byte value*/
+uint8_t DecodeBase64(char ch);
+
+/** Compute decoded size of a Base64-encoded string
+*
+* @param in Characters to decode.
+* @param inLength Number of characters to decode.
+* @return size of the decoded data (number of bytes)*/
+size_t ComputeDecodedSizeBase64(const char *in, size_t inLength);
+
+/** Decode a Base64-encoded string
+*
+* @param in Characters to decode.
+* @param inLength Number of characters to decode.
+* @param out Pointer where we will store the decoded data.
+* @param maxOutLength Size of output buffer.
+* @return size of the decoded data (number of bytes)*/
+size_t DecodeBase64(const char *in, size_t inLength, uint8_t *out, size_t maxOutLength);
+
+char EncodeBase64(char byte);
+
+/** Encode bytes in base64-encoding
+*
+* @param data Binary data to encode.
+* @param inLength Number of bytes to encode.
+* @return base64-encoded string*/
+std::string EncodeBase64(const char *data, size_t length);
+} // namespace Util
+} // namespace FBXDocParser
+
+#endif // FBX_UTIL_H
diff --git a/modules/fbx/fbx_parser/LICENSE b/modules/fbx/fbx_parser/LICENSE
new file mode 100644
index 0000000000..b42fc6efe6
--- /dev/null
+++ b/modules/fbx/fbx_parser/LICENSE
@@ -0,0 +1,39 @@
+The files in this folder were originally from ASSIMP, but have been heavily modified to fix bugs and match coding
+conventions of the Godot Engine project. We have kept a copy of the applicable licenses in the folder as required by
+the license.
+
+Open Asset Import Library (assimp)
+
+Copyright (c) 2006-2020, assimp team
+All rights reserved.
+
+Redistribution and use of this software in source and binary forms,
+with or without modification, are permitted provided that the
+following conditions are met:
+
+* Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the
+ following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the
+ following disclaimer in the documentation and/or other
+ materials provided with the distribution.
+
+* Neither the name of the assimp team, nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior
+ written permission of the assimp team.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
diff --git a/modules/assimp/register_types.cpp b/modules/fbx/register_types.cpp
index 3af8827bf9..c0591dbc77 100644
--- a/modules/assimp/register_types.cpp
+++ b/modules/fbx/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,23 +31,22 @@
#include "register_types.h"
#include "editor/editor_node.h"
-#include "editor_scene_importer_assimp.h"
+#include "editor_scene_importer_fbx.h"
#ifdef TOOLS_ENABLED
static void _editor_init() {
- Ref<EditorSceneImporterAssimp> import_assimp;
- import_assimp.instance();
- ResourceImporterScene::get_singleton()->add_importer(import_assimp);
+ Ref<EditorSceneImporterFBX> import_fbx;
+ import_fbx.instance();
+ ResourceImporterScene::get_singleton()->add_importer(import_fbx);
}
#endif
-void register_assimp_types() {
-
+void register_fbx_types() {
#ifdef TOOLS_ENABLED
ClassDB::APIType prev_api = ClassDB::get_current_api();
ClassDB::set_current_api(ClassDB::API_EDITOR);
- ClassDB::register_class<EditorSceneImporterAssimp>();
+ ClassDB::register_class<EditorSceneImporterFBX>();
ClassDB::set_current_api(prev_api);
@@ -55,5 +54,5 @@ void register_assimp_types() {
#endif
}
-void unregister_assimp_types() {
+void unregister_fbx_types() {
}
diff --git a/modules/assimp/register_types.h b/modules/fbx/register_types.h
index f399a7acc6..e5741afd72 100644
--- a/modules/assimp/register_types.h
+++ b/modules/fbx/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,10 +28,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef ASSIMP_REGISTER_TYPES_H
-#define ASSIMP_REGISTER_TYPES_H
+#ifndef FBX_REGISTER_TYPES_H
+#define FBX_REGISTER_TYPES_H
-void register_assimp_types();
-void unregister_assimp_types();
+void register_fbx_types();
+void unregister_fbx_types();
-#endif // ASSIMP_REGISTER_TYPES_H
+#endif // FBX_REGISTER_TYPES_H
diff --git a/modules/fbx/tools/import_utils.cpp b/modules/fbx/tools/import_utils.cpp
new file mode 100644
index 0000000000..c87dd1fd3a
--- /dev/null
+++ b/modules/fbx/tools/import_utils.cpp
@@ -0,0 +1,151 @@
+/*************************************************************************/
+/* import_utils.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "import_utils.h"
+
+Vector3 ImportUtils::deg2rad(const Vector3 &p_rotation) {
+ return p_rotation / 180.0 * Math_PI;
+}
+
+Vector3 ImportUtils::rad2deg(const Vector3 &p_rotation) {
+ return p_rotation / Math_PI * 180.0;
+}
+
+Basis ImportUtils::EulerToBasis(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation) {
+ Basis ret;
+
+ // FBX is using intrinsic euler, we can convert intrinsic to extrinsic (the one used in godot
+ // by simply invert its order: https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf
+ switch (mode) {
+ case FBXDocParser::Model::RotOrder_EulerXYZ:
+ ret.set_euler_zyx(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_EulerXZY:
+ ret.set_euler_yzx(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_EulerYZX:
+ ret.set_euler_xzy(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_EulerYXZ:
+ ret.set_euler_zxy(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_EulerZXY:
+ ret.set_euler_yxz(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_EulerZYX:
+ ret.set_euler_xyz(p_rotation);
+ break;
+
+ case FBXDocParser::Model::RotOrder_SphericXYZ:
+ // TODO do this.
+ break;
+
+ default:
+ // If you land here, Please integrate all enums.
+ CRASH_NOW_MSG("This is not unreachable.");
+ }
+
+ return ret;
+}
+
+Quat ImportUtils::EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation) {
+ return ImportUtils::EulerToBasis(mode, p_rotation);
+}
+
+Vector3 ImportUtils::BasisToEuler(FBXDocParser::Model::RotOrder mode, const Basis &p_rotation) {
+ // FBX is using intrinsic euler, we can convert intrinsic to extrinsic (the one used in godot
+ // by simply invert its order: https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf
+ switch (mode) {
+ case FBXDocParser::Model::RotOrder_EulerXYZ:
+ return p_rotation.get_euler_zyx();
+
+ case FBXDocParser::Model::RotOrder_EulerXZY:
+ return p_rotation.get_euler_yzx();
+
+ case FBXDocParser::Model::RotOrder_EulerYZX:
+ return p_rotation.get_euler_xzy();
+
+ case FBXDocParser::Model::RotOrder_EulerYXZ:
+ return p_rotation.get_euler_zxy();
+
+ case FBXDocParser::Model::RotOrder_EulerZXY:
+ return p_rotation.get_euler_yxz();
+
+ case FBXDocParser::Model::RotOrder_EulerZYX:
+ return p_rotation.get_euler_xyz();
+
+ case FBXDocParser::Model::RotOrder_SphericXYZ:
+ // TODO
+ return Vector3();
+
+ default:
+ // If you land here, Please integrate all enums.
+ CRASH_NOW_MSG("This is not unreachable.");
+ return Vector3();
+ }
+}
+
+Vector3 ImportUtils::QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quat &p_rotation) {
+ return BasisToEuler(mode, p_rotation);
+}
+
+Transform get_unscaled_transform(const Transform &p_initial, real_t p_scale) {
+ Transform unscaled = Transform(p_initial.basis, p_initial.origin * p_scale);
+ ERR_FAIL_COND_V_MSG(unscaled.basis.determinant() == 0, Transform(), "det is zero unscaled?");
+ return unscaled;
+}
+
+Vector3 get_poly_normal(const std::vector<Vector3> &p_vertices) {
+ ERR_FAIL_COND_V_MSG(p_vertices.size() < 3, Vector3(0, 0, 0), "At least 3 vertices are necesary");
+ // Using long double to make sure that normal is computed for even really tiny objects.
+ typedef long double ldouble;
+ ldouble x = 0.0;
+ ldouble y = 0.0;
+ ldouble z = 0.0;
+ for (size_t i = 0; i < p_vertices.size(); i += 1) {
+ const Vector3 current = p_vertices[i];
+ const Vector3 next = p_vertices[(i + 1) % p_vertices.size()];
+ x += (ldouble(current.y) - ldouble(next.y)) * (ldouble(current.z) + ldouble(next.z));
+ y += (ldouble(current.z) - ldouble(next.z)) * (ldouble(current.x) + ldouble(next.x));
+ z += (ldouble(current.x) - ldouble(next.x)) * (ldouble(current.y) + ldouble(next.y));
+ }
+ const ldouble l2 = x * x + y * y + z * z;
+ if (l2 == 0.0) {
+ return (p_vertices[0] - p_vertices[1]).normalized().cross((p_vertices[0] - p_vertices[2]).normalized()).normalized();
+ } else {
+ const double l = Math::sqrt(double(l2));
+ return Vector3(x / l, y / l, z / l);
+ }
+}
diff --git a/modules/fbx/tools/import_utils.h b/modules/fbx/tools/import_utils.h
new file mode 100644
index 0000000000..6261138812
--- /dev/null
+++ b/modules/fbx/tools/import_utils.h
@@ -0,0 +1,400 @@
+/*************************************************************************/
+/* import_utils.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 IMPORT_UTILS_FBX_IMPORTER_H
+#define IMPORT_UTILS_FBX_IMPORTER_H
+
+#include "core/io/image_loader.h"
+
+#include "data/import_state.h"
+#include "fbx_parser/FBXDocument.h"
+
+#include <string>
+
+#define CONVERT_FBX_TIME(time) static_cast<double>(time) / 46186158000LL
+
+/**
+ * Import Utils
+ * Conversion tools / glue code to convert from FBX to Godot
+*/
+class ImportUtils {
+public:
+ /// Convert a vector from degrees to radians.
+ static Vector3 deg2rad(const Vector3 &p_rotation);
+
+ /// Convert a vector from radians to degrees.
+ static Vector3 rad2deg(const Vector3 &p_rotation);
+
+ /// Converts rotation order vector (in rad) to quaternion.
+ static Basis EulerToBasis(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation);
+
+ /// Converts rotation order vector (in rad) to quaternion.
+ static Quat EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation);
+
+ /// Converts basis into rotation order vector (in rad).
+ static Vector3 BasisToEuler(FBXDocParser::Model::RotOrder mode, const Basis &p_rotation);
+
+ /// Converts quaternion into rotation order vector (in rad).
+ static Vector3 QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quat &p_rotation);
+
+ static void debug_xform(String name, const Transform &t) {
+ print_verbose(name + " " + t.origin + " rotation: " + (t.basis.get_euler() * (180 / Math_PI)));
+ }
+
+ static String FBXNodeToName(const std::string &name) {
+ // strip Model:: prefix, avoiding ambiguities (i.e. don't strip if
+ // this causes ambiguities, well possible between empty identifiers,
+ // such as "Model::" and ""). Make sure the behaviour is consistent
+ // across multiple calls to FixNodeName().
+
+ // We must remove this from the name
+ // Some bones have this
+ // SubDeformer::
+ // Meshes, Joints have this, some other IK elements too.
+ // Model::
+
+ String node_name = String(name.c_str());
+
+ if (node_name.substr(0, 7) == "Model::") {
+ node_name = node_name.substr(7, node_name.length() - 7);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 13) == "SubDeformer::") {
+ node_name = node_name.substr(13, node_name.length() - 13);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 11) == "AnimStack::") {
+ node_name = node_name.substr(11, node_name.length() - 11);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 15) == "AnimCurveNode::") {
+ node_name = node_name.substr(15, node_name.length() - 15);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 11) == "AnimCurve::") {
+ node_name = node_name.substr(11, node_name.length() - 11);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 10) == "Geometry::") {
+ node_name = node_name.substr(10, node_name.length() - 10);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 10) == "Material::") {
+ node_name = node_name.substr(10, node_name.length() - 10);
+ return node_name.replace(":", "");
+ }
+
+ if (node_name.substr(0, 9) == "Texture::") {
+ node_name = node_name.substr(9, node_name.length() - 9);
+ return node_name.replace(":", "");
+ }
+
+ return node_name.replace(":", "");
+ }
+
+ static std::string FBXAnimMeshName(const std::string &name) {
+ if (name.length()) {
+ size_t indexOf = name.find_first_of("::");
+ if (indexOf != std::string::npos && indexOf < name.size() - 2) {
+ return name.substr(indexOf + 2);
+ }
+ }
+ return name.length() ? name : "AnimMesh";
+ }
+
+ static Vector3 safe_import_vector3(const Vector3 &p_vec) {
+ Vector3 vector = p_vec;
+ if (Math::is_equal_approx(0, vector.x)) {
+ vector.x = 0;
+ }
+
+ if (Math::is_equal_approx(0, vector.y)) {
+ vector.y = 0;
+ }
+
+ if (Math::is_equal_approx(0, vector.z)) {
+ vector.z = 0;
+ }
+ return vector;
+ }
+
+ static void debug_xform(String name, const Basis &t) {
+ //print_verbose(name + " rotation: " + (t.get_euler() * (180 / Math_PI)));
+ }
+
+ static Vector3 FixAxisConversions(Vector3 input) {
+ return Vector3(input.x, input.y, input.z);
+ }
+
+ static void AlignMeshAxes(std::vector<Vector3> &vertex_data) {
+ for (size_t x = 0; x < vertex_data.size(); x++) {
+ vertex_data[x] = FixAxisConversions(vertex_data[x]);
+ }
+ }
+
+ struct AssetImportFbx {
+ enum ETimeMode {
+ TIME_MODE_DEFAULT = 0,
+ TIME_MODE_120 = 1,
+ TIME_MODE_100 = 2,
+ TIME_MODE_60 = 3,
+ TIME_MODE_50 = 4,
+ TIME_MODE_48 = 5,
+ TIME_MODE_30 = 6,
+ TIME_MODE_30_DROP = 7,
+ TIME_MODE_NTSC_DROP_FRAME = 8,
+ TIME_MODE_NTSC_FULL_FRAME = 9,
+ TIME_MODE_PAL = 10,
+ TIME_MODE_CINEMA = 11,
+ TIME_MODE_1000 = 12,
+ TIME_MODE_CINEMA_ND = 13,
+ TIME_MODE_CUSTOM = 14,
+ TIME_MODE_TIME_MODE_COUNT = 15
+ };
+ enum UpAxis {
+ UP_VECTOR_AXIS_X = 1,
+ UP_VECTOR_AXIS_Y = 2,
+ UP_VECTOR_AXIS_Z = 3
+ };
+ enum FrontAxis {
+ FRONT_PARITY_EVEN = 1,
+ FRONT_PARITY_ODD = 2,
+ };
+
+ enum CoordAxis {
+ COORD_RIGHT = 0,
+ COORD_LEFT = 1
+ };
+ };
+
+ /** Get fbx fps for time mode meta data
+ */
+ static float get_fbx_fps(int32_t time_mode) {
+ switch (time_mode) {
+ case AssetImportFbx::TIME_MODE_DEFAULT:
+ return 24;
+ case AssetImportFbx::TIME_MODE_120:
+ return 120;
+ case AssetImportFbx::TIME_MODE_100:
+ return 100;
+ case AssetImportFbx::TIME_MODE_60:
+ return 60;
+ case AssetImportFbx::TIME_MODE_50:
+ return 50;
+ case AssetImportFbx::TIME_MODE_48:
+ return 48;
+ case AssetImportFbx::TIME_MODE_30:
+ return 30;
+ case AssetImportFbx::TIME_MODE_30_DROP:
+ return 30;
+ case AssetImportFbx::TIME_MODE_NTSC_DROP_FRAME:
+ return 29.9700262f;
+ case AssetImportFbx::TIME_MODE_NTSC_FULL_FRAME:
+ return 29.9700262f;
+ case AssetImportFbx::TIME_MODE_PAL:
+ return 25;
+ case AssetImportFbx::TIME_MODE_CINEMA:
+ return 24;
+ case AssetImportFbx::TIME_MODE_1000:
+ return 1000;
+ case AssetImportFbx::TIME_MODE_CINEMA_ND:
+ return 23.976f;
+ case AssetImportFbx::TIME_MODE_CUSTOM:
+ return -1;
+ }
+ return 0;
+ }
+
+ static float get_fbx_fps(const FBXDocParser::FileGlobalSettings *FBXSettings) {
+ int time_mode = FBXSettings->TimeMode();
+
+ // get the animation FPS
+ float frames_per_second = get_fbx_fps(time_mode);
+
+ // handle animation custom FPS time.
+ if (time_mode == ImportUtils::AssetImportFbx::TIME_MODE_CUSTOM) {
+ print_verbose("FBX Animation has custom FPS setting");
+ frames_per_second = FBXSettings->CustomFrameRate();
+
+ // not our problem this is the modeller, we can print as an error so they can fix the source.
+ if (frames_per_second == 0) {
+ print_error("Custom animation time in file is set to 0 value, animation won't play, please edit your file to correct the FPS value");
+ }
+ }
+ return frames_per_second;
+ }
+
+ /**
+ * Find hardcoded textures from assimp which could be in many different directories
+ */
+
+ /**
+ * set_texture_mapping_mode
+ * Helper to check the mapping mode of the texture (repeat, clamp and mirror)
+ */
+ // static void set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<ImageTexture> texture) {
+ // ERR_FAIL_COND(texture.is_null());
+ // ERR_FAIL_COND(map_mode == NULL);
+ // aiTextureMapMode tex_mode = map_mode[0];
+
+ // int32_t flags = Texture::FLAGS_DEFAULT;
+ // if (tex_mode == aiTextureMapMode_Wrap) {
+ // //Default
+ // } else if (tex_mode == aiTextureMapMode_Clamp) {
+ // flags = flags & ~Texture::FLAG_REPEAT;
+ // } else if (tex_mode == aiTextureMapMode_Mirror) {
+ // flags = flags | Texture::FLAG_MIRRORED_REPEAT;
+ // }
+ // texture->set_flags(flags);
+ // }
+
+ /**
+ * Load or load from cache image :)
+ * We need to upgrade this in the later version :) should not be hard
+ */
+ //static Ref<Image> load_image(ImportState &state, const aiScene *p_scene, String p_path){
+ // Map<String, Ref<Image> >::Element *match = state.path_to_image_cache.find(p_path);
+
+ // // if our cache contains this image then don't bother
+ // if (match) {
+ // return match->get();
+ // }
+
+ // Vector<String> split_path = p_path.get_basename().split("*");
+ // if (split_path.size() == 2) {
+ // size_t texture_idx = split_path[1].to_int();
+ // ERR_FAIL_COND_V(texture_idx >= p_scene->mNumTextures, Ref<Image>());
+ // aiTexture *tex = p_scene->mTextures[texture_idx];
+ // String filename = AssimpUtils::get_raw_string_from_assimp(tex->mFilename);
+ // filename = filename.get_file();
+ // print_verbose("Open Asset Import: Loading embedded texture " + filename);
+ // if (tex->mHeight == 0) {
+ // if (tex->CheckFormat("png")) {
+ // Ref<Image> img = Image::_png_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
+ // ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
+ // state.path_to_image_cache.insert(p_path, img);
+ // return img;
+ // } else if (tex->CheckFormat("jpg")) {
+ // Ref<Image> img = Image::_jpg_mem_loader_func((uint8_t *)tex->pcData, tex->mWidth);
+ // ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
+ // state.path_to_image_cache.insert(p_path, img);
+ // return img;
+ // } else if (tex->CheckFormat("dds")) {
+ // ERR_FAIL_COND_V_MSG(true, Ref<Image>(), "Open Asset Import: Embedded dds not implemented");
+ // }
+ // } else {
+ // Ref<Image> img;
+ // img.instance();
+ // PoolByteArray arr;
+ // uint32_t size = tex->mWidth * tex->mHeight;
+ // arr.resize(size);
+ // memcpy(arr.write().ptr(), tex->pcData, size);
+ // ERR_FAIL_COND_V(arr.size() % 4 != 0, Ref<Image>());
+ // //ARGB8888 to RGBA8888
+ // for (int32_t i = 0; i < arr.size() / 4; i++) {
+ // arr.write().ptr()[(4 * i) + 3] = arr[(4 * i) + 0];
+ // arr.write().ptr()[(4 * i) + 0] = arr[(4 * i) + 1];
+ // arr.write().ptr()[(4 * i) + 1] = arr[(4 * i) + 2];
+ // arr.write().ptr()[(4 * i) + 2] = arr[(4 * i) + 3];
+ // }
+ // img->create(tex->mWidth, tex->mHeight, true, Image::FORMAT_RGBA8, arr);
+ // ERR_FAIL_COND_V(img.is_null(), Ref<Image>());
+ // state.path_to_image_cache.insert(p_path, img);
+ // return img;
+ // }
+ // return Ref<Image>();
+ // } else {
+ // Ref<Texture> texture = ResourceLoader::load(p_path);
+ // ERR_FAIL_COND_V(texture.is_null(), Ref<Image>());
+ // Ref<Image> image = texture->get_data();
+ // ERR_FAIL_COND_V(image.is_null(), Ref<Image>());
+ // state.path_to_image_cache.insert(p_path, image);
+ // return image;
+ // }
+
+ // return Ref<Image>();
+ //}
+
+ // /* create texture from assimp data, if found in path */
+ // static bool CreateAssimpTexture(
+ // AssimpImporter::ImportState &state,
+ // aiString texture_path,
+ // String &filename,
+ // String &path,
+ // AssimpImageData &image_state) {
+ // filename = get_raw_string_from_assimp(texture_path);
+ // path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
+ // bool found = false;
+ // find_texture_path(state.path, path, found);
+ // if (found) {
+ // image_state.raw_image = AssimpUtils::load_image(state, state.assimp_scene, path);
+ // if (image_state.raw_image.is_valid()) {
+ // image_state.texture.instance();
+ // image_state.texture->create_from_image(image_state.raw_image);
+ // image_state.texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
+ // return true;
+ // }
+ // }
+
+ // return false;
+ // }
+ // /** GetAssimpTexture
+ // * Designed to retrieve textures for you
+ // */
+ // static bool GetAssimpTexture(
+ // AssimpImporter::ImportState &state,
+ // aiMaterial *ai_material,
+ // aiTextureType texture_type,
+ // String &filename,
+ // String &path,
+ // AssimpImageData &image_state) {
+ // aiString ai_filename = aiString();
+ // if (AI_SUCCESS == ai_material->GetTexture(texture_type, 0, &ai_filename, NULL, NULL, NULL, NULL, image_state.map_mode)) {
+ // return CreateAssimpTexture(state, ai_filename, filename, path, image_state);
+ // }
+
+ // return false;
+ // }
+};
+
+// Apply the transforms so the basis will have scale 1.
+Transform get_unscaled_transform(const Transform &p_initial, real_t p_scale);
+
+/// Uses the Newell's method to compute any polygon normal.
+/// The polygon must be at least size of 3 or bigger.
+Vector3 get_poly_normal(const std::vector<Vector3> &p_vertices);
+
+#endif // IMPORT_UTILS_FBX_IMPORTER_H
diff --git a/modules/fbx/tools/validation_tools.cpp b/modules/fbx/tools/validation_tools.cpp
new file mode 100644
index 0000000000..9dbd8bf544
--- /dev/null
+++ b/modules/fbx/tools/validation_tools.cpp
@@ -0,0 +1,48 @@
+/*************************************************************************/
+/* validation_tools.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "validation_tools.h"
+
+#ifdef TOOLS_ENABLED
+
+#include "core/string/print_string.h"
+#include "core/string/ustring.h"
+
+ValidationTracker::Entries *ValidationTracker::entries_singleton = memnew(ValidationTracker::Entries);
+
+// for printing our CSV to dump validation problems of files
+// later we can make some agnostic tooling for this but this is fine for the time being.
+void ValidationTracker::Entries::add_validation_error(String asset_path, String message) {
+ print_error(message);
+ // note: implementation is static
+ validation_entries[asset_path].push_back(message);
+}
+
+#endif // TOOLS_ENABLED
diff --git a/modules/fbx/tools/validation_tools.h b/modules/fbx/tools/validation_tools.h
new file mode 100644
index 0000000000..ced100aed2
--- /dev/null
+++ b/modules/fbx/tools/validation_tools.h
@@ -0,0 +1,92 @@
+/*************************************************************************/
+/* validation_tools.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FBX_VALIDATION_TOOLS_H
+#define FBX_VALIDATION_TOOLS_H
+
+#ifdef TOOLS_ENABLED
+
+#include "core/io/json.h"
+#include "core/os/file_access.h"
+#include "core/string/ustring.h"
+#include "core/templates/local_vector.h"
+#include "core/templates/map.h"
+
+class ValidationTracker {
+protected:
+ struct Entries {
+ Map<String, LocalVector<String>> validation_entries = Map<String, LocalVector<String>>();
+
+ // for printing our CSV to dump validation problems of files
+ // later we can make some agnostic tooling for this but this is fine for the time being.
+ void add_validation_error(String asset_path, String message);
+ void print_to_csv() {
+ print_verbose("Exporting assset validation log please wait");
+ String massive_log_file;
+
+ String csv_header = "file_path, error message, extra data\n";
+ massive_log_file += csv_header;
+
+ for (Map<String, LocalVector<String>>::Element *element = validation_entries.front(); element; element = element->next()) {
+ for (unsigned int x = 0; x < element->value().size(); x++) {
+ const String &line_entry = element->key() + ", " + element->value()[x].c_escape() + "\n";
+ massive_log_file += line_entry;
+ }
+ }
+
+ String path = "asset_validation_errors.csv";
+ Error err;
+ FileAccess *file = FileAccess::open(path, FileAccess::WRITE, &err);
+ if (!file || err) {
+ if (file)
+ memdelete(file);
+ print_error("ValidationTracker Error - failed to create file - path: %s\n" + path);
+ return;
+ }
+
+ file->store_string(massive_log_file);
+ if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
+ print_error("ValidationTracker Error - failed to write to file - path: %s\n" + path);
+ }
+ file->close();
+ memdelete(file);
+ }
+ };
+ // asset path, error messages
+ static Entries *entries_singleton;
+
+public:
+ static Entries *get_singleton() {
+ return entries_singleton;
+ }
+};
+
+#endif // TOOLS_ENABLED
+#endif // FBX_VALIDATION_TOOLS_H
diff --git a/modules/freetype/SCsub b/modules/freetype/SCsub
index bfc1658bb4..fc2535a6ca 100644
--- a/modules/freetype/SCsub
+++ b/modules/freetype/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_freetype = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_freetype"]:
thirdparty_dir = "#thirdparty/freetype/"
thirdparty_sources = [
@@ -84,6 +87,7 @@ if env["builtin_freetype"]:
env_thirdparty = env_freetype.Clone()
env_thirdparty.disable_warnings()
lib = env_thirdparty.add_library("freetype_builtin", thirdparty_sources)
+ thirdparty_obj += lib
# Needs to be appended to arrive after libscene in the linker call,
# but we don't want it to arrive *after* system libs, so manual hack
@@ -98,5 +102,13 @@ if env["builtin_freetype"]:
if not inserted:
env.Append(LIBS=[lib])
+
# Godot source files
-env_freetype.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_freetype.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/freetype/register_types.cpp b/modules/freetype/register_types.cpp
index 15fa193183..e4e6a4c146 100644
--- a/modules/freetype/register_types.cpp
+++ b/modules/freetype/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/freetype/register_types.h b/modules/freetype/register_types.h
index aa8088d2e8..7a4f64b54b 100644
--- a/modules/freetype/register_types.h
+++ b/modules/freetype/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/freetype/uwpdef.h b/modules/freetype/uwpdef.h
index 2f9b2f4a53..f829edea67 100644
--- a/modules/freetype/uwpdef.h
+++ b/modules/freetype/uwpdef.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gamecenter/SCsub b/modules/gamecenter/SCsub
new file mode 100644
index 0000000000..72fbf7ab0e
--- /dev/null
+++ b/modules/gamecenter/SCsub
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_gamecenter = env_modules.Clone()
+
+# (iOS) Enable module support
+env_gamecenter.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])
+
+# (iOS) Build as separate static library
+modules_sources = []
+env_gamecenter.add_source_files(modules_sources, "*.cpp")
+env_gamecenter.add_source_files(modules_sources, "*.mm")
+mod_lib = env_modules.add_library("#bin/libgodot_gamecenter_module" + env["LIBSUFFIX"], modules_sources)
diff --git a/modules/gamecenter/config.py b/modules/gamecenter/config.py
new file mode 100644
index 0000000000..e68603fc93
--- /dev/null
+++ b/modules/gamecenter/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return platform == "iphone"
+
+
+def configure(env):
+ pass
diff --git a/modules/gamecenter/game_center.h b/modules/gamecenter/game_center.h
new file mode 100644
index 0000000000..1ac00ca126
--- /dev/null
+++ b/modules/gamecenter/game_center.h
@@ -0,0 +1,71 @@
+/*************************************************************************/
+/* game_center.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GAME_CENTER_H
+#define GAME_CENTER_H
+
+#include "core/object/class_db.h"
+
+class GameCenter : public Object {
+ GDCLASS(GameCenter, Object);
+
+ static GameCenter *instance;
+ static void _bind_methods();
+
+ List<Variant> pending_events;
+
+ bool authenticated;
+
+ void return_connect_error(const char *p_error_description);
+
+public:
+ Error authenticate();
+ bool is_authenticated();
+
+ Error post_score(Dictionary p_score);
+ Error award_achievement(Dictionary p_params);
+ void reset_achievements();
+ void request_achievements();
+ void request_achievement_descriptions();
+ Error show_game_center(Dictionary p_params);
+ Error request_identity_verification_signature();
+
+ void game_center_closed();
+
+ int get_pending_event_count();
+ Variant pop_pending_event();
+
+ static GameCenter *get_singleton();
+
+ GameCenter();
+ ~GameCenter();
+};
+
+#endif
diff --git a/modules/gamecenter/game_center.mm b/modules/gamecenter/game_center.mm
new file mode 100644
index 0000000000..b971bc1da3
--- /dev/null
+++ b/modules/gamecenter/game_center.mm
@@ -0,0 +1,380 @@
+/*************************************************************************/
+/* game_center.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "game_center.h"
+#import "platform/iphone/app_delegate.h"
+
+#import "game_center_delegate.h"
+#import "platform/iphone/view_controller.h"
+#import <GameKit/GameKit.h>
+
+GameCenter *GameCenter::instance = NULL;
+GodotGameCenterDelegate *gameCenterDelegate = nil;
+
+void GameCenter::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("authenticate"), &GameCenter::authenticate);
+ ClassDB::bind_method(D_METHOD("is_authenticated"), &GameCenter::is_authenticated);
+
+ ClassDB::bind_method(D_METHOD("post_score"), &GameCenter::post_score);
+ ClassDB::bind_method(D_METHOD("award_achievement", "achievement"), &GameCenter::award_achievement);
+ ClassDB::bind_method(D_METHOD("reset_achievements"), &GameCenter::reset_achievements);
+ ClassDB::bind_method(D_METHOD("request_achievements"), &GameCenter::request_achievements);
+ ClassDB::bind_method(D_METHOD("request_achievement_descriptions"), &GameCenter::request_achievement_descriptions);
+ ClassDB::bind_method(D_METHOD("show_game_center"), &GameCenter::show_game_center);
+ ClassDB::bind_method(D_METHOD("request_identity_verification_signature"), &GameCenter::request_identity_verification_signature);
+
+ ClassDB::bind_method(D_METHOD("get_pending_event_count"), &GameCenter::get_pending_event_count);
+ ClassDB::bind_method(D_METHOD("pop_pending_event"), &GameCenter::pop_pending_event);
+};
+
+Error GameCenter::authenticate() {
+ //if this class isn't available, game center isn't implemented
+ if ((NSClassFromString(@"GKLocalPlayer")) == nil) {
+ return ERR_UNAVAILABLE;
+ }
+
+ GKLocalPlayer *player = [GKLocalPlayer localPlayer];
+ ERR_FAIL_COND_V(![player respondsToSelector:@selector(authenticateHandler)], ERR_UNAVAILABLE);
+
+ UIViewController *root_controller = [[UIApplication sharedApplication] delegate].window.rootViewController;
+ ERR_FAIL_COND_V(!root_controller, FAILED);
+
+ // This handler is called several times. First when the view needs to be shown, then again
+ // after the view is cancelled or the user logs in. Or if the user's already logged in, it's
+ // called just once to confirm they're authenticated. This is why no result needs to be specified
+ // in the presentViewController phase. In this case, more calls to this function will follow.
+ _weakify(root_controller);
+ _weakify(player);
+ player.authenticateHandler = (^(UIViewController *controller, NSError *error) {
+ _strongify(root_controller);
+ _strongify(player);
+
+ if (controller) {
+ [root_controller presentViewController:controller animated:YES completion:nil];
+ } else {
+ Dictionary ret;
+ ret["type"] = "authentication";
+ if (player.isAuthenticated) {
+ ret["result"] = "ok";
+ if (@available(iOS 13, *)) {
+ ret["player_id"] = [player.teamPlayerID UTF8String];
+#if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
+ } else {
+ ret["player_id"] = [player.playerID UTF8String];
+#endif
+ }
+
+ GameCenter::get_singleton()->authenticated = true;
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ ret["error_description"] = [error.localizedDescription UTF8String];
+ GameCenter::get_singleton()->authenticated = false;
+ };
+
+ pending_events.push_back(ret);
+ };
+ });
+
+ return OK;
+};
+
+bool GameCenter::is_authenticated() {
+ return authenticated;
+};
+
+Error GameCenter::post_score(Dictionary p_score) {
+ ERR_FAIL_COND_V(!p_score.has("score") || !p_score.has("category"), ERR_INVALID_PARAMETER);
+ float score = p_score["score"];
+ String category = p_score["category"];
+
+ NSString *cat_str = [[NSString alloc] initWithUTF8String:category.utf8().get_data()];
+ GKScore *reporter = [[GKScore alloc] initWithLeaderboardIdentifier:cat_str];
+ reporter.value = score;
+
+ ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE);
+
+ [GKScore reportScores:@[ reporter ]
+ withCompletionHandler:^(NSError *error) {
+ Dictionary ret;
+ ret["type"] = "post_score";
+ if (error == nil) {
+ ret["result"] = "ok";
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ ret["error_description"] = [error.localizedDescription UTF8String];
+ };
+
+ pending_events.push_back(ret);
+ }];
+
+ return OK;
+};
+
+Error GameCenter::award_achievement(Dictionary p_params) {
+ ERR_FAIL_COND_V(!p_params.has("name") || !p_params.has("progress"), ERR_INVALID_PARAMETER);
+ String name = p_params["name"];
+ float progress = p_params["progress"];
+
+ NSString *name_str = [[NSString alloc] initWithUTF8String:name.utf8().get_data()];
+ GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier:name_str];
+ ERR_FAIL_COND_V(!achievement, FAILED);
+
+ ERR_FAIL_COND_V([GKAchievement respondsToSelector:@selector(reportAchievements)], ERR_UNAVAILABLE);
+
+ achievement.percentComplete = progress;
+ achievement.showsCompletionBanner = NO;
+ if (p_params.has("show_completion_banner")) {
+ achievement.showsCompletionBanner = p_params["show_completion_banner"] ? YES : NO;
+ }
+
+ [GKAchievement reportAchievements:@[ achievement ]
+ withCompletionHandler:^(NSError *error) {
+ Dictionary ret;
+ ret["type"] = "award_achievement";
+ if (error == nil) {
+ ret["result"] = "ok";
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ };
+
+ pending_events.push_back(ret);
+ }];
+
+ return OK;
+};
+
+void GameCenter::request_achievement_descriptions() {
+ [GKAchievementDescription loadAchievementDescriptionsWithCompletionHandler:^(NSArray *descriptions, NSError *error) {
+ Dictionary ret;
+ ret["type"] = "achievement_descriptions";
+ if (error == nil) {
+ ret["result"] = "ok";
+ PackedStringArray names;
+ PackedStringArray titles;
+ PackedStringArray unachieved_descriptions;
+ PackedStringArray achieved_descriptions;
+ PackedInt32Array maximum_points;
+ Array hidden;
+ Array replayable;
+
+ for (NSUInteger i = 0; i < [descriptions count]; i++) {
+ GKAchievementDescription *description = [descriptions objectAtIndex:i];
+
+ const char *str = [description.identifier UTF8String];
+ names.push_back(String::utf8(str != NULL ? str : ""));
+
+ str = [description.title UTF8String];
+ titles.push_back(String::utf8(str != NULL ? str : ""));
+
+ str = [description.unachievedDescription UTF8String];
+ unachieved_descriptions.push_back(String::utf8(str != NULL ? str : ""));
+
+ str = [description.achievedDescription UTF8String];
+ achieved_descriptions.push_back(String::utf8(str != NULL ? str : ""));
+
+ maximum_points.push_back(description.maximumPoints);
+
+ hidden.push_back(description.hidden == YES);
+
+ replayable.push_back(description.replayable == YES);
+ }
+
+ ret["names"] = names;
+ ret["titles"] = titles;
+ ret["unachieved_descriptions"] = unachieved_descriptions;
+ ret["achieved_descriptions"] = achieved_descriptions;
+ ret["maximum_points"] = maximum_points;
+ ret["hidden"] = hidden;
+ ret["replayable"] = replayable;
+
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ };
+
+ pending_events.push_back(ret);
+ }];
+};
+
+void GameCenter::request_achievements() {
+ [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) {
+ Dictionary ret;
+ ret["type"] = "achievements";
+ if (error == nil) {
+ ret["result"] = "ok";
+ PackedStringArray names;
+ PackedFloat32Array percentages;
+
+ for (NSUInteger i = 0; i < [achievements count]; i++) {
+ GKAchievement *achievement = [achievements objectAtIndex:i];
+ const char *str = [achievement.identifier UTF8String];
+ names.push_back(String::utf8(str != NULL ? str : ""));
+
+ percentages.push_back(achievement.percentComplete);
+ }
+
+ ret["names"] = names;
+ ret["progress"] = percentages;
+
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ };
+
+ pending_events.push_back(ret);
+ }];
+};
+
+void GameCenter::reset_achievements() {
+ [GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error) {
+ Dictionary ret;
+ ret["type"] = "reset_achievements";
+ if (error == nil) {
+ ret["result"] = "ok";
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ };
+
+ pending_events.push_back(ret);
+ }];
+};
+
+Error GameCenter::show_game_center(Dictionary p_params) {
+ ERR_FAIL_COND_V(!NSProtocolFromString(@"GKGameCenterControllerDelegate"), FAILED);
+
+ GKGameCenterViewControllerState view_state = GKGameCenterViewControllerStateDefault;
+ if (p_params.has("view")) {
+ String view_name = p_params["view"];
+ if (view_name == "default") {
+ view_state = GKGameCenterViewControllerStateDefault;
+ } else if (view_name == "leaderboards") {
+ view_state = GKGameCenterViewControllerStateLeaderboards;
+ } else if (view_name == "achievements") {
+ view_state = GKGameCenterViewControllerStateAchievements;
+ } else if (view_name == "challenges") {
+ view_state = GKGameCenterViewControllerStateChallenges;
+ } else {
+ return ERR_INVALID_PARAMETER;
+ }
+ }
+
+ GKGameCenterViewController *controller = [[GKGameCenterViewController alloc] init];
+ ERR_FAIL_COND_V(!controller, FAILED);
+
+ UIViewController *root_controller = [[UIApplication sharedApplication] delegate].window.rootViewController;
+ ERR_FAIL_COND_V(!root_controller, FAILED);
+
+ controller.gameCenterDelegate = gameCenterDelegate;
+ controller.viewState = view_state;
+ if (view_state == GKGameCenterViewControllerStateLeaderboards) {
+ controller.leaderboardIdentifier = nil;
+ if (p_params.has("leaderboard_name")) {
+ String name = p_params["leaderboard_name"];
+ NSString *name_str = [[NSString alloc] initWithUTF8String:name.utf8().get_data()];
+ controller.leaderboardIdentifier = name_str;
+ }
+ }
+
+ [root_controller presentViewController:controller animated:YES completion:nil];
+
+ return OK;
+};
+
+Error GameCenter::request_identity_verification_signature() {
+ ERR_FAIL_COND_V(!is_authenticated(), ERR_UNAUTHORIZED);
+
+ GKLocalPlayer *player = [GKLocalPlayer localPlayer];
+ [player generateIdentityVerificationSignatureWithCompletionHandler:^(NSURL *publicKeyUrl, NSData *signature, NSData *salt, uint64_t timestamp, NSError *error) {
+ Dictionary ret;
+ ret["type"] = "identity_verification_signature";
+ if (error == nil) {
+ ret["result"] = "ok";
+ ret["public_key_url"] = [publicKeyUrl.absoluteString UTF8String];
+ ret["signature"] = [[signature base64EncodedStringWithOptions:0] UTF8String];
+ ret["salt"] = [[salt base64EncodedStringWithOptions:0] UTF8String];
+ ret["timestamp"] = timestamp;
+ if (@available(iOS 13, *)) {
+ ret["player_id"] = [player.teamPlayerID UTF8String];
+#if !defined(TARGET_OS_SIMULATOR) || !TARGET_OS_SIMULATOR
+ } else {
+ ret["player_id"] = [player.playerID UTF8String];
+#endif
+ }
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = (int64_t)error.code;
+ ret["error_description"] = [error.localizedDescription UTF8String];
+ };
+
+ pending_events.push_back(ret);
+ }];
+
+ return OK;
+};
+
+void GameCenter::game_center_closed() {
+ Dictionary ret;
+ ret["type"] = "show_game_center";
+ ret["result"] = "ok";
+ pending_events.push_back(ret);
+}
+
+int GameCenter::get_pending_event_count() {
+ return pending_events.size();
+};
+
+Variant GameCenter::pop_pending_event() {
+ Variant front = pending_events.front()->get();
+ pending_events.pop_front();
+
+ return front;
+};
+
+GameCenter *GameCenter::get_singleton() {
+ return instance;
+};
+
+GameCenter::GameCenter() {
+ ERR_FAIL_COND(instance != NULL);
+ instance = this;
+ authenticated = false;
+
+ gameCenterDelegate = [[GodotGameCenterDelegate alloc] init];
+};
+
+GameCenter::~GameCenter() {
+ if (gameCenterDelegate) {
+ gameCenterDelegate = nil;
+ }
+}
diff --git a/modules/gamecenter/game_center_delegate.h b/modules/gamecenter/game_center_delegate.h
new file mode 100644
index 0000000000..ef1d2ae93d
--- /dev/null
+++ b/modules/gamecenter/game_center_delegate.h
@@ -0,0 +1,35 @@
+/*************************************************************************/
+/* game_center_delegate.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#import <GameKit/GameKit.h>
+
+@interface GodotGameCenterDelegate : NSObject <GKGameCenterControllerDelegate>
+
+@end
diff --git a/modules/gamecenter/game_center_delegate.mm b/modules/gamecenter/game_center_delegate.mm
new file mode 100644
index 0000000000..6e20db572b
--- /dev/null
+++ b/modules/gamecenter/game_center_delegate.mm
@@ -0,0 +1,45 @@
+/*************************************************************************/
+/* game_center_delegate.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#import "game_center_delegate.h"
+
+#include "game_center.h"
+
+@implementation GodotGameCenterDelegate
+
+- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController {
+ //[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone
+ if (GameCenter::get_singleton()) {
+ GameCenter::get_singleton()->game_center_closed();
+ }
+ [gameCenterViewController dismissViewControllerAnimated:YES completion:nil];
+}
+
+@end
diff --git a/modules/gamecenter/game_center_module.cpp b/modules/gamecenter/game_center_module.cpp
new file mode 100644
index 0000000000..8f6ef291c0
--- /dev/null
+++ b/modules/gamecenter/game_center_module.cpp
@@ -0,0 +1,48 @@
+/*************************************************************************/
+/* game_center_module.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "game_center_module.h"
+
+#include "core/config/engine.h"
+
+#include "game_center.h"
+
+GameCenter *game_center;
+
+void register_gamecenter_types() {
+ game_center = memnew(GameCenter);
+ Engine::get_singleton()->add_singleton(Engine::Singleton("GameCenter", game_center));
+}
+
+void unregister_gamecenter_types() {
+ if (game_center) {
+ memdelete(game_center);
+ }
+}
diff --git a/modules/gamecenter/game_center_module.h b/modules/gamecenter/game_center_module.h
new file mode 100644
index 0000000000..5df3645b1c
--- /dev/null
+++ b/modules/gamecenter/game_center_module.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* game_center_module.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+void register_gamecenter_types();
+void unregister_gamecenter_types();
diff --git a/modules/gamecenter/gamecenter.gdip b/modules/gamecenter/gamecenter.gdip
new file mode 100644
index 0000000000..eb44effbdd
--- /dev/null
+++ b/modules/gamecenter/gamecenter.gdip
@@ -0,0 +1,17 @@
+[config]
+name="GameCenter"
+binary="gamecenter_lib.a"
+
+initialization="register_gamecenter_types"
+deinitialization="unregister_gamecenter_types"
+
+[dependencies]
+linked=[]
+embedded=[]
+system=["GameKit.framework"]
+
+capabilities=["gamekit"]
+
+files=[]
+
+[plist]
diff --git a/modules/gdnative/SCsub b/modules/gdnative/SCsub
index cab05549d2..45354ce692 100644
--- a/modules/gdnative/SCsub
+++ b/modules/gdnative/SCsub
@@ -20,16 +20,14 @@ SConscript("net/SCsub")
SConscript("xr/SCsub")
SConscript("pluginscript/SCsub")
SConscript("videodecoder/SCsub")
+SConscript("text/SCsub")
-from platform_methods import run_in_subprocess
import gdnative_builders
_, gensource = env_gdnative.CommandNoCache(
["include/gdnative_api_struct.gen.h", "gdnative_api_struct.gen.cpp"],
"gdnative_api.json",
- run_in_subprocess(gdnative_builders.build_gdnative_api_struct),
+ env.Run(gdnative_builders.build_gdnative_api_struct, "Generating GDNative API."),
)
env_gdnative.add_source_files(env.modules_sources, [gensource])
-
-env.use_ptrcall = True
diff --git a/modules/gdnative/android/android_gdn.cpp b/modules/gdnative/android/android_gdn.cpp
index bc39be1813..a48e51a390 100644
--- a/modules/gdnative/android/android_gdn.cpp
+++ b/modules/gdnative/android/android_gdn.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py
index 4b997e4bfe..fd860e9763 100644
--- a/modules/gdnative/config.py
+++ b/modules/gdnative/config.py
@@ -3,12 +3,11 @@ def can_build(env, platform):
def configure(env):
- env.use_ptrcall = True
+ pass
def get_doc_classes():
return [
- "@NativeScript",
"XRInterfaceGDNative",
"GDNative",
"GDNativeLibrary",
diff --git a/modules/gdnative/doc_classes/@NativeScript.xml b/modules/gdnative/doc_classes/@NativeScript.xml
deleted file mode 100644
index 809b225e21..0000000000
--- a/modules/gdnative/doc_classes/@NativeScript.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="@NativeScript" version="4.0">
- <brief_description>
- </brief_description>
- <description>
- </description>
- <tutorials>
- </tutorials>
- <methods>
- </methods>
- <constants>
- </constants>
-</class>
diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml
index 1aab864102..05cda05f9f 100644
--- a/modules/gdnative/doc_classes/GDNativeLibrary.xml
+++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml
@@ -7,8 +7,8 @@
A GDNative library can implement [NativeScript]s, global functions to call with the [GDNative] class, or low-level engine extensions through interfaces such as [XRInterfaceGDNative]. The library must be compiled for each platform and architecture that the project will run on.
</description>
<tutorials>
- <link>https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-c-example.html</link>
- <link>https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-cpp-example.html</link>
+ <link title="GDNative C example">https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-c-example.html</link>
+ <link title="GDNative C++ example">https://docs.godotengine.org/en/latest/tutorials/plugins/gdnative/gdnative-cpp-example.html</link>
</tutorials>
<methods>
<method name="get_current_dependencies" qualifiers="const">
diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp
index a131e3a78f..e3a359e09a 100644
--- a/modules/gdnative/gdnative.cpp
+++ b/modules/gdnative/gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,11 +30,11 @@
#include "gdnative.h"
-#include "core/global_constants.h"
+#include "core/config/project_settings.h"
+#include "core/core_constants.h"
#include "core/io/file_access_encrypted.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "scene/main/scene_tree.h"
@@ -63,7 +63,6 @@ GDNativeLibrary::~GDNativeLibrary() {
}
bool GDNativeLibrary::_set(const StringName &p_name, const Variant &p_property) {
-
String name = p_name;
if (name.begins_with("entry/")) {
@@ -115,8 +114,9 @@ void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
// set entries
List<String> entry_key_list;
- if (config_file->has_section("entry"))
+ if (config_file->has_section("entry")) {
config_file->get_section_keys("entry", &entry_key_list);
+ }
for (List<String>::Element *E = entry_key_list.front(); E; E = E->next()) {
String key = E->get();
@@ -132,8 +132,9 @@ void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
// set dependencies
List<String> dependency_key_list;
- if (config_file->has_section("dependencies"))
+ if (config_file->has_section("dependencies")) {
config_file->get_section_keys("dependencies", &dependency_key_list);
+ }
for (List<String>::Element *E = dependency_key_list.front(); E; E = E->next()) {
String key = E->get();
@@ -148,7 +149,6 @@ void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
}
void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) {
-
set_singleton(p_config_file->get_value("general", "singleton", default_singleton));
set_load_once(p_config_file->get_value("general", "load_once", default_load_once));
set_symbol_prefix(p_config_file->get_value("general", "symbol_prefix", default_symbol_prefix));
@@ -156,11 +156,11 @@ void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) {
String entry_lib_path;
{
-
List<String> entry_keys;
- if (p_config_file->has_section("entry"))
+ if (p_config_file->has_section("entry")) {
p_config_file->get_section_keys("entry", &entry_keys);
+ }
for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) {
String key = E->get();
@@ -188,11 +188,11 @@ void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) {
Vector<String> dependency_paths;
{
-
List<String> dependency_keys;
- if (p_config_file->has_section("dependencies"))
+ if (p_config_file->has_section("dependencies")) {
p_config_file->get_section_keys("dependencies", &dependency_keys);
+ }
for (List<String>::Element *E = dependency_keys.front(); E; E = E->next()) {
String key = E->get();
@@ -286,13 +286,31 @@ bool GDNative::initialize() {
}
String lib_path = library->get_current_library_path();
- if (lib_path.empty()) {
+ if (lib_path.is_empty()) {
ERR_PRINT("No library set for this platform");
return false;
}
#ifdef IPHONE_ENABLED
- // on iOS we use static linking
+ // On iOS we use static linking by default.
String path = "";
+
+ // On iOS dylibs is not allowed, but can be replaced with .framework or .xcframework.
+ // If they are used, we can run dlopen on them.
+ // They should be located under Frameworks directory, so we need to replace library path.
+ if (!lib_path.ends_with(".a")) {
+ path = ProjectSettings::get_singleton()->globalize_path(lib_path);
+
+ if (!FileAccess::exists(path)) {
+ String lib_name = lib_path.get_basename().get_file();
+ String framework_path_format = "Frameworks/$name.framework/$name";
+
+ Dictionary format_dict;
+ format_dict["name"] = lib_name;
+ String framework_path = framework_path_format.format(format_dict, "$_");
+
+ path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file(framework_path);
+ }
+ }
#elif defined(ANDROID_ENABLED)
// On Android dynamic libraries are located separately from resource assets,
// we should pass library name to dlopen(). The library name is flattened
@@ -383,7 +401,6 @@ bool GDNative::initialize() {
}
bool GDNative::terminate() {
-
if (!initialized) {
ERR_PRINT("No valid library handle, can't terminate GDNative object");
return false;
@@ -452,7 +469,6 @@ Vector<StringName> GDNativeCallRegistry::get_native_call_types() {
}
Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) {
-
Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type);
if (!E) {
ERR_PRINT((String("No handler for native call type \"" + p_native_call_type) + "\" found").utf8().get_data());
@@ -478,7 +494,6 @@ Variant GDNative::call_native(StringName p_native_call_type, StringName p_proced
}
Error GDNative::get_symbol(StringName p_procedure_name, void *&r_handle, bool p_optional) const {
-
if (!initialized) {
ERR_PRINT("No valid library handle, can't get symbol from GDNative object");
return ERR_CANT_OPEN;
@@ -520,13 +535,13 @@ bool GDNativeLibraryResourceLoader::handles_type(const String &p_type) const {
String GDNativeLibraryResourceLoader::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
- if (el == "gdnlib")
+ if (el == "gdnlib") {
return "GDNativeLibrary";
+ }
return "";
}
Error GDNativeLibraryResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
-
Ref<GDNativeLibrary> lib = p_resource;
if (lib.is_null()) {
diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h
index 6d26c2141d..765087d176 100644
--- a/modules/gdnative/gdnative.h
+++ b/modules/gdnative/gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,10 +31,10 @@
#ifndef GDNATIVE_H
#define GDNATIVE_H
+#include "core/io/resource.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/os/thread_safe.h"
-#include "core/resource.h"
#include "gdnative/gdnative.h"
#include "gdnative_api_struct.gen.h"
diff --git a/modules/gdnative/gdnative/aabb.cpp b/modules/gdnative/gdnative/aabb.cpp
index 246e5d4e8d..41b5029ef4 100644
--- a/modules/gdnative/gdnative/aabb.cpp
+++ b/modules/gdnative/gdnative/aabb.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,14 @@
#include "gdnative/aabb.h"
#include "core/math/aabb.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_aabb) == sizeof(AABB), "AABB size mismatch");
+
void GDAPI godot_aabb_new(godot_aabb *r_dest, const godot_vector3 *p_pos, const godot_vector3 *p_size) {
const Vector3 *pos = (const Vector3 *)p_pos;
const Vector3 *size = (const Vector3 *)p_size;
@@ -79,6 +81,13 @@ godot_string GDAPI godot_aabb_as_string(const godot_aabb *p_self) {
return ret;
}
+godot_aabb GDAPI godot_aabb_abs(const godot_aabb *p_self) {
+ godot_aabb dest;
+ const AABB *self = (const AABB *)p_self;
+ *((AABB *)&dest) = self->abs();
+ return dest;
+}
+
godot_real GDAPI godot_aabb_get_area(const godot_aabb *p_self) {
const AABB *self = (const AABB *)p_self;
return self->get_area();
diff --git a/modules/gdnative/gdnative/array.cpp b/modules/gdnative/gdnative/array.cpp
index 0c764ab8fd..7099b9d459 100644
--- a/modules/gdnative/gdnative/array.cpp
+++ b/modules/gdnative/gdnative/array.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,17 +30,19 @@
#include "gdnative/array.h"
-#include "core/array.h"
#include "core/os/memory.h"
+#include "core/variant/array.h"
-#include "core/color.h"
+#include "core/math/color.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_array) == sizeof(Array), "Array size mismatch");
+
void GDAPI godot_array_new(godot_array *r_dest) {
Array *dest = (Array *)r_dest;
memnew_placement(dest, Array);
@@ -88,6 +90,18 @@ void GDAPI godot_array_new_packed_vector2_array(godot_array *r_dest, const godot
}
}
+void GDAPI godot_array_new_packed_vector2i_array(godot_array *r_dest, const godot_packed_vector2i_array *p_pv2a) {
+ Array *dest = (Array *)r_dest;
+ Vector<Vector2i> *pca = (Vector<Vector2i> *)p_pv2a;
+ memnew_placement(dest, Array);
+ dest->resize(pca->size());
+
+ for (int i = 0; i < dest->size(); i++) {
+ Variant v = pca->operator[](i);
+ dest->operator[](i) = v;
+ }
+}
+
void GDAPI godot_array_new_packed_string_array(godot_array *r_dest, const godot_packed_string_array *p_psa) {
Array *dest = (Array *)r_dest;
Vector<String> *pca = (Vector<String> *)p_psa;
@@ -100,9 +114,33 @@ void GDAPI godot_array_new_packed_string_array(godot_array *r_dest, const godot_
}
}
-void GDAPI godot_array_new_packed_real_array(godot_array *r_dest, const godot_packed_real_array *p_pra) {
+void GDAPI godot_array_new_packed_float32_array(godot_array *r_dest, const godot_packed_float32_array *p_pra) {
+ Array *dest = (Array *)r_dest;
+ Vector<float> *pca = (Vector<float> *)p_pra;
+ memnew_placement(dest, Array);
+ dest->resize(pca->size());
+
+ for (int i = 0; i < dest->size(); i++) {
+ Variant v = pca->operator[](i);
+ dest->operator[](i) = v;
+ }
+}
+
+void GDAPI godot_array_new_packed_float64_array(godot_array *r_dest, const godot_packed_float64_array *p_pra) {
+ Array *dest = (Array *)r_dest;
+ Vector<double> *pca = (Vector<double> *)p_pra;
+ memnew_placement(dest, Array);
+ dest->resize(pca->size());
+
+ for (int i = 0; i < dest->size(); i++) {
+ Variant v = pca->operator[](i);
+ dest->operator[](i) = v;
+ }
+}
+
+void GDAPI godot_array_new_packed_int32_array(godot_array *r_dest, const godot_packed_int32_array *p_pia) {
Array *dest = (Array *)r_dest;
- Vector<godot_real> *pca = (Vector<godot_real> *)p_pra;
+ Vector<int32_t> *pca = (Vector<int32_t> *)p_pia;
memnew_placement(dest, Array);
dest->resize(pca->size());
@@ -112,9 +150,9 @@ void GDAPI godot_array_new_packed_real_array(godot_array *r_dest, const godot_pa
}
}
-void GDAPI godot_array_new_packed_int_array(godot_array *r_dest, const godot_packed_int_array *p_pia) {
+void GDAPI godot_array_new_packed_int64_array(godot_array *r_dest, const godot_packed_int64_array *p_pia) {
Array *dest = (Array *)r_dest;
- Vector<godot_int> *pca = (Vector<godot_int> *)p_pia;
+ Vector<int64_t> *pca = (Vector<int64_t> *)p_pia;
memnew_placement(dest, Array);
dest->resize(pca->size());
@@ -177,9 +215,9 @@ godot_int GDAPI godot_array_count(const godot_array *p_self, const godot_variant
return self->count(*val);
}
-godot_bool GDAPI godot_array_empty(const godot_array *p_self) {
+godot_bool GDAPI godot_array_is_empty(const godot_array *p_self) {
const Array *self = (const Array *)p_self;
- return self->empty();
+ return self->is_empty();
}
void GDAPI godot_array_erase(godot_array *p_self, const godot_variant *p_value) {
diff --git a/modules/gdnative/gdnative/basis.cpp b/modules/gdnative/gdnative/basis.cpp
index 4f489287b9..bfcd9bbf2c 100644
--- a/modules/gdnative/gdnative/basis.cpp
+++ b/modules/gdnative/gdnative/basis.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,14 @@
#include "gdnative/basis.h"
#include "core/math/basis.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_basis) == sizeof(Basis), "Basis size mismatch");
+
void GDAPI godot_basis_new_with_rows(godot_basis *r_dest, const godot_vector3 *p_x_axis, const godot_vector3 *p_y_axis, const godot_vector3 *p_z_axis) {
const Vector3 *x_axis = (const Vector3 *)p_x_axis;
const Vector3 *y_axis = (const Vector3 *)p_y_axis;
diff --git a/modules/gdnative/gdnative/callable.cpp b/modules/gdnative/gdnative/callable.cpp
new file mode 100644
index 0000000000..d4730a14b3
--- /dev/null
+++ b/modules/gdnative/gdnative/callable.cpp
@@ -0,0 +1,252 @@
+/*************************************************************************/
+/* callable.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdnative/callable.h"
+
+#include "core/io/resource.h"
+#include "core/variant/callable.h"
+#include "core/variant/variant.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+static_assert(sizeof(godot_callable) == sizeof(Callable), "Callable size mismatch");
+static_assert(sizeof(godot_signal) == sizeof(Signal), "Signal size mismatch");
+
+// Callable
+
+void GDAPI godot_callable_new_with_object(godot_callable *r_dest, const godot_object *p_object, const godot_string_name *p_method) {
+ Callable *dest = (Callable *)r_dest;
+ const Object *object = (const Object *)p_object;
+ const StringName *method = (const StringName *)p_method;
+ memnew_placement(dest, Callable(object, *method));
+}
+
+void GDAPI godot_callable_new_with_object_id(godot_callable *r_dest, uint64_t p_objectid, const godot_string_name *p_method) {
+ Callable *dest = (Callable *)r_dest;
+ const StringName *method = (const StringName *)p_method;
+ memnew_placement(dest, Callable(ObjectID(p_objectid), *method));
+}
+
+void GDAPI godot_callable_new_copy(godot_callable *r_dest, const godot_callable *p_src) {
+ Callable *dest = (Callable *)r_dest;
+ const Callable *src = (const Callable *)p_src;
+ memnew_placement(dest, Callable(*src));
+}
+
+void GDAPI godot_callable_destroy(godot_callable *p_self) {
+ Callable *self = (Callable *)p_self;
+ self->~Callable();
+}
+
+godot_int GDAPI godot_callable_call(const godot_callable *p_self, const godot_variant **p_arguments, godot_int p_argcount, godot_variant *r_return_value) {
+ const Callable *self = (const Callable *)p_self;
+ const Variant **arguments = (const Variant **)p_arguments;
+ Variant *return_value = (Variant *)r_return_value;
+ Variant ret;
+ Callable::CallError err;
+ self->call(arguments, p_argcount, ret, err);
+ if (return_value)
+ (*return_value) = ret;
+ return (godot_int)err.error;
+}
+
+void GDAPI godot_callable_call_deferred(const godot_callable *p_self, const godot_variant **p_arguments, godot_int p_argcount) {
+ const Callable *self = (const Callable *)p_self;
+ const Variant **arguments = (const Variant **)p_arguments;
+ self->call_deferred(arguments, p_argcount);
+}
+
+godot_bool GDAPI godot_callable_is_null(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return self->is_null();
+}
+
+godot_bool GDAPI godot_callable_is_custom(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return self->is_custom();
+}
+
+godot_bool GDAPI godot_callable_is_standard(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return self->is_standard();
+}
+
+godot_object GDAPI *godot_callable_get_object(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return (godot_object *)self->get_object();
+}
+
+uint64_t GDAPI godot_callable_get_object_id(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return (uint64_t)self->get_object_id();
+}
+
+godot_string_name GDAPI godot_callable_get_method(const godot_callable *p_self) {
+ godot_string_name raw_dest;
+ const Callable *self = (const Callable *)p_self;
+ StringName *dest = (StringName *)&raw_dest;
+ memnew_placement(dest, StringName(self->get_method()));
+ return raw_dest;
+}
+
+uint32_t GDAPI godot_callable_hash(const godot_callable *p_self) {
+ const Callable *self = (const Callable *)p_self;
+ return self->hash();
+}
+
+godot_string GDAPI godot_callable_as_string(const godot_callable *p_self) {
+ godot_string ret;
+ const Callable *self = (const Callable *)p_self;
+ memnew_placement(&ret, String(*self));
+ return ret;
+}
+
+godot_bool GDAPI godot_callable_operator_equal(const godot_callable *p_self, const godot_callable *p_other) {
+ const Callable *self = (const Callable *)p_self;
+ const Callable *other = (const Callable *)p_other;
+ return *self == *other;
+}
+
+godot_bool GDAPI godot_callable_operator_less(const godot_callable *p_self, const godot_callable *p_other) {
+ const Callable *self = (const Callable *)p_self;
+ const Callable *other = (const Callable *)p_other;
+ return *self < *other;
+}
+
+// Signal
+
+void GDAPI godot_signal_new_with_object(godot_signal *r_dest, const godot_object *p_object, const godot_string_name *p_name) {
+ Signal *dest = (Signal *)r_dest;
+ const Object *object = (const Object *)p_object;
+ const StringName *name = (const StringName *)p_name;
+ memnew_placement(dest, Signal(object, *name));
+}
+
+void GDAPI godot_signal_new_with_object_id(godot_signal *r_dest, uint64_t p_objectid, const godot_string_name *p_name) {
+ Signal *dest = (Signal *)r_dest;
+ const StringName *name = (const StringName *)p_name;
+ memnew_placement(dest, Signal(ObjectID(p_objectid), *name));
+}
+
+void GDAPI godot_signal_new_copy(godot_signal *r_dest, const godot_signal *p_src) {
+ Signal *dest = (Signal *)r_dest;
+ const Signal *src = (const Signal *)p_src;
+ memnew_placement(dest, Signal(*src));
+}
+
+void GDAPI godot_signal_destroy(godot_signal *p_self) {
+ Signal *self = (Signal *)p_self;
+ self->~Signal();
+}
+
+godot_int GDAPI godot_signal_emit(const godot_signal *p_self, const godot_variant **p_arguments, godot_int p_argcount) {
+ const Signal *self = (const Signal *)p_self;
+ const Variant **arguments = (const Variant **)p_arguments;
+ return (godot_int)self->emit(arguments, p_argcount);
+}
+
+godot_int GDAPI godot_signal_connect(godot_signal *p_self, const godot_callable *p_callable, const godot_array *p_binds, uint32_t p_flags) {
+ Signal *self = (Signal *)p_self;
+ const Callable *callable = (const Callable *)p_callable;
+ const Array *binds_ar = (const Array *)p_binds;
+ Vector<Variant> binds;
+ for (int i = 0; i < binds_ar->size(); i++) {
+ binds.push_back(binds_ar->get(i));
+ }
+ return (godot_int)self->connect(*callable, binds, p_flags);
+}
+
+void GDAPI godot_signal_disconnect(godot_signal *p_self, const godot_callable *p_callable) {
+ Signal *self = (Signal *)p_self;
+ const Callable *callable = (const Callable *)p_callable;
+ self->disconnect(*callable);
+}
+
+godot_bool GDAPI godot_signal_is_null(const godot_signal *p_self) {
+ const Signal *self = (const Signal *)p_self;
+ return self->is_null();
+}
+
+godot_bool GDAPI godot_signal_is_connected(const godot_signal *p_self, const godot_callable *p_callable) {
+ const Signal *self = (const Signal *)p_self;
+ const Callable *callable = (const Callable *)p_callable;
+ return self->is_connected(*callable);
+}
+
+godot_array GDAPI godot_signal_get_connections(const godot_signal *p_self) {
+ godot_array raw_dest;
+ const Signal *self = (const Signal *)p_self;
+ Array *dest = (Array *)&raw_dest;
+ memnew_placement(dest, Array(self->get_connections()));
+ return raw_dest;
+}
+
+godot_object GDAPI *godot_signal_get_object(const godot_signal *p_self) {
+ const Signal *self = (const Signal *)p_self;
+ return (godot_object *)self->get_object();
+}
+
+uint64_t GDAPI godot_signal_get_object_id(const godot_signal *p_self) {
+ const Signal *self = (const Signal *)p_self;
+ return (uint64_t)self->get_object_id();
+}
+
+godot_string_name GDAPI godot_signal_get_name(const godot_signal *p_self) {
+ godot_string_name raw_dest;
+ const Signal *self = (const Signal *)p_self;
+ StringName *dest = (StringName *)&raw_dest;
+ memnew_placement(dest, StringName(self->get_name()));
+ return raw_dest;
+}
+
+godot_string GDAPI godot_signal_as_string(const godot_signal *p_self) {
+ godot_string ret;
+ const Signal *self = (const Signal *)p_self;
+ memnew_placement(&ret, String(*self));
+ return ret;
+}
+
+godot_bool GDAPI godot_signal_operator_equal(const godot_signal *p_self, const godot_signal *p_other) {
+ const Signal *self = (const Signal *)p_self;
+ const Signal *other = (const Signal *)p_other;
+ return *self == *other;
+}
+
+godot_bool GDAPI godot_signal_operator_less(const godot_signal *p_self, const godot_signal *p_other) {
+ const Signal *self = (const Signal *)p_self;
+ const Signal *other = (const Signal *)p_other;
+ return *self < *other;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/modules/gdnative/gdnative/color.cpp b/modules/gdnative/gdnative/color.cpp
index 68c83e05a6..939dec3a47 100644
--- a/modules/gdnative/gdnative/color.cpp
+++ b/modules/gdnative/gdnative/color.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,21 +30,21 @@
#include "gdnative/color.h"
-#include "core/color.h"
-#include "core/variant.h"
+#include "core/math/color.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
-void GDAPI godot_color_new_rgba(godot_color *r_dest, const godot_real p_r, const godot_real p_g, const godot_real p_b, const godot_real p_a) {
+static_assert(sizeof(godot_color) == sizeof(Color), "Color size mismatch");
+void GDAPI godot_color_new_rgba(godot_color *r_dest, const godot_real p_r, const godot_real p_g, const godot_real p_b, const godot_real p_a) {
Color *dest = (Color *)r_dest;
*dest = Color(p_r, p_g, p_b, p_a);
}
void GDAPI godot_color_new_rgb(godot_color *r_dest, const godot_real p_r, const godot_real p_g, const godot_real p_b) {
-
Color *dest = (Color *)r_dest;
*dest = Color(p_r, p_g, p_b);
}
@@ -148,13 +148,6 @@ godot_color GDAPI godot_color_inverted(const godot_color *p_self) {
return dest;
}
-godot_color GDAPI godot_color_contrasted(const godot_color *p_self) {
- godot_color dest;
- const Color *self = (const Color *)p_self;
- *((Color *)&dest) = self->contrasted();
- return dest;
-}
-
godot_color GDAPI godot_color_lerp(const godot_color *p_self, const godot_color *p_b, const godot_real p_t) {
godot_color dest;
const Color *self = (const Color *)p_self;
diff --git a/modules/gdnative/gdnative/dictionary.cpp b/modules/gdnative/gdnative/dictionary.cpp
index b145b88934..f3c040428a 100644
--- a/modules/gdnative/gdnative/dictionary.cpp
+++ b/modules/gdnative/gdnative/dictionary.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,15 +30,17 @@
#include "gdnative/dictionary.h"
-#include "core/variant.h"
-// core/variant.h before to avoid compile errors with MSVC
-#include "core/dictionary.h"
+#include "core/variant/variant.h"
+// core/variant/variant.h before to avoid compile errors with MSVC
#include "core/io/json.h"
+#include "core/variant/dictionary.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_dictionary) == sizeof(Dictionary), "Dictionary size mismatch");
+
void GDAPI godot_dictionary_new(godot_dictionary *r_dest) {
Dictionary *dest = (Dictionary *)r_dest;
memnew_placement(dest, Dictionary);
@@ -69,9 +71,9 @@ godot_int GDAPI godot_dictionary_size(const godot_dictionary *p_self) {
return self->size();
}
-godot_bool GDAPI godot_dictionary_empty(const godot_dictionary *p_self) {
+godot_bool GDAPI godot_dictionary_is_empty(const godot_dictionary *p_self) {
const Dictionary *self = (const Dictionary *)p_self;
- return self->empty();
+ return self->is_empty();
}
void GDAPI godot_dictionary_clear(godot_dictionary *p_self) {
diff --git a/modules/gdnative/gdnative/gdnative.cpp b/modules/gdnative/gdnative/gdnative.cpp
index 3175340448..1c11130d89 100644
--- a/modules/gdnative/gdnative/gdnative.cpp
+++ b/modules/gdnative/gdnative/gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,12 +30,12 @@
#include "gdnative/gdnative.h"
-#include "core/class_db.h"
-#include "core/engine.h"
-#include "core/error_macros.h"
-#include "core/global_constants.h"
+#include "core/config/engine.h"
+#include "core/core_constants.h"
+#include "core/error/error_macros.h"
+#include "core/object/class_db.h"
#include "core/os/os.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#include "modules/gdnative/gdnative.h"
@@ -56,14 +56,12 @@ godot_object GDAPI *godot_global_get_singleton(char *p_name) {
// MethodBind API
godot_method_bind GDAPI *godot_method_bind_get_method(const char *p_classname, const char *p_methodname) {
-
MethodBind *mb = ClassDB::get_method(StringName(p_classname), StringName(p_methodname));
// MethodBind *mb = ClassDB::get_method("Node", "get_name");
return (godot_method_bind *)mb;
}
void GDAPI godot_method_bind_ptrcall(godot_method_bind *p_method_bind, godot_object *p_instance, const void **p_args, void *p_ret) {
-
MethodBind *mb = (MethodBind *)p_method_bind;
Object *o = (Object *)p_instance;
mb->ptrcall(o, p_args, p_ret);
@@ -93,8 +91,9 @@ godot_variant GDAPI godot_method_bind_call(godot_method_bind *p_method_bind, god
godot_class_constructor GDAPI godot_get_class_constructor(const char *p_classname) {
ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(StringName(p_classname));
- if (class_info)
+ if (class_info) {
return (godot_class_constructor)class_info->creation_func;
+ }
return nullptr;
}
@@ -102,10 +101,10 @@ godot_dictionary GDAPI godot_get_global_constants() {
godot_dictionary constants;
godot_dictionary_new(&constants);
Dictionary *p_constants = (Dictionary *)&constants;
- const int constants_count = GlobalConstants::get_global_constant_count();
+ const int constants_count = CoreConstants::get_global_constant_count();
for (int i = 0; i < constants_count; ++i) {
- const char *name = GlobalConstants::get_global_constant_name(i);
- int value = GlobalConstants::get_global_constant_value(i);
+ const char *name = CoreConstants::get_global_constant_name(i);
+ int value = CoreConstants::get_global_constant_value(i);
(*p_constants)[name] = value;
}
return constants;
@@ -166,7 +165,7 @@ void _gdnative_report_loading_error(const godot_object *p_library, const char *p
_err_print_error("gdnative_init", library->get_current_library_path().utf8().ptr(), 0, message.utf8().ptr());
}
-godot_object GDAPI *godot_instance_from_id(godot_int p_instance_id) {
+godot_object GDAPI *godot_instance_from_id(uint64_t p_instance_id) {
return (godot_object *)ObjectDB::get_instance(ObjectID(p_instance_id));
}
@@ -177,12 +176,19 @@ void *godot_get_class_tag(const godot_string_name *p_class) {
}
godot_object *godot_object_cast_to(const godot_object *p_object, void *p_class_tag) {
- if (!p_object) return nullptr;
+ if (!p_object) {
+ return nullptr;
+ }
Object *o = (Object *)p_object;
return o->is_class_ptr(p_class_tag) ? (godot_object *)o : nullptr;
}
+uint64_t GDAPI godot_object_get_instance_id(const godot_object *p_object) {
+ const Object *o = (const Object *)p_object;
+ return (uint64_t)o->get_instance_id();
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/gdnative/node_path.cpp b/modules/gdnative/gdnative/node_path.cpp
index 93f43835c8..7b215c0d0b 100644
--- a/modules/gdnative/gdnative/node_path.cpp
+++ b/modules/gdnative/gdnative/node_path.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,15 @@
#include "gdnative/node_path.h"
-#include "core/node_path.h"
-#include "core/variant.h"
+#include "core/string/node_path.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_node_path) == sizeof(NodePath), "NodePath size mismatch");
+
void GDAPI godot_node_path_new(godot_node_path *r_dest, const godot_string *p_from) {
NodePath *dest = (NodePath *)r_dest;
const String *from = (const String *)p_from;
diff --git a/modules/gdnative/gdnative/packed_arrays.cpp b/modules/gdnative/gdnative/packed_arrays.cpp
new file mode 100644
index 0000000000..e714999234
--- /dev/null
+++ b/modules/gdnative/gdnative/packed_arrays.cpp
@@ -0,0 +1,1141 @@
+/*************************************************************************/
+/* packed_arrays.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdnative/packed_arrays.h"
+
+#include "core/variant/array.h"
+
+#include "core/variant/variant.h"
+
+#include "core/math/color.h"
+#include "core/math/vector2.h"
+#include "core/math/vector3.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+static_assert(sizeof(godot_packed_byte_array) == sizeof(Vector<uint8_t>), "Vector<uint8_t> size mismatch");
+static_assert(sizeof(godot_packed_int32_array) == sizeof(Vector<int32_t>), "Vector<int32_t> size mismatch");
+static_assert(sizeof(godot_packed_int64_array) == sizeof(Vector<int64_t>), "Vector<int64_t> size mismatch");
+static_assert(sizeof(godot_packed_float32_array) == sizeof(Vector<float>), "Vector<float> size mismatch");
+static_assert(sizeof(godot_packed_float64_array) == sizeof(Vector<double>), "Vector<double> size mismatch");
+static_assert(sizeof(godot_packed_string_array) == sizeof(Vector<String>), "Vector<String> size mismatch");
+static_assert(sizeof(godot_packed_vector2_array) == sizeof(Vector<Vector2>), "Vector<Vector2> size mismatch");
+static_assert(sizeof(godot_packed_vector2i_array) == sizeof(Vector<Vector2i>), "Vector<Vector2i> size mismatch");
+static_assert(sizeof(godot_packed_vector3_array) == sizeof(Vector<Vector3>), "Vector<Vector3> size mismatch");
+static_assert(sizeof(godot_packed_color_array) == sizeof(Vector<Color>), "Vector<Color> size mismatch");
+
+#define memnew_placement_custom(m_placement, m_class, m_constr) _post_initialize(new (m_placement, sizeof(m_class), "") m_constr)
+
+// byte
+
+void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *r_dest) {
+ Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
+ memnew_placement(dest, Vector<uint8_t>);
+}
+
+void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src) {
+ Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
+ const Vector<uint8_t> *src = (const Vector<uint8_t> *)p_src;
+ memnew_placement(dest, Vector<uint8_t>(*src));
+}
+
+void GDAPI godot_packed_byte_array_new_with_array(godot_packed_byte_array *r_dest, const godot_array *p_a) {
+ Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<uint8_t>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const uint8_t GDAPI *godot_packed_byte_array_ptr(const godot_packed_byte_array *p_self) {
+ const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
+ return self->ptr();
+}
+
+uint8_t GDAPI *godot_packed_byte_array_ptrw(godot_packed_byte_array *p_self) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ return self->ptrw();
+}
+
+void GDAPI godot_packed_byte_array_append(godot_packed_byte_array *p_self, const uint8_t p_data) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_byte_array_append_array(godot_packed_byte_array *p_self, const godot_packed_byte_array *p_array) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ Vector<uint8_t> *array = (Vector<uint8_t> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_byte_array_insert(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ return (godot_error)self->insert(p_idx, p_data);
+}
+
+godot_bool GDAPI godot_packed_byte_array_has(godot_packed_byte_array *p_self, const uint8_t p_value) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ return (godot_bool)self->has(p_value);
+}
+
+void GDAPI godot_packed_byte_array_sort(godot_packed_byte_array *p_self) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_byte_array_invert(godot_packed_byte_array *p_self) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_byte_array_push_back(godot_packed_byte_array *p_self, const uint8_t p_data) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_byte_array_remove(godot_packed_byte_array *p_self, const godot_int p_idx) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_byte_array_resize(godot_packed_byte_array *p_self, const godot_int p_size) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_byte_array_set(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data) {
+ Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
+ self->set(p_idx, p_data);
+}
+
+uint8_t GDAPI godot_packed_byte_array_get(const godot_packed_byte_array *p_self, const godot_int p_idx) {
+ const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
+ return self->get(p_idx);
+}
+
+godot_int GDAPI godot_packed_byte_array_size(const godot_packed_byte_array *p_self) {
+ const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_byte_array_is_empty(const godot_packed_byte_array *p_self) {
+ const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self) {
+ ((Vector<uint8_t> *)p_self)->~Vector();
+}
+
+// int32
+
+void GDAPI godot_packed_int32_array_new(godot_packed_int32_array *r_dest) {
+ Vector<int32_t> *dest = (Vector<int32_t> *)r_dest;
+ memnew_placement(dest, Vector<int32_t>);
+}
+
+void GDAPI godot_packed_int32_array_new_copy(godot_packed_int32_array *r_dest, const godot_packed_int32_array *p_src) {
+ Vector<int32_t> *dest = (Vector<int32_t> *)r_dest;
+ const Vector<int32_t> *src = (const Vector<int32_t> *)p_src;
+ memnew_placement(dest, Vector<int32_t>(*src));
+}
+
+void GDAPI godot_packed_int32_array_new_with_array(godot_packed_int32_array *r_dest, const godot_array *p_a) {
+ Vector<int32_t> *dest = (Vector<int32_t> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<int32_t>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const int32_t GDAPI *godot_packed_int32_array_ptr(const godot_packed_int32_array *p_self) {
+ const Vector<int32_t> *self = (const Vector<int32_t> *)p_self;
+ return self->ptr();
+}
+
+int32_t GDAPI *godot_packed_int32_array_ptrw(godot_packed_int32_array *p_self) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ return self->ptrw();
+}
+
+void GDAPI godot_packed_int32_array_append(godot_packed_int32_array *p_self, const int32_t p_data) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_int32_array_append_array(godot_packed_int32_array *p_self, const godot_packed_int32_array *p_array) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ Vector<int32_t> *array = (Vector<int32_t> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_int32_array_insert(godot_packed_int32_array *p_self, const godot_int p_idx, const int32_t p_data) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ return (godot_error)self->insert(p_idx, p_data);
+}
+
+godot_bool GDAPI godot_packed_int32_array_has(godot_packed_int32_array *p_self, const int32_t p_value) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ return (godot_bool)self->has(p_value);
+}
+
+void GDAPI godot_packed_int32_array_sort(godot_packed_int32_array *p_self) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_int32_array_invert(godot_packed_int32_array *p_self) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_int32_array_push_back(godot_packed_int32_array *p_self, const int32_t p_data) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_int32_array_remove(godot_packed_int32_array *p_self, const godot_int p_idx) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_int32_array_resize(godot_packed_int32_array *p_self, const godot_int p_size) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_int32_array_set(godot_packed_int32_array *p_self, const godot_int p_idx, const int32_t p_data) {
+ Vector<int32_t> *self = (Vector<int32_t> *)p_self;
+ self->set(p_idx, p_data);
+}
+
+int32_t GDAPI godot_packed_int32_array_get(const godot_packed_int32_array *p_self, const godot_int p_idx) {
+ const Vector<int32_t> *self = (const Vector<int32_t> *)p_self;
+ return self->get(p_idx);
+}
+
+godot_int GDAPI godot_packed_int32_array_size(const godot_packed_int32_array *p_self) {
+ const Vector<int32_t> *self = (const Vector<int32_t> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_int32_array_is_empty(const godot_packed_int32_array *p_self) {
+ const Vector<int32_t> *self = (const Vector<int32_t> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_int32_array_destroy(godot_packed_int32_array *p_self) {
+ ((Vector<int32_t> *)p_self)->~Vector();
+}
+
+// int64
+
+void GDAPI godot_packed_int64_array_new(godot_packed_int64_array *r_dest) {
+ Vector<int64_t> *dest = (Vector<int64_t> *)r_dest;
+ memnew_placement(dest, Vector<int64_t>);
+}
+
+void GDAPI godot_packed_int64_array_new_copy(godot_packed_int64_array *r_dest, const godot_packed_int64_array *p_src) {
+ Vector<int64_t> *dest = (Vector<int64_t> *)r_dest;
+ const Vector<int64_t> *src = (const Vector<int64_t> *)p_src;
+ memnew_placement(dest, Vector<int64_t>(*src));
+}
+
+void GDAPI godot_packed_int64_array_new_with_array(godot_packed_int64_array *r_dest, const godot_array *p_a) {
+ Vector<int64_t> *dest = (Vector<int64_t> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<int64_t>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const int64_t GDAPI *godot_packed_int64_array_ptr(const godot_packed_int64_array *p_self) {
+ const Vector<int64_t> *self = (const Vector<int64_t> *)p_self;
+ return self->ptr();
+}
+
+int64_t GDAPI *godot_packed_int64_array_ptrw(godot_packed_int64_array *p_self) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ return self->ptrw();
+}
+
+void GDAPI godot_packed_int64_array_append(godot_packed_int64_array *p_self, const int64_t p_data) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_int64_array_append_array(godot_packed_int64_array *p_self, const godot_packed_int64_array *p_array) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ Vector<int64_t> *array = (Vector<int64_t> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_int64_array_insert(godot_packed_int64_array *p_self, const godot_int p_idx, const int64_t p_data) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ return (godot_error)self->insert(p_idx, p_data);
+}
+
+godot_bool GDAPI godot_packed_int64_array_has(godot_packed_int64_array *p_self, const int64_t p_value) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ return (godot_bool)self->has(p_value);
+}
+
+void GDAPI godot_packed_int64_array_sort(godot_packed_int64_array *p_self) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_int64_array_invert(godot_packed_int64_array *p_self) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_int64_array_push_back(godot_packed_int64_array *p_self, const int64_t p_data) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_int64_array_remove(godot_packed_int64_array *p_self, const godot_int p_idx) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_int64_array_resize(godot_packed_int64_array *p_self, const godot_int p_size) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_int64_array_set(godot_packed_int64_array *p_self, const godot_int p_idx, const int64_t p_data) {
+ Vector<int64_t> *self = (Vector<int64_t> *)p_self;
+ self->set(p_idx, p_data);
+}
+
+int64_t GDAPI godot_packed_int64_array_get(const godot_packed_int64_array *p_self, const godot_int p_idx) {
+ const Vector<int64_t> *self = (const Vector<int64_t> *)p_self;
+ return self->get(p_idx);
+}
+
+godot_int GDAPI godot_packed_int64_array_size(const godot_packed_int64_array *p_self) {
+ const Vector<int64_t> *self = (const Vector<int64_t> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_int64_array_is_empty(const godot_packed_int64_array *p_self) {
+ const Vector<int64_t> *self = (const Vector<int64_t> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_int64_array_destroy(godot_packed_int64_array *p_self) {
+ ((Vector<int64_t> *)p_self)->~Vector();
+}
+
+// float32
+
+void GDAPI godot_packed_float32_array_new(godot_packed_float32_array *r_dest) {
+ Vector<float> *dest = (Vector<float> *)r_dest;
+ memnew_placement(dest, Vector<float>);
+}
+
+void GDAPI godot_packed_float32_array_new_copy(godot_packed_float32_array *r_dest, const godot_packed_float32_array *p_src) {
+ Vector<float> *dest = (Vector<float> *)r_dest;
+ const Vector<float> *src = (const Vector<float> *)p_src;
+ memnew_placement(dest, Vector<float>(*src));
+}
+
+void GDAPI godot_packed_float32_array_new_with_array(godot_packed_float32_array *r_dest, const godot_array *p_a) {
+ Vector<float> *dest = (Vector<float> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<float>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const float GDAPI *godot_packed_float32_array_ptr(const godot_packed_float32_array *p_self) {
+ const Vector<float> *self = (const Vector<float> *)p_self;
+ return self->ptr();
+}
+
+float GDAPI *godot_packed_float32_array_ptrw(godot_packed_float32_array *p_self) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ return self->ptrw();
+}
+
+void GDAPI godot_packed_float32_array_append(godot_packed_float32_array *p_self, const float p_data) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_float32_array_append_array(godot_packed_float32_array *p_self, const godot_packed_float32_array *p_array) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ Vector<float> *array = (Vector<float> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_float32_array_insert(godot_packed_float32_array *p_self, const godot_int p_idx, const float p_data) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ return (godot_error)self->insert(p_idx, p_data);
+}
+
+godot_bool GDAPI godot_packed_float32_array_has(godot_packed_float32_array *p_self, const float p_value) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ return (godot_bool)self->has(p_value);
+}
+
+void GDAPI godot_packed_float32_array_sort(godot_packed_float32_array *p_self) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_float32_array_invert(godot_packed_float32_array *p_self) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_float32_array_push_back(godot_packed_float32_array *p_self, const float p_data) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_float32_array_remove(godot_packed_float32_array *p_self, const godot_int p_idx) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_float32_array_resize(godot_packed_float32_array *p_self, const godot_int p_size) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_float32_array_set(godot_packed_float32_array *p_self, const godot_int p_idx, const float p_data) {
+ Vector<float> *self = (Vector<float> *)p_self;
+ self->set(p_idx, p_data);
+}
+
+float GDAPI godot_packed_float32_array_get(const godot_packed_float32_array *p_self, const godot_int p_idx) {
+ const Vector<float> *self = (const Vector<float> *)p_self;
+ return self->get(p_idx);
+}
+
+godot_int GDAPI godot_packed_float32_array_size(const godot_packed_float32_array *p_self) {
+ const Vector<float> *self = (const Vector<float> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_float32_array_is_empty(const godot_packed_float32_array *p_self) {
+ const Vector<float> *self = (const Vector<float> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_float32_array_destroy(godot_packed_float32_array *p_self) {
+ ((Vector<float> *)p_self)->~Vector();
+}
+
+// float64
+
+void GDAPI godot_packed_float64_array_new(godot_packed_float64_array *r_dest) {
+ Vector<double> *dest = (Vector<double> *)r_dest;
+ memnew_placement(dest, Vector<double>);
+}
+
+void GDAPI godot_packed_float64_array_new_copy(godot_packed_float64_array *r_dest, const godot_packed_float64_array *p_src) {
+ Vector<double> *dest = (Vector<double> *)r_dest;
+ const Vector<double> *src = (const Vector<double> *)p_src;
+ memnew_placement(dest, Vector<double>(*src));
+}
+
+void GDAPI godot_packed_float64_array_new_with_array(godot_packed_float64_array *r_dest, const godot_array *p_a) {
+ Vector<double> *dest = (Vector<double> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<double>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const double GDAPI *godot_packed_float64_array_ptr(const godot_packed_float64_array *p_self) {
+ const Vector<double> *self = (const Vector<double> *)p_self;
+ return self->ptr();
+}
+
+double GDAPI *godot_packed_float64_array_ptrw(godot_packed_float64_array *p_self) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ return self->ptrw();
+}
+
+void GDAPI godot_packed_float64_array_append(godot_packed_float64_array *p_self, const double p_data) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_float64_array_append_array(godot_packed_float64_array *p_self, const godot_packed_float64_array *p_array) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ Vector<double> *array = (Vector<double> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_float64_array_insert(godot_packed_float64_array *p_self, const godot_int p_idx, const double p_data) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ return (godot_error)self->insert(p_idx, p_data);
+}
+
+godot_bool GDAPI godot_packed_float64_array_has(godot_packed_float64_array *p_self, const double p_value) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ return (godot_bool)self->has(p_value);
+}
+
+void GDAPI godot_packed_float64_array_sort(godot_packed_float64_array *p_self) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_float64_array_invert(godot_packed_float64_array *p_self) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_float64_array_push_back(godot_packed_float64_array *p_self, const double p_data) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->push_back(p_data);
+}
+
+void GDAPI godot_packed_float64_array_remove(godot_packed_float64_array *p_self, const godot_int p_idx) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_float64_array_resize(godot_packed_float64_array *p_self, const godot_int p_size) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_float64_array_set(godot_packed_float64_array *p_self, const godot_int p_idx, const double p_data) {
+ Vector<double> *self = (Vector<double> *)p_self;
+ self->set(p_idx, p_data);
+}
+
+double GDAPI godot_packed_float64_array_get(const godot_packed_float64_array *p_self, const godot_int p_idx) {
+ const Vector<double> *self = (const Vector<double> *)p_self;
+ return self->get(p_idx);
+}
+
+godot_int GDAPI godot_packed_float64_array_size(const godot_packed_float64_array *p_self) {
+ const Vector<double> *self = (const Vector<double> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_float64_array_is_empty(const godot_packed_float64_array *p_self) {
+ const Vector<double> *self = (const Vector<double> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_float64_array_destroy(godot_packed_float64_array *p_self) {
+ ((Vector<double> *)p_self)->~Vector();
+}
+
+// string
+
+void GDAPI godot_packed_string_array_new(godot_packed_string_array *r_dest) {
+ Vector<String> *dest = (Vector<String> *)r_dest;
+ memnew_placement(dest, Vector<String>);
+}
+
+void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src) {
+ Vector<String> *dest = (Vector<String> *)r_dest;
+ const Vector<String> *src = (const Vector<String> *)p_src;
+ memnew_placement(dest, Vector<String>(*src));
+}
+
+void GDAPI godot_packed_string_array_new_with_array(godot_packed_string_array *r_dest, const godot_array *p_a) {
+ Vector<String> *dest = (Vector<String> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<String>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const godot_string GDAPI *godot_packed_string_array_ptr(const godot_packed_string_array *p_self) {
+ const Vector<String> *self = (const Vector<String> *)p_self;
+ return (const godot_string *)self->ptr();
+}
+
+godot_string GDAPI *godot_packed_string_array_ptrw(godot_packed_string_array *p_self) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ return (godot_string *)self->ptrw();
+}
+
+void GDAPI godot_packed_string_array_append(godot_packed_string_array *p_self, const godot_string *p_data) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ String &s = *(String *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_string_array_append_array(godot_packed_string_array *p_self, const godot_packed_string_array *p_array) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ Vector<String> *array = (Vector<String> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_string_array_insert(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ String &s = *(String *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_string_array_has(godot_packed_string_array *p_self, const godot_string *p_value) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ String &s = *(String *)p_value;
+ return (godot_bool)self->has(s);
+}
+
+void GDAPI godot_packed_string_array_sort(godot_packed_string_array *p_self) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_string_array_invert(godot_packed_string_array *p_self) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_string_array_push_back(godot_packed_string_array *p_self, const godot_string *p_data) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ String &s = *(String *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_string_array_remove(godot_packed_string_array *p_self, const godot_int p_idx) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_string_array_resize(godot_packed_string_array *p_self, const godot_int p_size) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_string_array_set(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data) {
+ Vector<String> *self = (Vector<String> *)p_self;
+ String &s = *(String *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_string GDAPI godot_packed_string_array_get(const godot_packed_string_array *p_self, const godot_int p_idx) {
+ const Vector<String> *self = (const Vector<String> *)p_self;
+ godot_string str;
+ String *s = (String *)&str;
+ memnew_placement(s, String);
+ *s = self->get(p_idx);
+ return str;
+}
+
+godot_int GDAPI godot_packed_string_array_size(const godot_packed_string_array *p_self) {
+ const Vector<String> *self = (const Vector<String> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_string_array_is_empty(const godot_packed_string_array *p_self) {
+ const Vector<String> *self = (const Vector<String> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self) {
+ ((Vector<String> *)p_self)->~Vector();
+}
+
+// vector2
+
+void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *r_dest) {
+ Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
+ memnew_placement(dest, Vector<Vector2>);
+}
+
+void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src) {
+ Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
+ const Vector<Vector2> *src = (const Vector<Vector2> *)p_src;
+ memnew_placement(dest, Vector<Vector2>(*src));
+}
+
+void GDAPI godot_packed_vector2_array_new_with_array(godot_packed_vector2_array *r_dest, const godot_array *p_a) {
+ Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<Vector2>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const godot_vector2 GDAPI *godot_packed_vector2_array_ptr(const godot_packed_vector2_array *p_self) {
+ const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
+ return (const godot_vector2 *)self->ptr();
+}
+
+godot_vector2 GDAPI *godot_packed_vector2_array_ptrw(godot_packed_vector2_array *p_self) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ return (godot_vector2 *)self->ptrw();
+}
+
+void GDAPI godot_packed_vector2_array_append(godot_packed_vector2_array *p_self, const godot_vector2 *p_data) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector2 &s = *(Vector2 *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector2_array_append_array(godot_packed_vector2_array *p_self, const godot_packed_vector2_array *p_array) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector<Vector2> *array = (Vector<Vector2> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_vector2_array_insert(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector2 &s = *(Vector2 *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_vector2_array_has(godot_packed_vector2_array *p_self, const godot_vector2 *p_value) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector2 &v = *(Vector2 *)p_value;
+ return (godot_bool)self->has(v);
+}
+
+void GDAPI godot_packed_vector2_array_sort(godot_packed_vector2_array *p_self) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_vector2_array_invert(godot_packed_vector2_array *p_self) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_vector2_array_push_back(godot_packed_vector2_array *p_self, const godot_vector2 *p_data) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector2 &s = *(Vector2 *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector2_array_remove(godot_packed_vector2_array *p_self, const godot_int p_idx) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_vector2_array_resize(godot_packed_vector2_array *p_self, const godot_int p_size) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_vector2_array_set(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data) {
+ Vector<Vector2> *self = (Vector<Vector2> *)p_self;
+ Vector2 &s = *(Vector2 *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_vector2 GDAPI godot_packed_vector2_array_get(const godot_packed_vector2_array *p_self, const godot_int p_idx) {
+ const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
+ godot_vector2 v;
+ Vector2 *s = (Vector2 *)&v;
+ *s = self->get(p_idx);
+ return v;
+}
+
+godot_int GDAPI godot_packed_vector2_array_size(const godot_packed_vector2_array *p_self) {
+ const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_vector2_array_is_empty(const godot_packed_vector2_array *p_self) {
+ const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self) {
+ ((Vector<Vector2> *)p_self)->~Vector();
+}
+
+// vector2i
+
+void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *r_dest) {
+ Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest;
+ memnew_placement(dest, Vector<Vector2i>);
+}
+
+void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src) {
+ Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest;
+ const Vector<Vector2i> *src = (const Vector<Vector2i> *)p_src;
+ memnew_placement(dest, Vector<Vector2i>(*src));
+}
+
+void GDAPI godot_packed_vector2i_array_new_with_array(godot_packed_vector2i_array *r_dest, const godot_array *p_a) {
+ Vector<Vector2i> *dest = (Vector<Vector2i> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<Vector2i>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const godot_vector2i GDAPI *godot_packed_vector2i_array_ptr(const godot_packed_vector2i_array *p_self) {
+ const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self;
+ return (const godot_vector2i *)self->ptr();
+}
+
+godot_vector2i GDAPI *godot_packed_vector2i_array_ptrw(godot_packed_vector2i_array *p_self) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ return (godot_vector2i *)self->ptrw();
+}
+
+void GDAPI godot_packed_vector2i_array_append(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector2i &s = *(Vector2i *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector2i_array_append_array(godot_packed_vector2i_array *p_self, const godot_packed_vector2i_array *p_array) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector<Vector2i> *array = (Vector<Vector2i> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_vector2i_array_insert(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector2i &s = *(Vector2i *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_vector2i_array_has(godot_packed_vector2i_array *p_self, const godot_vector2i *p_value) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector2i &v = *(Vector2i *)p_value;
+ return (godot_bool)self->has(v);
+}
+
+void GDAPI godot_packed_vector2i_array_sort(godot_packed_vector2i_array *p_self) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_vector2i_array_invert(godot_packed_vector2i_array *p_self) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_vector2i_array_push_back(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector2i &s = *(Vector2i *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector2i_array_remove(godot_packed_vector2i_array *p_self, const godot_int p_idx) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_vector2i_array_resize(godot_packed_vector2i_array *p_self, const godot_int p_size) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_vector2i_array_set(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data) {
+ Vector<Vector2i> *self = (Vector<Vector2i> *)p_self;
+ Vector2i &s = *(Vector2i *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_vector2i GDAPI godot_packed_vector2i_array_get(const godot_packed_vector2i_array *p_self, const godot_int p_idx) {
+ const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self;
+ godot_vector2i v;
+ Vector2i *s = (Vector2i *)&v;
+ *s = self->get(p_idx);
+ return v;
+}
+
+godot_int GDAPI godot_packed_vector2i_array_size(const godot_packed_vector2i_array *p_self) {
+ const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_vector2i_array_is_empty(const godot_packed_vector2i_array *p_self) {
+ const Vector<Vector2i> *self = (const Vector<Vector2i> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self) {
+ ((Vector<Vector2i> *)p_self)->~Vector();
+}
+
+// vector3
+
+void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest) {
+ Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
+ memnew_placement(dest, Vector<Vector3>);
+}
+
+void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src) {
+ Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
+ const Vector<Vector3> *src = (const Vector<Vector3> *)p_src;
+ memnew_placement(dest, Vector<Vector3>(*src));
+}
+
+void GDAPI godot_packed_vector3_array_new_with_array(godot_packed_vector3_array *r_dest, const godot_array *p_a) {
+ Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<Vector3>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const godot_vector3 GDAPI *godot_packed_vector3_array_ptr(const godot_packed_vector3_array *p_self) {
+ const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
+ return (const godot_vector3 *)self->ptr();
+}
+
+godot_vector3 GDAPI *godot_packed_vector3_array_ptrw(godot_packed_vector3_array *p_self) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ return (godot_vector3 *)self->ptrw();
+}
+
+void GDAPI godot_packed_vector3_array_append(godot_packed_vector3_array *p_self, const godot_vector3 *p_data) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector3 &s = *(Vector3 *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector3_array_append_array(godot_packed_vector3_array *p_self, const godot_packed_vector3_array *p_array) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector<Vector3> *array = (Vector<Vector3> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_vector3_array_insert(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector3 &s = *(Vector3 *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_vector3_array_has(godot_packed_vector3_array *p_self, const godot_vector3 *p_value) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector3 &v = *(Vector3 *)p_value;
+ return (godot_bool)self->has(v);
+}
+
+void GDAPI godot_packed_vector3_array_sort(godot_packed_vector3_array *p_self) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_vector3_array_invert(godot_packed_vector3_array *p_self) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_vector3_array_push_back(godot_packed_vector3_array *p_self, const godot_vector3 *p_data) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector3 &s = *(Vector3 *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_vector3_array_remove(godot_packed_vector3_array *p_self, const godot_int p_idx) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_vector3_array_resize(godot_packed_vector3_array *p_self, const godot_int p_size) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_vector3_array_set(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data) {
+ Vector<Vector3> *self = (Vector<Vector3> *)p_self;
+ Vector3 &s = *(Vector3 *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_vector3 GDAPI godot_packed_vector3_array_get(const godot_packed_vector3_array *p_self, const godot_int p_idx) {
+ const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
+ godot_vector3 v;
+ Vector3 *s = (Vector3 *)&v;
+ *s = self->get(p_idx);
+ return v;
+}
+
+godot_int GDAPI godot_packed_vector3_array_size(const godot_packed_vector3_array *p_self) {
+ const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_vector3_array_is_empty(const godot_packed_vector3_array *p_self) {
+ const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self) {
+ ((Vector<Vector3> *)p_self)->~Vector();
+}
+
+// color
+
+void GDAPI godot_packed_color_array_new(godot_packed_color_array *r_dest) {
+ Vector<Color> *dest = (Vector<Color> *)r_dest;
+ memnew_placement(dest, Vector<Color>);
+}
+
+void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src) {
+ Vector<Color> *dest = (Vector<Color> *)r_dest;
+ const Vector<Color> *src = (const Vector<Color> *)p_src;
+ memnew_placement(dest, Vector<Color>(*src));
+}
+
+void GDAPI godot_packed_color_array_new_with_array(godot_packed_color_array *r_dest, const godot_array *p_a) {
+ Vector<Color> *dest = (Vector<Color> *)r_dest;
+ Array *a = (Array *)p_a;
+ memnew_placement(dest, Vector<Color>);
+
+ dest->resize(a->size());
+ for (int i = 0; i < a->size(); i++) {
+ dest->set(i, (*a)[i]);
+ }
+}
+
+const godot_color GDAPI *godot_packed_color_array_ptr(const godot_packed_color_array *p_self) {
+ const Vector<Color> *self = (const Vector<Color> *)p_self;
+ return (const godot_color *)self->ptr();
+}
+
+godot_color GDAPI *godot_packed_color_array_ptrw(godot_packed_color_array *p_self) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ return (godot_color *)self->ptrw();
+}
+
+void GDAPI godot_packed_color_array_append(godot_packed_color_array *p_self, const godot_color *p_data) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Color &s = *(Color *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_color_array_append_array(godot_packed_color_array *p_self, const godot_packed_color_array *p_array) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Vector<Color> *array = (Vector<Color> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_color_array_insert(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Color &s = *(Color *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_color_array_has(godot_packed_color_array *p_self, const godot_color *p_value) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Color &c = *(Color *)p_value;
+ return (godot_bool)self->has(c);
+}
+
+void GDAPI godot_packed_color_array_sort(godot_packed_color_array *p_self) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_color_array_invert(godot_packed_color_array *p_self) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_color_array_push_back(godot_packed_color_array *p_self, const godot_color *p_data) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Color &s = *(Color *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_color_array_remove(godot_packed_color_array *p_self, const godot_int p_idx) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_color_array_resize(godot_packed_color_array *p_self, const godot_int p_size) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_color_array_set(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data) {
+ Vector<Color> *self = (Vector<Color> *)p_self;
+ Color &s = *(Color *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_color GDAPI godot_packed_color_array_get(const godot_packed_color_array *p_self, const godot_int p_idx) {
+ const Vector<Color> *self = (const Vector<Color> *)p_self;
+ godot_color v;
+ Color *s = (Color *)&v;
+ *s = self->get(p_idx);
+ return v;
+}
+
+godot_int GDAPI godot_packed_color_array_size(const godot_packed_color_array *p_self) {
+ const Vector<Color> *self = (const Vector<Color> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_color_array_is_empty(const godot_packed_color_array *p_self) {
+ const Vector<Color> *self = (const Vector<Color> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self) {
+ ((Vector<Color> *)p_self)->~Vector();
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/modules/gdnative/gdnative/plane.cpp b/modules/gdnative/gdnative/plane.cpp
index 17221fe081..32a90d08fa 100644
--- a/modules/gdnative/gdnative/plane.cpp
+++ b/modules/gdnative/gdnative/plane.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,14 +31,15 @@
#include "gdnative/plane.h"
#include "core/math/plane.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
-void GDAPI godot_plane_new_with_reals(godot_plane *r_dest, const godot_real p_a, const godot_real p_b, const godot_real p_c, const godot_real p_d) {
+static_assert(sizeof(godot_plane) == sizeof(Plane), "Plane size mismatch");
+void GDAPI godot_plane_new_with_reals(godot_plane *r_dest, const godot_real p_a, const godot_real p_b, const godot_real p_c, const godot_real p_d) {
Plane *dest = (Plane *)r_dest;
*dest = Plane(p_a, p_b, p_c, p_d);
}
@@ -78,13 +79,6 @@ godot_vector3 GDAPI godot_plane_center(const godot_plane *p_self) {
return dest;
}
-godot_vector3 GDAPI godot_plane_get_any_point(const godot_plane *p_self) {
- godot_vector3 dest;
- const Plane *self = (const Plane *)p_self;
- *((Vector3 *)&dest) = self->get_any_point();
- return dest;
-}
-
godot_bool GDAPI godot_plane_is_point_over(const godot_plane *p_self, const godot_vector3 *p_point) {
const Plane *self = (const Plane *)p_self;
const Vector3 *point = (const Vector3 *)p_point;
diff --git a/modules/gdnative/gdnative/pool_arrays.cpp b/modules/gdnative/gdnative/pool_arrays.cpp
deleted file mode 100644
index 589b4d4dfe..0000000000
--- a/modules/gdnative/gdnative/pool_arrays.cpp
+++ /dev/null
@@ -1,666 +0,0 @@
-/*************************************************************************/
-/* pool_arrays.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 "gdnative/pool_arrays.h"
-
-#include "core/array.h"
-
-#include "core/variant.h"
-
-#include "core/color.h"
-#include "core/math/vector2.h"
-#include "core/math/vector3.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define memnew_placement_custom(m_placement, m_class, m_constr) _post_initialize(new (m_placement, sizeof(m_class), "") m_constr)
-
-// byte
-
-void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *r_dest) {
- Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
- memnew_placement(dest, Vector<uint8_t>);
-}
-
-void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src) {
- Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
- const Vector<uint8_t> *src = (const Vector<uint8_t> *)p_src;
- memnew_placement(dest, Vector<uint8_t>(*src));
-}
-
-void GDAPI godot_packed_byte_array_new_with_array(godot_packed_byte_array *r_dest, const godot_array *p_a) {
- Vector<uint8_t> *dest = (Vector<uint8_t> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<uint8_t>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_byte_array_append(godot_packed_byte_array *p_self, const uint8_t p_data) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_byte_array_append_array(godot_packed_byte_array *p_self, const godot_packed_byte_array *p_array) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- Vector<uint8_t> *array = (Vector<uint8_t> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_byte_array_insert(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- return (godot_error)self->insert(p_idx, p_data);
-}
-
-void GDAPI godot_packed_byte_array_invert(godot_packed_byte_array *p_self) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_byte_array_push_back(godot_packed_byte_array *p_self, const uint8_t p_data) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_byte_array_remove(godot_packed_byte_array *p_self, const godot_int p_idx) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_byte_array_resize(godot_packed_byte_array *p_self, const godot_int p_size) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_byte_array_set(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data) {
- Vector<uint8_t> *self = (Vector<uint8_t> *)p_self;
- self->set(p_idx, p_data);
-}
-
-uint8_t GDAPI godot_packed_byte_array_get(const godot_packed_byte_array *p_self, const godot_int p_idx) {
- const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
- return self->get(p_idx);
-}
-
-godot_int GDAPI godot_packed_byte_array_size(const godot_packed_byte_array *p_self) {
- const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_byte_array_empty(const godot_packed_byte_array *p_self) {
- const Vector<uint8_t> *self = (const Vector<uint8_t> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self) {
- ((Vector<uint8_t> *)p_self)->~Vector();
-}
-
-// int
-
-void GDAPI godot_packed_int_array_new(godot_packed_int_array *r_dest) {
- Vector<godot_int> *dest = (Vector<godot_int> *)r_dest;
- memnew_placement(dest, Vector<godot_int>);
-}
-
-void GDAPI godot_packed_int_array_new_copy(godot_packed_int_array *r_dest, const godot_packed_int_array *p_src) {
- Vector<godot_int> *dest = (Vector<godot_int> *)r_dest;
- const Vector<godot_int> *src = (const Vector<godot_int> *)p_src;
- memnew_placement(dest, Vector<godot_int>(*src));
-}
-
-void GDAPI godot_packed_int_array_new_with_array(godot_packed_int_array *r_dest, const godot_array *p_a) {
- Vector<godot_int> *dest = (Vector<godot_int> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<godot_int>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_int_array_append(godot_packed_int_array *p_self, const godot_int p_data) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_int_array_append_array(godot_packed_int_array *p_self, const godot_packed_int_array *p_array) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- Vector<godot_int> *array = (Vector<godot_int> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_int_array_insert(godot_packed_int_array *p_self, const godot_int p_idx, const godot_int p_data) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- return (godot_error)self->insert(p_idx, p_data);
-}
-
-void GDAPI godot_packed_int_array_invert(godot_packed_int_array *p_self) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_int_array_push_back(godot_packed_int_array *p_self, const godot_int p_data) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_int_array_remove(godot_packed_int_array *p_self, const godot_int p_idx) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_int_array_resize(godot_packed_int_array *p_self, const godot_int p_size) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_int_array_set(godot_packed_int_array *p_self, const godot_int p_idx, const godot_int p_data) {
- Vector<godot_int> *self = (Vector<godot_int> *)p_self;
- self->set(p_idx, p_data);
-}
-
-godot_int GDAPI godot_packed_int_array_get(const godot_packed_int_array *p_self, const godot_int p_idx) {
- const Vector<godot_int> *self = (const Vector<godot_int> *)p_self;
- return self->get(p_idx);
-}
-
-godot_int GDAPI godot_packed_int_array_size(const godot_packed_int_array *p_self) {
- const Vector<godot_int> *self = (const Vector<godot_int> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_int_array_empty(const godot_packed_int_array *p_self) {
- const Vector<godot_int> *self = (const Vector<godot_int> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_int_array_destroy(godot_packed_int_array *p_self) {
- ((Vector<godot_int> *)p_self)->~Vector();
-}
-
-// real
-
-void GDAPI godot_packed_real_array_new(godot_packed_real_array *r_dest) {
- Vector<godot_real> *dest = (Vector<godot_real> *)r_dest;
- memnew_placement(dest, Vector<godot_real>);
-}
-
-void GDAPI godot_packed_real_array_new_copy(godot_packed_real_array *r_dest, const godot_packed_real_array *p_src) {
- Vector<godot_real> *dest = (Vector<godot_real> *)r_dest;
- const Vector<godot_real> *src = (const Vector<godot_real> *)p_src;
- memnew_placement(dest, Vector<godot_real>(*src));
-}
-
-void GDAPI godot_packed_real_array_new_with_array(godot_packed_real_array *r_dest, const godot_array *p_a) {
- Vector<godot_real> *dest = (Vector<godot_real> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<godot_real>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_real_array_append(godot_packed_real_array *p_self, const godot_real p_data) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_real_array_append_array(godot_packed_real_array *p_self, const godot_packed_real_array *p_array) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- Vector<godot_real> *array = (Vector<godot_real> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_real_array_insert(godot_packed_real_array *p_self, const godot_int p_idx, const godot_real p_data) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- return (godot_error)self->insert(p_idx, p_data);
-}
-
-void GDAPI godot_packed_real_array_invert(godot_packed_real_array *p_self) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_real_array_push_back(godot_packed_real_array *p_self, const godot_real p_data) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->push_back(p_data);
-}
-
-void GDAPI godot_packed_real_array_remove(godot_packed_real_array *p_self, const godot_int p_idx) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_real_array_resize(godot_packed_real_array *p_self, const godot_int p_size) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_real_array_set(godot_packed_real_array *p_self, const godot_int p_idx, const godot_real p_data) {
- Vector<godot_real> *self = (Vector<godot_real> *)p_self;
- self->set(p_idx, p_data);
-}
-
-godot_real GDAPI godot_packed_real_array_get(const godot_packed_real_array *p_self, const godot_int p_idx) {
- const Vector<godot_real> *self = (const Vector<godot_real> *)p_self;
- return self->get(p_idx);
-}
-
-godot_int GDAPI godot_packed_real_array_size(const godot_packed_real_array *p_self) {
- const Vector<godot_real> *self = (const Vector<godot_real> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_real_array_empty(const godot_packed_real_array *p_self) {
- const Vector<godot_real> *self = (const Vector<godot_real> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_real_array_destroy(godot_packed_real_array *p_self) {
- ((Vector<godot_real> *)p_self)->~Vector();
-}
-
-// string
-
-void GDAPI godot_packed_string_array_new(godot_packed_string_array *r_dest) {
- Vector<String> *dest = (Vector<String> *)r_dest;
- memnew_placement(dest, Vector<String>);
-}
-
-void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src) {
- Vector<String> *dest = (Vector<String> *)r_dest;
- const Vector<String> *src = (const Vector<String> *)p_src;
- memnew_placement(dest, Vector<String>(*src));
-}
-
-void GDAPI godot_packed_string_array_new_with_array(godot_packed_string_array *r_dest, const godot_array *p_a) {
- Vector<String> *dest = (Vector<String> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<String>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_string_array_append(godot_packed_string_array *p_self, const godot_string *p_data) {
- Vector<String> *self = (Vector<String> *)p_self;
- String &s = *(String *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_string_array_append_array(godot_packed_string_array *p_self, const godot_packed_string_array *p_array) {
- Vector<String> *self = (Vector<String> *)p_self;
- Vector<String> *array = (Vector<String> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_string_array_insert(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data) {
- Vector<String> *self = (Vector<String> *)p_self;
- String &s = *(String *)p_data;
- return (godot_error)self->insert(p_idx, s);
-}
-
-void GDAPI godot_packed_string_array_invert(godot_packed_string_array *p_self) {
- Vector<String> *self = (Vector<String> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_string_array_push_back(godot_packed_string_array *p_self, const godot_string *p_data) {
- Vector<String> *self = (Vector<String> *)p_self;
- String &s = *(String *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_string_array_remove(godot_packed_string_array *p_self, const godot_int p_idx) {
- Vector<String> *self = (Vector<String> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_string_array_resize(godot_packed_string_array *p_self, const godot_int p_size) {
- Vector<String> *self = (Vector<String> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_string_array_set(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data) {
- Vector<String> *self = (Vector<String> *)p_self;
- String &s = *(String *)p_data;
- self->set(p_idx, s);
-}
-
-godot_string GDAPI godot_packed_string_array_get(const godot_packed_string_array *p_self, const godot_int p_idx) {
- const Vector<String> *self = (const Vector<String> *)p_self;
- godot_string str;
- String *s = (String *)&str;
- memnew_placement(s, String);
- *s = self->get(p_idx);
- return str;
-}
-
-godot_int GDAPI godot_packed_string_array_size(const godot_packed_string_array *p_self) {
- const Vector<String> *self = (const Vector<String> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_string_array_empty(const godot_packed_string_array *p_self) {
- const Vector<String> *self = (const Vector<String> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self) {
- ((Vector<String> *)p_self)->~Vector();
-}
-
-// vector2
-
-void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *r_dest) {
- Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
- memnew_placement(dest, Vector<Vector2>);
-}
-
-void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src) {
- Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
- const Vector<Vector2> *src = (const Vector<Vector2> *)p_src;
- memnew_placement(dest, Vector<Vector2>(*src));
-}
-
-void GDAPI godot_packed_vector2_array_new_with_array(godot_packed_vector2_array *r_dest, const godot_array *p_a) {
- Vector<Vector2> *dest = (Vector<Vector2> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<Vector2>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_vector2_array_append(godot_packed_vector2_array *p_self, const godot_vector2 *p_data) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- Vector2 &s = *(Vector2 *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_vector2_array_append_array(godot_packed_vector2_array *p_self, const godot_packed_vector2_array *p_array) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- Vector<Vector2> *array = (Vector<Vector2> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_vector2_array_insert(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- Vector2 &s = *(Vector2 *)p_data;
- return (godot_error)self->insert(p_idx, s);
-}
-
-void GDAPI godot_packed_vector2_array_invert(godot_packed_vector2_array *p_self) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_vector2_array_push_back(godot_packed_vector2_array *p_self, const godot_vector2 *p_data) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- Vector2 &s = *(Vector2 *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_vector2_array_remove(godot_packed_vector2_array *p_self, const godot_int p_idx) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_vector2_array_resize(godot_packed_vector2_array *p_self, const godot_int p_size) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_vector2_array_set(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data) {
- Vector<Vector2> *self = (Vector<Vector2> *)p_self;
- Vector2 &s = *(Vector2 *)p_data;
- self->set(p_idx, s);
-}
-
-godot_vector2 GDAPI godot_packed_vector2_array_get(const godot_packed_vector2_array *p_self, const godot_int p_idx) {
- const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
- godot_vector2 v;
- Vector2 *s = (Vector2 *)&v;
- *s = self->get(p_idx);
- return v;
-}
-
-godot_int GDAPI godot_packed_vector2_array_size(const godot_packed_vector2_array *p_self) {
- const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_vector2_array_empty(const godot_packed_vector2_array *p_self) {
- const Vector<Vector2> *self = (const Vector<Vector2> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self) {
- ((Vector<Vector2> *)p_self)->~Vector();
-}
-
-// vector3
-
-void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest) {
- Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
- memnew_placement(dest, Vector<Vector3>);
-}
-
-void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src) {
- Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
- const Vector<Vector3> *src = (const Vector<Vector3> *)p_src;
- memnew_placement(dest, Vector<Vector3>(*src));
-}
-
-void GDAPI godot_packed_vector3_array_new_with_array(godot_packed_vector3_array *r_dest, const godot_array *p_a) {
- Vector<Vector3> *dest = (Vector<Vector3> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<Vector3>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_vector3_array_append(godot_packed_vector3_array *p_self, const godot_vector3 *p_data) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- Vector3 &s = *(Vector3 *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_vector3_array_append_array(godot_packed_vector3_array *p_self, const godot_packed_vector3_array *p_array) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- Vector<Vector3> *array = (Vector<Vector3> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_vector3_array_insert(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- Vector3 &s = *(Vector3 *)p_data;
- return (godot_error)self->insert(p_idx, s);
-}
-
-void GDAPI godot_packed_vector3_array_invert(godot_packed_vector3_array *p_self) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_vector3_array_push_back(godot_packed_vector3_array *p_self, const godot_vector3 *p_data) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- Vector3 &s = *(Vector3 *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_vector3_array_remove(godot_packed_vector3_array *p_self, const godot_int p_idx) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_vector3_array_resize(godot_packed_vector3_array *p_self, const godot_int p_size) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_vector3_array_set(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data) {
- Vector<Vector3> *self = (Vector<Vector3> *)p_self;
- Vector3 &s = *(Vector3 *)p_data;
- self->set(p_idx, s);
-}
-
-godot_vector3 GDAPI godot_packed_vector3_array_get(const godot_packed_vector3_array *p_self, const godot_int p_idx) {
- const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
- godot_vector3 v;
- Vector3 *s = (Vector3 *)&v;
- *s = self->get(p_idx);
- return v;
-}
-
-godot_int GDAPI godot_packed_vector3_array_size(const godot_packed_vector3_array *p_self) {
- const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_vector3_array_empty(const godot_packed_vector3_array *p_self) {
- const Vector<Vector3> *self = (const Vector<Vector3> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self) {
- ((Vector<Vector3> *)p_self)->~Vector();
-}
-
-// color
-
-void GDAPI godot_packed_color_array_new(godot_packed_color_array *r_dest) {
- Vector<Color> *dest = (Vector<Color> *)r_dest;
- memnew_placement(dest, Vector<Color>);
-}
-
-void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src) {
- Vector<Color> *dest = (Vector<Color> *)r_dest;
- const Vector<Color> *src = (const Vector<Color> *)p_src;
- memnew_placement(dest, Vector<Color>(*src));
-}
-
-void GDAPI godot_packed_color_array_new_with_array(godot_packed_color_array *r_dest, const godot_array *p_a) {
- Vector<Color> *dest = (Vector<Color> *)r_dest;
- Array *a = (Array *)p_a;
- memnew_placement(dest, Vector<Color>);
-
- dest->resize(a->size());
- for (int i = 0; i < a->size(); i++) {
- dest->set(i, (*a)[i]);
- }
-}
-
-void GDAPI godot_packed_color_array_append(godot_packed_color_array *p_self, const godot_color *p_data) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- Color &s = *(Color *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_color_array_append_array(godot_packed_color_array *p_self, const godot_packed_color_array *p_array) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- Vector<Color> *array = (Vector<Color> *)p_array;
- self->append_array(*array);
-}
-
-godot_error GDAPI godot_packed_color_array_insert(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- Color &s = *(Color *)p_data;
- return (godot_error)self->insert(p_idx, s);
-}
-
-void GDAPI godot_packed_color_array_invert(godot_packed_color_array *p_self) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- self->invert();
-}
-
-void GDAPI godot_packed_color_array_push_back(godot_packed_color_array *p_self, const godot_color *p_data) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- Color &s = *(Color *)p_data;
- self->push_back(s);
-}
-
-void GDAPI godot_packed_color_array_remove(godot_packed_color_array *p_self, const godot_int p_idx) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- self->remove(p_idx);
-}
-
-void GDAPI godot_packed_color_array_resize(godot_packed_color_array *p_self, const godot_int p_size) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- self->resize(p_size);
-}
-
-void GDAPI godot_packed_color_array_set(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data) {
- Vector<Color> *self = (Vector<Color> *)p_self;
- Color &s = *(Color *)p_data;
- self->set(p_idx, s);
-}
-
-godot_color GDAPI godot_packed_color_array_get(const godot_packed_color_array *p_self, const godot_int p_idx) {
- const Vector<Color> *self = (const Vector<Color> *)p_self;
- godot_color v;
- Color *s = (Color *)&v;
- *s = self->get(p_idx);
- return v;
-}
-
-godot_int GDAPI godot_packed_color_array_size(const godot_packed_color_array *p_self) {
- const Vector<Color> *self = (const Vector<Color> *)p_self;
- return self->size();
-}
-
-godot_bool GDAPI godot_packed_color_array_empty(const godot_packed_color_array *p_self) {
- const Vector<Color> *self = (const Vector<Color> *)p_self;
- return self->empty();
-}
-
-void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self) {
- ((Vector<Color> *)p_self)->~Vector();
-}
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/modules/gdnative/gdnative/quat.cpp b/modules/gdnative/gdnative/quat.cpp
index be30b89e5f..29edad6636 100644
--- a/modules/gdnative/gdnative/quat.cpp
+++ b/modules/gdnative/gdnative/quat.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,14 +31,15 @@
#include "gdnative/quat.h"
#include "core/math/quat.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
-void GDAPI godot_quat_new(godot_quat *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z, const godot_real p_w) {
+static_assert(sizeof(godot_quat) == sizeof(Quat), "Quat size mismatch");
+void GDAPI godot_quat_new(godot_quat *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z, const godot_real p_w) {
Quat *dest = (Quat *)r_dest;
*dest = Quat(p_x, p_y, p_z, p_w);
}
diff --git a/modules/gdnative/gdnative/rect2.cpp b/modules/gdnative/gdnative/rect2.cpp
index 906b4f0932..40e8e64ca1 100644
--- a/modules/gdnative/gdnative/rect2.cpp
+++ b/modules/gdnative/gdnative/rect2.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,17 @@
#include "gdnative/rect2.h"
#include "core/math/transform_2d.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_rect2) == sizeof(Rect2), "Rect2 size mismatch");
+static_assert(sizeof(godot_rect2i) == sizeof(Rect2i), "Rect2i size mismatch");
+
+// Rect2
+
void GDAPI godot_rect2_new_with_position_and_size(godot_rect2 *r_dest, const godot_vector2 *p_pos, const godot_vector2 *p_size) {
const Vector2 *position = (const Vector2 *)p_pos;
const Vector2 *size = (const Vector2 *)p_size;
@@ -45,7 +50,6 @@ void GDAPI godot_rect2_new_with_position_and_size(godot_rect2 *r_dest, const god
}
void GDAPI godot_rect2_new(godot_rect2 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_width, const godot_real p_height) {
-
Rect2 *dest = (Rect2 *)r_dest;
*dest = Rect2(p_x, p_y, p_width, p_height);
}
@@ -57,6 +61,13 @@ godot_string GDAPI godot_rect2_as_string(const godot_rect2 *p_self) {
return ret;
}
+godot_rect2i GDAPI godot_rect2_as_rect2i(const godot_rect2 *p_self) {
+ godot_rect2i dest;
+ const Rect2 *self = (const Rect2 *)p_self;
+ *((Rect2i *)&dest) = Rect2i(*self);
+ return dest;
+}
+
godot_real GDAPI godot_rect2_get_area(const godot_rect2 *p_self) {
const Rect2 *self = (const Rect2 *)p_self;
return self->get_area();
@@ -79,11 +90,11 @@ godot_bool GDAPI godot_rect2_has_no_area(const godot_rect2 *p_self) {
return self->has_no_area();
}
-godot_rect2 GDAPI godot_rect2_clip(const godot_rect2 *p_self, const godot_rect2 *p_b) {
+godot_rect2 GDAPI godot_rect2_intersection(const godot_rect2 *p_self, const godot_rect2 *p_b) {
godot_rect2 dest;
const Rect2 *self = (const Rect2 *)p_self;
const Rect2 *b = (const Rect2 *)p_b;
- *((Rect2 *)&dest) = self->clip(*b);
+ *((Rect2 *)&dest) = self->intersection(*b);
return dest;
}
@@ -116,10 +127,10 @@ godot_rect2 GDAPI godot_rect2_grow_individual(const godot_rect2 *p_self, const g
return dest;
}
-godot_rect2 GDAPI godot_rect2_grow_margin(const godot_rect2 *p_self, const godot_int p_margin, const godot_real p_by) {
+godot_rect2 GDAPI godot_rect2_grow_side(const godot_rect2 *p_self, const godot_int p_side, const godot_real p_by) {
godot_rect2 dest;
const Rect2 *self = (const Rect2 *)p_self;
- *((Rect2 *)&dest) = self->grow_margin((Margin)p_margin, p_by);
+ *((Rect2 *)&dest) = self->grow_side((Side)p_side, p_by);
return dest;
}
@@ -172,6 +183,149 @@ void GDAPI godot_rect2_set_size(godot_rect2 *p_self, const godot_vector2 *p_size
self->set_size(*size);
}
+// Rect2i
+
+void GDAPI godot_rect2i_new_with_position_and_size(godot_rect2i *r_dest, const godot_vector2i *p_pos, const godot_vector2i *p_size) {
+ const Vector2i *position = (const Vector2i *)p_pos;
+ const Vector2i *size = (const Vector2i *)p_size;
+ Rect2i *dest = (Rect2i *)r_dest;
+ *dest = Rect2i(*position, *size);
+}
+
+void GDAPI godot_rect2i_new(godot_rect2i *r_dest, const godot_int p_x, const godot_int p_y, const godot_int p_width, const godot_int p_height) {
+ Rect2i *dest = (Rect2i *)r_dest;
+ *dest = Rect2i(p_x, p_y, p_width, p_height);
+}
+
+godot_string GDAPI godot_rect2i_as_string(const godot_rect2i *p_self) {
+ godot_string ret;
+ const Rect2i *self = (const Rect2i *)p_self;
+ memnew_placement(&ret, String(*self));
+ return ret;
+}
+
+godot_rect2 GDAPI godot_rect2i_as_rect2(const godot_rect2i *p_self) {
+ godot_rect2 dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *((Rect2 *)&dest) = Rect2(*self);
+ return dest;
+}
+
+godot_int GDAPI godot_rect2i_get_area(const godot_rect2i *p_self) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ return self->get_area();
+}
+
+godot_bool GDAPI godot_rect2i_intersects(const godot_rect2i *p_self, const godot_rect2i *p_b) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Rect2i *b = (const Rect2i *)p_b;
+ return self->intersects(*b);
+}
+
+godot_bool GDAPI godot_rect2i_encloses(const godot_rect2i *p_self, const godot_rect2i *p_b) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Rect2i *b = (const Rect2i *)p_b;
+ return self->encloses(*b);
+}
+
+godot_bool GDAPI godot_rect2i_has_no_area(const godot_rect2i *p_self) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ return self->has_no_area();
+}
+
+godot_rect2i GDAPI godot_rect2i_intersection(const godot_rect2i *p_self, const godot_rect2i *p_b) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Rect2i *b = (const Rect2i *)p_b;
+ *((Rect2i *)&dest) = self->intersection(*b);
+ return dest;
+}
+
+godot_rect2i GDAPI godot_rect2i_merge(const godot_rect2i *p_self, const godot_rect2i *p_b) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Rect2i *b = (const Rect2i *)p_b;
+ *((Rect2i *)&dest) = self->merge(*b);
+ return dest;
+}
+
+godot_bool GDAPI godot_rect2i_has_point(const godot_rect2i *p_self, const godot_vector2i *p_point) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Vector2i *point = (const Vector2i *)p_point;
+ return self->has_point(*point);
+}
+
+godot_rect2i GDAPI godot_rect2i_grow(const godot_rect2i *p_self, const godot_int p_by) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+
+ *((Rect2i *)&dest) = self->grow(p_by);
+ return dest;
+}
+
+godot_rect2i GDAPI godot_rect2i_grow_individual(const godot_rect2i *p_self, const godot_int p_left, const godot_int p_top, const godot_int p_right, const godot_int p_bottom) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *((Rect2i *)&dest) = self->grow_individual(p_left, p_top, p_right, p_bottom);
+ return dest;
+}
+
+godot_rect2i GDAPI godot_rect2i_grow_side(const godot_rect2i *p_self, const godot_int p_side, const godot_int p_by) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *((Rect2i *)&dest) = self->grow_side((Side)p_side, p_by);
+ return dest;
+}
+
+godot_rect2i GDAPI godot_rect2i_abs(const godot_rect2i *p_self) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *((Rect2i *)&dest) = self->abs();
+ return dest;
+}
+
+godot_rect2i GDAPI godot_rect2i_expand(const godot_rect2i *p_self, const godot_vector2i *p_to) {
+ godot_rect2i dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Vector2i *to = (const Vector2i *)p_to;
+ *((Rect2i *)&dest) = self->expand(*to);
+ return dest;
+}
+
+godot_bool GDAPI godot_rect2i_operator_equal(const godot_rect2i *p_self, const godot_rect2i *p_b) {
+ const Rect2i *self = (const Rect2i *)p_self;
+ const Rect2i *b = (const Rect2i *)p_b;
+ return *self == *b;
+}
+
+godot_vector2i GDAPI godot_rect2i_get_position(const godot_rect2i *p_self) {
+ godot_vector2i dest;
+ Vector2i *d = (Vector2i *)&dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *d = self->get_position();
+ return dest;
+}
+
+godot_vector2i GDAPI godot_rect2i_get_size(const godot_rect2i *p_self) {
+ godot_vector2i dest;
+ Vector2i *d = (Vector2i *)&dest;
+ const Rect2i *self = (const Rect2i *)p_self;
+ *d = self->get_size();
+ return dest;
+}
+
+void GDAPI godot_rect2i_set_position(godot_rect2i *p_self, const godot_vector2i *p_pos) {
+ Rect2i *self = (Rect2i *)p_self;
+ const Vector2i *position = (const Vector2i *)p_pos;
+ self->set_position(*position);
+}
+
+void GDAPI godot_rect2i_set_size(godot_rect2i *p_self, const godot_vector2i *p_size) {
+ Rect2i *self = (Rect2i *)p_self;
+ const Vector2i *size = (const Vector2i *)p_size;
+ self->set_size(*size);
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/gdnative/rid.cpp b/modules/gdnative/gdnative/rid.cpp
index 7ea80123a3..33685ef51f 100644
--- a/modules/gdnative/gdnative/rid.cpp
+++ b/modules/gdnative/gdnative/rid.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,14 +30,16 @@
#include "gdnative/rid.h"
-#include "core/resource.h"
-#include "core/rid.h"
-#include "core/variant.h"
+#include "core/io/resource.h"
+#include "core/templates/rid.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_rid) == sizeof(RID), "RID size mismatch");
+
void GDAPI godot_rid_new(godot_rid *r_dest) {
RID *dest = (RID *)r_dest;
memnew_placement(dest, RID);
diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp
index 4cb55900b0..734bbe0d16 100644
--- a/modules/gdnative/gdnative/string.cpp
+++ b/modules/gdnative/gdnative/string.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,9 +30,9 @@
#include "gdnative/string.h"
-#include "core/string_name.h"
-#include "core/ustring.h"
-#include "core/variant.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
+#include "core/variant/variant.h"
#include <string.h>
@@ -40,6 +40,11 @@
extern "C" {
#endif
+static_assert(sizeof(godot_char16_string) == sizeof(Char16String), "Char16String size mismatch");
+static_assert(sizeof(godot_char_string) == sizeof(CharString), "CharString size mismatch");
+static_assert(sizeof(godot_string) == sizeof(String), "String size mismatch");
+static_assert(sizeof(godot_char_type) == sizeof(char32_t), "char32_t size mismatch");
+
godot_int GDAPI godot_char_string_length(const godot_char_string *p_cs) {
const CharString *cs = (const CharString *)p_cs;
@@ -58,6 +63,24 @@ void GDAPI godot_char_string_destroy(godot_char_string *p_cs) {
cs->~CharString();
}
+godot_int GDAPI godot_char16_string_length(const godot_char16_string *p_cs) {
+ const Char16String *cs = (const Char16String *)p_cs;
+
+ return cs->length();
+}
+
+const char16_t GDAPI *godot_char16_string_get_data(const godot_char16_string *p_cs) {
+ const Char16String *cs = (const Char16String *)p_cs;
+
+ return cs->get_data();
+}
+
+void GDAPI godot_char16_string_destroy(godot_char16_string *p_cs) {
+ Char16String *cs = (Char16String *)p_cs;
+
+ cs->~Char16String();
+}
+
void GDAPI godot_string_new(godot_string *r_dest) {
String *dest = (String *)r_dest;
memnew_placement(dest, String);
@@ -66,27 +89,97 @@ void GDAPI godot_string_new(godot_string *r_dest) {
void GDAPI godot_string_new_copy(godot_string *r_dest, const godot_string *p_src) {
String *dest = (String *)r_dest;
const String *src = (const String *)p_src;
- memnew_placement(dest, String(*src));
+ memnew_placement(dest, String);
+ *dest = String(*src);
}
-void GDAPI godot_string_new_with_wide_string(godot_string *r_dest, const wchar_t *p_contents, const int p_size) {
+void GDAPI godot_string_new_with_latin1_chars(godot_string *r_dest, const char *p_contents) {
String *dest = (String *)r_dest;
- memnew_placement(dest, String(p_contents, p_size));
+ memnew_placement(dest, String);
+ *dest = String(p_contents);
}
-const wchar_t GDAPI *godot_string_operator_index(godot_string *p_self, const godot_int p_idx) {
+void GDAPI godot_string_new_with_utf8_chars(godot_string *r_dest, const char *p_contents) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ dest->parse_utf8(p_contents);
+}
+
+void GDAPI godot_string_new_with_utf16_chars(godot_string *r_dest, const char16_t *p_contents) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ dest->parse_utf16(p_contents);
+}
+
+void GDAPI godot_string_new_with_utf32_chars(godot_string *r_dest, const char32_t *p_contents) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ *dest = String((const char32_t *)p_contents);
+}
+
+void GDAPI godot_string_new_with_wide_chars(godot_string *r_dest, const wchar_t *p_contents) {
+ String *dest = (String *)r_dest;
+ if (sizeof(wchar_t) == 2) {
+ // wchar_t is 16 bit, parse.
+ memnew_placement(dest, String);
+ dest->parse_utf16((const char16_t *)p_contents);
+ } else {
+ // wchar_t is 32 bit, copy.
+ memnew_placement(dest, String);
+ *dest = String((const char32_t *)p_contents);
+ }
+}
+
+void GDAPI godot_string_new_with_latin1_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ *dest = String(p_contents, p_size);
+}
+
+void GDAPI godot_string_new_with_utf8_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ dest->parse_utf8(p_contents, p_size);
+}
+
+void GDAPI godot_string_new_with_utf16_chars_and_len(godot_string *r_dest, const char16_t *p_contents, const int p_size) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ dest->parse_utf16(p_contents, p_size);
+}
+
+void GDAPI godot_string_new_with_utf32_chars_and_len(godot_string *r_dest, const char32_t *p_contents, const int p_size) {
+ String *dest = (String *)r_dest;
+ memnew_placement(dest, String);
+ *dest = String((const char32_t *)p_contents, p_size);
+}
+
+void GDAPI godot_string_new_with_wide_chars_and_len(godot_string *r_dest, const wchar_t *p_contents, const int p_size) {
+ String *dest = (String *)r_dest;
+ if (sizeof(wchar_t) == 2) {
+ // wchar_t is 16 bit, parse.
+ memnew_placement(dest, String);
+ dest->parse_utf16((const char16_t *)p_contents, p_size);
+ } else {
+ // wchar_t is 32 bit, copy.
+ memnew_placement(dest, String);
+ *dest = String((const char32_t *)p_contents, p_size);
+ }
+}
+
+const godot_char_type GDAPI *godot_string_operator_index(godot_string *p_self, const godot_int p_idx) {
String *self = (String *)p_self;
return &(self->operator[](p_idx));
}
-wchar_t GDAPI godot_string_operator_index_const(const godot_string *p_self, const godot_int p_idx) {
+godot_char_type GDAPI godot_string_operator_index_const(const godot_string *p_self, const godot_int p_idx) {
const String *self = (const String *)p_self;
return self->operator[](p_idx);
}
-const wchar_t GDAPI *godot_string_wide_str(const godot_string *p_self) {
+const godot_char_type GDAPI *godot_string_get_data(const godot_string *p_self) {
const String *self = (const String *)p_self;
- return self->c_str();
+ return self->get_data();
}
godot_bool GDAPI godot_string_operator_equal(const godot_string *p_self, const godot_string *p_b) {
@@ -137,6 +230,7 @@ signed char GDAPI godot_string_nocasecmp_to(const godot_string *p_self, const go
return self->nocasecmp_to(*str);
}
+
signed char GDAPI godot_string_naturalnocasecmp_to(const godot_string *p_self, const godot_string *p_str) {
const String *self = (const String *)p_self;
const String *str = (const String *)p_str;
@@ -157,22 +251,14 @@ godot_bool GDAPI godot_string_begins_with_char_array(const godot_string *p_self,
return self->begins_with(p_char_array);
}
-godot_array GDAPI godot_string_bigrams(const godot_string *p_self) {
+godot_packed_string_array GDAPI godot_string_bigrams(const godot_string *p_self) {
const String *self = (const String *)p_self;
- Vector<String> return_value = self->bigrams();
-
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
-
- return result;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->bigrams()));
+ return ret;
};
-godot_string GDAPI godot_string_chr(wchar_t p_character) {
+godot_string GDAPI godot_string_chr(godot_char_type p_character) {
godot_string result;
memnew_placement(&result, String(String::chr(p_character)));
@@ -186,99 +272,77 @@ godot_bool GDAPI godot_string_ends_with(const godot_string *p_self, const godot_
return self->ends_with(*string);
}
-godot_int GDAPI godot_string_count(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to) {
+godot_bool GDAPI godot_string_ends_with_char_array(const godot_string *p_self, const char *p_char_array) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+
+ return self->ends_with(p_char_array);
+}
+
+godot_int GDAPI godot_string_count(const godot_string *p_self, const godot_string *p_what, godot_int p_from, godot_int p_to) {
+ const String *self = (const String *)p_self;
+ const String *what = (const String *)p_what;
return self->count(*what, p_from, p_to);
}
-godot_int GDAPI godot_string_countn(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to) {
+godot_int GDAPI godot_string_countn(const godot_string *p_self, const godot_string *p_what, godot_int p_from, godot_int p_to) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->countn(*what, p_from, p_to);
}
-godot_int GDAPI godot_string_find(const godot_string *p_self, godot_string p_what) {
+godot_int GDAPI godot_string_find(const godot_string *p_self, const godot_string *p_what) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->find(*what);
}
-godot_int GDAPI godot_string_find_from(const godot_string *p_self, godot_string p_what, godot_int p_from) {
+godot_int GDAPI godot_string_find_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->find(*what, p_from);
}
-godot_int GDAPI godot_string_findmk(const godot_string *p_self, const godot_array *p_keys) {
+godot_int GDAPI godot_string_findmk(const godot_string *p_self, const godot_packed_string_array *p_keys) {
const String *self = (const String *)p_self;
-
- Vector<String> keys;
- Array *keys_proxy = (Array *)p_keys;
- keys.resize(keys_proxy->size());
- for (int i = 0; i < keys_proxy->size(); i++) {
- keys.write[i] = (*keys_proxy)[i];
- }
-
- return self->findmk(keys);
+ const Vector<String> *keys = (const Vector<String> *)p_keys;
+ return self->findmk(*keys);
}
-godot_int GDAPI godot_string_findmk_from(const godot_string *p_self, const godot_array *p_keys, godot_int p_from) {
+godot_int GDAPI godot_string_findmk_from(const godot_string *p_self, const godot_packed_string_array *p_keys, godot_int p_from) {
const String *self = (const String *)p_self;
-
- Vector<String> keys;
- Array *keys_proxy = (Array *)p_keys;
- keys.resize(keys_proxy->size());
- for (int i = 0; i < keys_proxy->size(); i++) {
- keys.write[i] = (*keys_proxy)[i];
- }
-
- return self->findmk(keys, p_from);
+ const Vector<String> *keys = (const Vector<String> *)p_keys;
+ return self->findmk(*keys, p_from);
}
-godot_int GDAPI godot_string_findmk_from_in_place(const godot_string *p_self, const godot_array *p_keys, godot_int p_from, godot_int *r_key) {
+godot_int GDAPI godot_string_findmk_from_in_place(const godot_string *p_self, const godot_packed_string_array *p_keys, godot_int p_from, godot_int *r_key) {
const String *self = (const String *)p_self;
-
- Vector<String> keys;
- Array *keys_proxy = (Array *)p_keys;
- keys.resize(keys_proxy->size());
- for (int i = 0; i < keys_proxy->size(); i++) {
- keys.write[i] = (*keys_proxy)[i];
- }
-
+ const Vector<String> *keys = (const Vector<String> *)p_keys;
int key;
- int ret = self->findmk(keys, p_from, &key);
+ int ret = self->findmk(*keys, p_from, &key);
if (r_key) {
*r_key = key;
}
return ret;
}
-godot_int GDAPI godot_string_findn(const godot_string *p_self, godot_string p_what) {
+godot_int GDAPI godot_string_findn(const godot_string *p_self, const godot_string *p_what) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->findn(*what);
}
-godot_int GDAPI godot_string_findn_from(const godot_string *p_self, godot_string p_what, godot_int p_from) {
+godot_int GDAPI godot_string_findn_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->findn(*what, p_from);
}
-godot_int GDAPI godot_string_find_last(const godot_string *p_self, godot_string p_what) {
- const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
-
- return self->find_last(*what);
-}
-
godot_string GDAPI godot_string_format(const godot_string *p_self, const godot_variant *p_values) {
const String *self = (const String *)p_self;
const Variant *values = (const Variant *)p_values;
@@ -305,21 +369,9 @@ godot_string GDAPI godot_string_hex_encode_buffer(const uint8_t *p_buffer, godot
return result;
}
-godot_int GDAPI godot_string_hex_to_int(const godot_string *p_self) {
- const String *self = (const String *)p_self;
-
- return self->hex_to_int();
-}
-
-godot_int GDAPI godot_string_hex_to_int_without_prefix(const godot_string *p_self) {
- const String *self = (const String *)p_self;
-
- return self->hex_to_int(true);
-}
-
-godot_string GDAPI godot_string_insert(const godot_string *p_self, godot_int p_at_pos, godot_string p_string) {
+godot_string GDAPI godot_string_insert(const godot_string *p_self, godot_int p_at_pos, const godot_string *p_string) {
const String *self = (const String *)p_self;
- String *content = (String *)&p_string;
+ const String *content = (const String *)p_string;
godot_string result;
memnew_placement(&result, String(self->insert(p_at_pos, *content)));
@@ -442,58 +494,58 @@ godot_string GDAPI godot_string_pad_zeros(const godot_string *p_self, godot_int
return result;
}
-godot_string GDAPI godot_string_replace(const godot_string *p_self, godot_string p_key, godot_string p_with) {
+godot_string GDAPI godot_string_replace(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with) {
const String *self = (const String *)p_self;
- String *key = (String *)&p_key;
- String *with = (String *)&p_with;
+ const String *key = (const String *)p_key;
+ const String *with = (const String *)p_with;
godot_string result;
memnew_placement(&result, String(self->replace(*key, *with)));
return result;
}
-godot_string GDAPI godot_string_replacen(const godot_string *p_self, godot_string p_key, godot_string p_with) {
+godot_string GDAPI godot_string_replacen(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with) {
const String *self = (const String *)p_self;
- String *key = (String *)&p_key;
- String *with = (String *)&p_with;
+ const String *key = (const String *)p_key;
+ const String *with = (const String *)p_with;
godot_string result;
memnew_placement(&result, String(self->replacen(*key, *with)));
return result;
}
-godot_int GDAPI godot_string_rfind(const godot_string *p_self, godot_string p_what) {
+godot_int GDAPI godot_string_rfind(const godot_string *p_self, const godot_string *p_what) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->rfind(*what);
}
-godot_int GDAPI godot_string_rfindn(const godot_string *p_self, godot_string p_what) {
+godot_int GDAPI godot_string_rfindn(const godot_string *p_self, const godot_string *p_what) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->rfindn(*what);
}
-godot_int GDAPI godot_string_rfind_from(const godot_string *p_self, godot_string p_what, godot_int p_from) {
+godot_int GDAPI godot_string_rfind_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->rfind(*what, p_from);
}
-godot_int GDAPI godot_string_rfindn_from(const godot_string *p_self, godot_string p_what, godot_int p_from) {
+godot_int GDAPI godot_string_rfindn_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from) {
const String *self = (const String *)p_self;
- String *what = (String *)&p_what;
+ const String *what = (const String *)p_what;
return self->rfindn(*what, p_from);
}
-godot_string GDAPI godot_string_replace_first(const godot_string *p_self, godot_string p_key, godot_string p_with) {
+godot_string GDAPI godot_string_replace_first(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with) {
const String *self = (const String *)p_self;
- String *key = (String *)&p_key;
- String *with = (String *)&p_with;
+ const String *key = (const String *)p_key;
+ const String *with = (const String *)p_with;
godot_string result;
memnew_placement(&result, String(self->replace_first(*key, *with)));
@@ -543,24 +595,18 @@ godot_string GDAPI godot_string_substr(const godot_string *p_self, godot_int p_f
return result;
}
-double GDAPI godot_string_to_double(const godot_string *p_self) {
+godot_int GDAPI godot_string_to_int(const godot_string *p_self) {
const String *self = (const String *)p_self;
- return self->to_double();
+ return self->to_int();
}
-godot_real GDAPI godot_string_to_float(const godot_string *p_self) {
+double GDAPI godot_string_to_float(const godot_string *p_self) {
const String *self = (const String *)p_self;
return self->to_float();
}
-godot_int GDAPI godot_string_to_int(const godot_string *p_self) {
- const String *self = (const String *)p_self;
-
- return self->to_int();
-}
-
godot_string GDAPI godot_string_capitalize(const godot_string *p_self) {
const String *self = (const String *)p_self;
godot_string result;
@@ -585,15 +631,19 @@ godot_string GDAPI godot_string_camelcase_to_underscore_lowercased(const godot_s
return result;
}
-double GDAPI godot_string_char_to_double(const char *p_what) {
- return String::to_double(p_what);
+double GDAPI godot_string_char_to_float(const char *p_what) {
+ return String::to_float(p_what);
+}
+
+double GDAPI godot_string_wchar_to_float(const wchar_t *p_str, const wchar_t **r_end) {
+ return String::to_float(p_str, r_end);
}
godot_int GDAPI godot_string_char_to_int(const char *p_what) {
return String::to_int(p_what);
}
-int64_t GDAPI godot_string_wchar_to_int(const wchar_t *p_str) {
+godot_int GDAPI godot_string_wchar_to_int(const wchar_t *p_str) {
return String::to_int(p_str);
}
@@ -601,42 +651,32 @@ godot_int GDAPI godot_string_char_to_int_with_len(const char *p_what, godot_int
return String::to_int(p_what, p_len);
}
-int64_t GDAPI godot_string_char_to_int64_with_len(const wchar_t *p_str, int p_len) {
+godot_int GDAPI godot_string_wchar_to_int_with_len(const wchar_t *p_str, int p_len) {
return String::to_int(p_str, p_len);
}
-int64_t GDAPI godot_string_hex_to_int64(const godot_string *p_self) {
- const String *self = (const String *)p_self;
-
- return self->hex_to_int64(false);
-}
-
-int64_t GDAPI godot_string_hex_to_int64_with_prefix(const godot_string *p_self) {
+godot_int GDAPI godot_string_hex_to_int(const godot_string *p_self) {
const String *self = (const String *)p_self;
- return self->hex_to_int64();
+ return self->hex_to_int(false);
}
-int64_t GDAPI godot_string_to_int64(const godot_string *p_self) {
+godot_int GDAPI godot_string_hex_to_int_with_prefix(const godot_string *p_self) {
const String *self = (const String *)p_self;
- return self->to_int64();
-}
-
-double GDAPI godot_string_unicode_char_to_double(const wchar_t *p_str, const wchar_t **r_end) {
- return String::to_double(p_str, r_end);
+ return self->hex_to_int();
}
-godot_string GDAPI godot_string_get_slice(const godot_string *p_self, godot_string p_splitter, godot_int p_slice) {
+godot_string GDAPI godot_string_get_slice(const godot_string *p_self, const godot_string *p_splitter, godot_int p_slice) {
const String *self = (const String *)p_self;
- String *splitter = (String *)&p_splitter;
+ const String *splitter = (const String *)p_splitter;
godot_string result;
memnew_placement(&result, String(self->get_slice(*splitter, p_slice)));
return result;
}
-godot_string GDAPI godot_string_get_slicec(const godot_string *p_self, wchar_t p_splitter, godot_int p_slice) {
+godot_string GDAPI godot_string_get_slicec(const godot_string *p_self, godot_char_type p_splitter, godot_int p_slice) {
const String *self = (const String *)p_self;
godot_string result;
memnew_placement(&result, String(self->get_slicec(p_splitter, p_slice)));
@@ -644,221 +684,149 @@ godot_string GDAPI godot_string_get_slicec(const godot_string *p_self, wchar_t p
return result;
}
-godot_array GDAPI godot_string_split(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_string_array GDAPI godot_string_split(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<String> return_value = self->split(*splitter, false);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
-
- return result;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->split(*splitter, false)));
+ return ret;
}
-godot_array GDAPI godot_string_split_allow_empty(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_string_array GDAPI godot_string_split_allow_empty(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<String> return_value = self->split(*splitter);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->split(*splitter, true)));
+ return ret;
+}
- return result;
+godot_packed_string_array GDAPI godot_string_split_with_maxsplit(const godot_string *p_self, const godot_string *p_splitter, const godot_bool p_allow_empty, const godot_int p_maxsplit) {
+ const String *self = (const String *)p_self;
+ const String *splitter = (const String *)p_splitter;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->split(*splitter, p_allow_empty, p_maxsplit)));
+ return ret;
}
-godot_array GDAPI godot_string_split_floats(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<float> return_value = self->split_floats(*splitter, false);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
- return result;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->rsplit(*splitter, false)));
+ return ret;
}
-godot_array GDAPI godot_string_split_floats_allows_empty(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_string_array GDAPI godot_string_rsplit_allow_empty(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<float> return_value = self->split_floats(*splitter);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
- return result;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->rsplit(*splitter, true)));
+ return ret;
}
-godot_array GDAPI godot_string_split_floats_mk(const godot_string *p_self, const godot_array *p_splitters) {
+godot_packed_string_array GDAPI godot_string_rsplit_with_maxsplit(const godot_string *p_self, const godot_string *p_splitter, const godot_bool p_allow_empty, const godot_int p_maxsplit) {
const String *self = (const String *)p_self;
+ const String *splitter = (const String *)p_splitter;
- Vector<String> splitters;
- Array *splitter_proxy = (Array *)p_splitters;
- splitters.resize(splitter_proxy->size());
- for (int i = 0; i < splitter_proxy->size(); i++) {
- splitters.write[i] = (*splitter_proxy)[i];
- }
-
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<float> return_value = self->split_floats_mk(splitters, false);
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->rsplit(*splitter, p_allow_empty, p_maxsplit)));
+ return ret;
+}
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
+godot_packed_float32_array GDAPI godot_string_split_floats(const godot_string *p_self, const godot_string *p_splitter) {
+ const String *self = (const String *)p_self;
+ const String *splitter = (const String *)p_splitter;
- return result;
+ godot_packed_float32_array ret;
+ memnew_placement(&ret, Vector<float>(self->split_floats(*splitter, false)));
+ return ret;
}
-godot_array GDAPI godot_string_split_floats_mk_allows_empty(const godot_string *p_self, const godot_array *p_splitters) {
+godot_packed_float32_array GDAPI godot_string_split_floats_allow_empty(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
+ const String *splitter = (const String *)p_splitter;
- Vector<String> splitters;
- Array *splitter_proxy = (Array *)p_splitters;
- splitters.resize(splitter_proxy->size());
- for (int i = 0; i < splitter_proxy->size(); i++) {
- splitters.write[i] = (*splitter_proxy)[i];
- }
-
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<float> return_value = self->split_floats_mk(splitters);
+ godot_packed_float32_array ret;
+ memnew_placement(&ret, Vector<float>(self->split_floats(*splitter, true)));
+ return ret;
+}
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
+godot_packed_float32_array GDAPI godot_string_split_floats_mk(const godot_string *p_self, const godot_packed_string_array *p_splitters) {
+ const String *self = (const String *)p_self;
+ const Vector<String> *splitters = (const Vector<String> *)p_splitters;
- return result;
+ godot_packed_float32_array ret;
+ memnew_placement(&ret, Vector<float>(self->split_floats_mk(*splitters, false)));
+ return ret;
}
-godot_array GDAPI godot_string_split_ints(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_float32_array GDAPI godot_string_split_floats_mk_allow_empty(const godot_string *p_self, const godot_packed_string_array *p_splitters) {
const String *self = (const String *)p_self;
- const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<int> return_value = self->split_ints(*splitter, false);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
+ const Vector<String> *splitters = (const Vector<String> *)p_splitters;
- return result;
+ godot_packed_float32_array ret;
+ memnew_placement(&ret, Vector<float>(self->split_floats_mk(*splitters, true)));
+ return ret;
}
-godot_array GDAPI godot_string_split_ints_allows_empty(const godot_string *p_self, const godot_string *p_splitter) {
+godot_packed_int32_array GDAPI godot_string_split_ints(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
const String *splitter = (const String *)p_splitter;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<int> return_value = self->split_ints(*splitter);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
- return result;
+ godot_packed_int32_array ret;
+ memnew_placement(&ret, Vector<int>(self->split_ints(*splitter, false)));
+ return ret;
}
-godot_array GDAPI godot_string_split_ints_mk(const godot_string *p_self, const godot_array *p_splitters) {
+godot_packed_int32_array GDAPI godot_string_split_ints_allow_empty(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
+ const String *splitter = (const String *)p_splitter;
- Vector<String> splitters;
- Array *splitter_proxy = (Array *)p_splitters;
- splitters.resize(splitter_proxy->size());
- for (int i = 0; i < splitter_proxy->size(); i++) {
- splitters.write[i] = (*splitter_proxy)[i];
- }
-
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<int> return_value = self->split_ints_mk(splitters, false);
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
-
- return result;
+ godot_packed_int32_array ret;
+ memnew_placement(&ret, Vector<int>(self->split_ints(*splitter, true)));
+ return ret;
}
-godot_array GDAPI godot_string_split_ints_mk_allows_empty(const godot_string *p_self, const godot_array *p_splitters) {
+godot_packed_int32_array GDAPI godot_string_split_ints_mk(const godot_string *p_self, const godot_packed_string_array *p_splitters) {
const String *self = (const String *)p_self;
+ const Vector<String> *splitters = (const Vector<String> *)p_splitters;
- Vector<String> splitters;
- Array *splitter_proxy = (Array *)p_splitters;
- splitters.resize(splitter_proxy->size());
- for (int i = 0; i < splitter_proxy->size(); i++) {
- splitters.write[i] = (*splitter_proxy)[i];
- }
-
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<int> return_value = self->split_ints_mk(splitters);
+ godot_packed_int32_array ret;
+ memnew_placement(&ret, Vector<int>(self->split_ints_mk(*splitters, false)));
+ return ret;
+}
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
+godot_packed_int32_array GDAPI godot_string_split_ints_mk_allow_empty(const godot_string *p_self, const godot_packed_string_array *p_splitters) {
+ const String *self = (const String *)p_self;
+ const Vector<String> *splitters = (const Vector<String> *)p_splitters;
- return result;
+ godot_packed_int32_array ret;
+ memnew_placement(&ret, Vector<int>(self->split_ints_mk(*splitters, true)));
+ return ret;
}
-godot_array GDAPI godot_string_split_spaces(const godot_string *p_self) {
+godot_packed_string_array GDAPI godot_string_split_spaces(const godot_string *p_self) {
const String *self = (const String *)p_self;
- godot_array result;
- memnew_placement(&result, Array);
- Array *proxy = (Array *)&result;
- Vector<String> return_value = self->split_spaces();
-
- proxy->resize(return_value.size());
- for (int i = 0; i < return_value.size(); i++) {
- (*proxy)[i] = return_value[i];
- }
- return result;
+ godot_packed_string_array ret;
+ memnew_placement(&ret, Vector<String>(self->split_spaces()));
+ return ret;
}
-godot_int GDAPI godot_string_get_slice_count(const godot_string *p_self, godot_string p_splitter) {
+godot_int GDAPI godot_string_get_slice_count(const godot_string *p_self, const godot_string *p_splitter) {
const String *self = (const String *)p_self;
- String *splitter = (String *)&p_splitter;
+ const String *splitter = (const String *)p_splitter;
return self->get_slice_count(*splitter);
}
-wchar_t GDAPI godot_string_char_lowercase(wchar_t p_char) {
+godot_char_type GDAPI godot_string_char_lowercase(godot_char_type p_char) {
return String::char_lowercase(p_char);
}
-wchar_t GDAPI godot_string_char_uppercase(wchar_t p_char) {
+godot_char_type GDAPI godot_string_char_uppercase(godot_char_type p_char) {
return String::char_uppercase(p_char);
}
@@ -902,7 +870,7 @@ godot_string GDAPI godot_string_left(const godot_string *p_self, godot_int p_pos
return result;
}
-wchar_t GDAPI godot_string_ord_at(const godot_string *p_self, godot_int p_idx) {
+godot_char_type GDAPI godot_string_ord_at(const godot_string *p_self, godot_int p_idx) {
const String *self = (const String *)p_self;
return self->ord_at(p_idx);
@@ -925,6 +893,14 @@ godot_string GDAPI godot_string_right(const godot_string *p_self, godot_int p_po
return result;
}
+godot_string GDAPI godot_string_repeat(const godot_string *p_self, godot_int p_count) {
+ const String *self = (const String *)p_self;
+ godot_string result;
+ memnew_placement(&result, String(self->repeat(p_count)));
+
+ return result;
+}
+
godot_string GDAPI godot_string_strip_edges(const godot_string *p_self, godot_bool p_left, godot_bool p_right) {
const String *self = (const String *)p_self;
godot_string result;
@@ -956,7 +932,7 @@ godot_char_string GDAPI godot_string_ascii(const godot_string *p_self) {
return result;
}
-godot_char_string GDAPI godot_string_ascii_extended(const godot_string *p_self) {
+godot_char_string GDAPI godot_string_latin1(const godot_string *p_self) {
const String *self = (const String *)p_self;
godot_char_string result;
@@ -1002,6 +978,42 @@ godot_string GDAPI godot_string_chars_to_utf8_with_len(const char *p_utf8, godot
return result;
}
+godot_char16_string GDAPI godot_string_utf16(const godot_string *p_self) {
+ const String *self = (const String *)p_self;
+
+ godot_char16_string result;
+
+ memnew_placement(&result, Char16String(self->utf16()));
+
+ return result;
+}
+
+godot_bool GDAPI godot_string_parse_utf16(godot_string *p_self, const char16_t *p_utf16) {
+ String *self = (String *)p_self;
+
+ return self->parse_utf16(p_utf16);
+}
+
+godot_bool GDAPI godot_string_parse_utf16_with_len(godot_string *p_self, const char16_t *p_utf16, godot_int p_len) {
+ String *self = (String *)p_self;
+
+ return self->parse_utf16(p_utf16, p_len);
+}
+
+godot_string GDAPI godot_string_chars_to_utf16(const char16_t *p_utf16) {
+ godot_string result;
+ memnew_placement(&result, String(String::utf16(p_utf16)));
+
+ return result;
+}
+
+godot_string GDAPI godot_string_chars_to_utf16_with_len(const char16_t *p_utf16, godot_int p_len) {
+ godot_string result;
+ memnew_placement(&result, String(String::utf16(p_utf16, p_len)));
+
+ return result;
+}
+
uint32_t GDAPI godot_string_hash(const godot_string *p_self) {
const String *self = (const String *)p_self;
@@ -1022,28 +1034,18 @@ uint32_t GDAPI godot_string_hash_chars_with_len(const char *p_cstr, godot_int p_
return String::hash(p_cstr, p_len);
}
-uint32_t GDAPI godot_string_hash_utf8_chars(const wchar_t *p_str) {
+uint32_t GDAPI godot_string_hash_wide_chars(const wchar_t *p_str) {
return String::hash(p_str);
}
-uint32_t GDAPI godot_string_hash_utf8_chars_with_len(const wchar_t *p_str, godot_int p_len) {
+uint32_t GDAPI godot_string_hash_wide_chars_with_len(const wchar_t *p_str, godot_int p_len) {
return String::hash(p_str, p_len);
}
godot_packed_byte_array GDAPI godot_string_md5_buffer(const godot_string *p_self) {
const String *self = (const String *)p_self;
- Vector<uint8_t> tmp_result = self->md5_buffer();
-
godot_packed_byte_array result;
- memnew_placement(&result, PackedByteArray);
- PackedByteArray *proxy = (PackedByteArray *)&result;
- uint8_t *proxy_writer = proxy->ptrw();
- proxy->resize(tmp_result.size());
-
- for (int i = 0; i < tmp_result.size(); i++) {
- proxy_writer[i] = tmp_result[i];
- }
-
+ memnew_placement(&result, PackedByteArray(self->md5_buffer()));
return result;
}
@@ -1055,23 +1057,28 @@ godot_string GDAPI godot_string_md5_text(const godot_string *p_self) {
return result;
}
-godot_packed_byte_array GDAPI godot_string_sha256_buffer(const godot_string *p_self) {
+godot_packed_byte_array GDAPI godot_string_sha1_buffer(const godot_string *p_self) {
const String *self = (const String *)p_self;
- Vector<uint8_t> tmp_result = self->sha256_buffer();
-
godot_packed_byte_array result;
- memnew_placement(&result, PackedByteArray);
- PackedByteArray *proxy = (PackedByteArray *)&result;
- uint8_t *proxy_writer = proxy->ptrw();
- proxy->resize(tmp_result.size());
+ memnew_placement(&result, PackedByteArray(self->sha1_buffer()));
+ return result;
+}
- for (int i = 0; i < tmp_result.size(); i++) {
- proxy_writer[i] = tmp_result[i];
- }
+godot_string GDAPI godot_string_sha1_text(const godot_string *p_self) {
+ const String *self = (const String *)p_self;
+ godot_string result;
+ memnew_placement(&result, String(self->sha1_text()));
return result;
}
+godot_packed_byte_array GDAPI godot_string_sha256_buffer(const godot_string *p_self) {
+ const String *self = (const String *)p_self;
+ godot_packed_byte_array result;
+ memnew_placement(&result, PackedByteArray(self->sha256_buffer()));
+ return result;
+}
+
godot_string GDAPI godot_string_sha256_text(const godot_string *p_self) {
const String *self = (const String *)p_self;
godot_string result;
@@ -1080,10 +1087,10 @@ godot_string GDAPI godot_string_sha256_text(const godot_string *p_self) {
return result;
}
-godot_bool godot_string_empty(const godot_string *p_self) {
+godot_bool godot_string_is_empty(const godot_string *p_self) {
const String *self = (const String *)p_self;
- return self->empty();
+ return self->is_empty();
}
// path functions
@@ -1105,7 +1112,7 @@ godot_string GDAPI godot_string_get_file(const godot_string *p_self) {
return result;
}
-godot_string GDAPI godot_string_humanize_size(size_t p_size) {
+godot_string GDAPI godot_string_humanize_size(uint64_t p_size) {
godot_string result;
String return_value = String::humanize_size(p_size);
memnew_placement(&result, String(return_value));
@@ -1214,15 +1221,6 @@ godot_string GDAPI godot_string_json_escape(const godot_string *p_self) {
return result;
}
-godot_string GDAPI godot_string_word_wrap(const godot_string *p_self, godot_int p_chars_per_line) {
- const String *self = (const String *)p_self;
- godot_string result;
- String return_value = self->word_wrap(p_chars_per_line);
- memnew_placement(&result, String(return_value));
-
- return result;
-}
-
godot_string GDAPI godot_string_xml_escape(const godot_string *p_self) {
const String *self = (const String *)p_self;
godot_string result;
@@ -1268,6 +1266,22 @@ godot_string GDAPI godot_string_percent_encode(const godot_string *p_self) {
return result;
}
+godot_string GDAPI godot_string_join(const godot_string *p_self, const godot_packed_string_array *p_parts) {
+ const String *self = (const String *)p_self;
+ const Vector<String> *parts = (const Vector<String> *)p_parts;
+ godot_string result;
+ String return_value = self->join(*parts);
+ memnew_placement(&result, String(return_value));
+
+ return result;
+}
+
+godot_bool GDAPI godot_string_is_valid_filename(const godot_string *p_self) {
+ const String *self = (const String *)p_self;
+
+ return self->is_valid_filename();
+}
+
godot_bool GDAPI godot_string_is_valid_float(const godot_string *p_self) {
const String *self = (const String *)p_self;
@@ -1333,31 +1347,22 @@ godot_string GDAPI godot_string_trim_suffix(const godot_string *p_self, const go
return result;
}
-godot_string GDAPI godot_string_rstrip(const godot_string *p_self, const godot_string *p_chars) {
+godot_string GDAPI godot_string_lstrip(const godot_string *p_self, const godot_string *p_chars) {
const String *self = (const String *)p_self;
String *chars = (String *)p_chars;
godot_string result;
- String return_value = self->rstrip(*chars);
+ String return_value = self->lstrip(*chars);
memnew_placement(&result, String(return_value));
return result;
}
-godot_packed_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_divisor,
- const godot_bool p_allow_empty, const godot_int p_maxsplit) {
+godot_string GDAPI godot_string_rstrip(const godot_string *p_self, const godot_string *p_chars) {
const String *self = (const String *)p_self;
- String *divisor = (String *)p_divisor;
-
- godot_packed_string_array result;
- memnew_placement(&result, PackedStringArray);
- PackedStringArray *proxy = (PackedStringArray *)&result;
- String *proxy_writer = proxy->ptrw();
- Vector<String> tmp_result = self->rsplit(*divisor, p_allow_empty, p_maxsplit);
- proxy->resize(tmp_result.size());
-
- for (int i = 0; i < tmp_result.size(); i++) {
- proxy_writer[i] = tmp_result[i];
- }
+ String *chars = (String *)p_chars;
+ godot_string result;
+ String return_value = self->rstrip(*chars);
+ memnew_placement(&result, String(return_value));
return result;
}
diff --git a/modules/gdnative/gdnative/string_name.cpp b/modules/gdnative/gdnative/string_name.cpp
index 1abb4486b1..3d83f744d6 100644
--- a/modules/gdnative/gdnative/string_name.cpp
+++ b/modules/gdnative/gdnative/string_name.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,8 +30,8 @@
#include "gdnative/string_name.h"
-#include "core/string_name.h"
-#include "core/ustring.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
#include <string.h>
@@ -39,6 +39,8 @@
extern "C" {
#endif
+static_assert(sizeof(godot_string_name) == sizeof(StringName), "StringName size mismatch");
+
void GDAPI godot_string_name_new(godot_string_name *r_dest, const godot_string *p_name) {
StringName *dest = (StringName *)r_dest;
const String *name = (const String *)p_name;
diff --git a/modules/gdnative/gdnative/transform.cpp b/modules/gdnative/gdnative/transform.cpp
index c9b3e37fb2..059e12b401 100644
--- a/modules/gdnative/gdnative/transform.cpp
+++ b/modules/gdnative/gdnative/transform.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,14 @@
#include "gdnative/transform.h"
#include "core/math/transform.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_transform) == sizeof(Transform), "Transform size mismatch");
+
void GDAPI godot_transform_new_with_axis_origin(godot_transform *r_dest, const godot_vector3 *p_x_axis, const godot_vector3 *p_y_axis, const godot_vector3 *p_z_axis, const godot_vector3 *p_origin) {
const Vector3 *x_axis = (const Vector3 *)p_x_axis;
const Vector3 *y_axis = (const Vector3 *)p_y_axis;
diff --git a/modules/gdnative/gdnative/transform2d.cpp b/modules/gdnative/gdnative/transform2d.cpp
index 26a71333b1..878599514d 100644
--- a/modules/gdnative/gdnative/transform2d.cpp
+++ b/modules/gdnative/gdnative/transform2d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,14 @@
#include "gdnative/transform2d.h"
#include "core/math/transform_2d.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_transform2d) == sizeof(Transform2D), "Transform2D size mismatch");
+
void GDAPI godot_transform2d_new(godot_transform2d *r_dest, const godot_real p_rot, const godot_vector2 *p_pos) {
const Vector2 *pos = (const Vector2 *)p_pos;
Transform2D *dest = (Transform2D *)r_dest;
diff --git a/modules/gdnative/gdnative/variant.cpp b/modules/gdnative/gdnative/variant.cpp
index f0fc44ae8a..7ee5fe59e2 100644
--- a/modules/gdnative/gdnative/variant.cpp
+++ b/modules/gdnative/gdnative/variant.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,15 @@
#include "gdnative/variant.h"
-#include "core/reference.h"
-#include "core/variant.h"
+#include "core/object/reference.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
+static_assert(sizeof(godot_variant) == sizeof(Variant), "Variant size mismatch");
+
// Workaround GCC ICE on armv7hl which was affected GCC 6.0 up to 8.0 (GH-16100).
// It was fixed upstream in 8.1, and a fix was backported to 7.4.
// This can be removed once no supported distro ships with versions older than 7.4.
@@ -97,24 +99,48 @@ void GDAPI godot_variant_new_string(godot_variant *r_dest, const godot_string *p
memnew_placement_custom(dest, Variant, Variant(*s));
}
+void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s) {
+ Variant *dest = (Variant *)r_dest;
+ StringName *s = (StringName *)p_s;
+ memnew_placement_custom(dest, Variant, Variant(*s));
+}
+
void GDAPI godot_variant_new_vector2(godot_variant *r_dest, const godot_vector2 *p_v2) {
Variant *dest = (Variant *)r_dest;
Vector2 *v2 = (Vector2 *)p_v2;
memnew_placement_custom(dest, Variant, Variant(*v2));
}
+void GDAPI godot_variant_new_vector2i(godot_variant *r_dest, const godot_vector2i *p_v2) {
+ Variant *dest = (Variant *)r_dest;
+ Vector2i *v2 = (Vector2i *)p_v2;
+ memnew_placement_custom(dest, Variant, Variant(*v2));
+}
+
void GDAPI godot_variant_new_rect2(godot_variant *r_dest, const godot_rect2 *p_rect2) {
Variant *dest = (Variant *)r_dest;
Rect2 *rect2 = (Rect2 *)p_rect2;
memnew_placement_custom(dest, Variant, Variant(*rect2));
}
+void GDAPI godot_variant_new_rect2i(godot_variant *r_dest, const godot_rect2i *p_rect2) {
+ Variant *dest = (Variant *)r_dest;
+ Rect2i *rect2 = (Rect2i *)p_rect2;
+ memnew_placement_custom(dest, Variant, Variant(*rect2));
+}
+
void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 *p_v3) {
Variant *dest = (Variant *)r_dest;
Vector3 *v3 = (Vector3 *)p_v3;
memnew_placement_custom(dest, Variant, Variant(*v3));
}
+void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3) {
+ Variant *dest = (Variant *)r_dest;
+ Vector3i *v3 = (Vector3i *)p_v3;
+ memnew_placement_custom(dest, Variant, Variant(*v3));
+}
+
void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d) {
Variant *dest = (Variant *)r_dest;
Transform2D *t2d = (Transform2D *)p_t2d;
@@ -169,6 +195,18 @@ void GDAPI godot_variant_new_rid(godot_variant *r_dest, const godot_rid *p_rid)
memnew_placement_custom(dest, Variant, Variant(*rid));
}
+void GDAPI godot_variant_new_callable(godot_variant *r_dest, const godot_callable *p_cb) {
+ Variant *dest = (Variant *)r_dest;
+ Callable *cb = (Callable *)p_cb;
+ memnew_placement_custom(dest, Variant, Variant(*cb));
+}
+
+void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p_signal) {
+ Variant *dest = (Variant *)r_dest;
+ Signal *signal = (Signal *)p_signal;
+ memnew_placement_custom(dest, Variant, Variant(*signal));
+}
+
void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj) {
Variant *dest = (Variant *)r_dest;
Object *obj = (Object *)p_obj;
@@ -207,18 +245,30 @@ void GDAPI godot_variant_new_packed_byte_array(godot_variant *r_dest, const godo
memnew_placement_custom(dest, Variant, Variant(*pba));
}
-void GDAPI godot_variant_new_packed_int_array(godot_variant *r_dest, const godot_packed_int_array *p_pia) {
+void GDAPI godot_variant_new_packed_int32_array(godot_variant *r_dest, const godot_packed_int32_array *p_pia) {
Variant *dest = (Variant *)r_dest;
PackedInt32Array *pia = (PackedInt32Array *)p_pia;
memnew_placement_custom(dest, Variant, Variant(*pia));
}
-void GDAPI godot_variant_new_packed_real_array(godot_variant *r_dest, const godot_packed_real_array *p_pra) {
+void GDAPI godot_variant_new_packed_int64_array(godot_variant *r_dest, const godot_packed_int64_array *p_pia) {
+ Variant *dest = (Variant *)r_dest;
+ PackedInt64Array *pia = (PackedInt64Array *)p_pia;
+ memnew_placement_custom(dest, Variant, Variant(*pia));
+}
+
+void GDAPI godot_variant_new_packed_float32_array(godot_variant *r_dest, const godot_packed_float32_array *p_pra) {
Variant *dest = (Variant *)r_dest;
PackedFloat32Array *pra = (PackedFloat32Array *)p_pra;
memnew_placement_custom(dest, Variant, Variant(*pra));
}
+void GDAPI godot_variant_new_packed_float64_array(godot_variant *r_dest, const godot_packed_float64_array *p_pra) {
+ Variant *dest = (Variant *)r_dest;
+ PackedFloat64Array *pra = (PackedFloat64Array *)p_pra;
+ memnew_placement_custom(dest, Variant, Variant(*pra));
+}
+
void GDAPI godot_variant_new_packed_string_array(godot_variant *r_dest, const godot_packed_string_array *p_psa) {
Variant *dest = (Variant *)r_dest;
PackedStringArray *psa = (PackedStringArray *)p_psa;
@@ -271,6 +321,14 @@ godot_string GDAPI godot_variant_as_string(const godot_variant *p_self) {
return raw_dest;
}
+godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self) {
+ godot_string_name raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ StringName *dest = (StringName *)&raw_dest;
+ memnew_placement(dest, StringName(self->operator StringName())); // operator = is overloaded by StringName
+ return raw_dest;
+}
+
godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self) {
godot_vector2 raw_dest;
const Variant *self = (const Variant *)p_self;
@@ -279,6 +337,14 @@ godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self) {
return raw_dest;
}
+godot_vector2i GDAPI godot_variant_as_vector2i(const godot_variant *p_self) {
+ godot_vector2i raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ *dest = *self;
+ return raw_dest;
+}
+
godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self) {
godot_rect2 raw_dest;
const Variant *self = (const Variant *)p_self;
@@ -287,6 +353,14 @@ godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self) {
return raw_dest;
}
+godot_rect2i GDAPI godot_variant_as_rect2i(const godot_variant *p_self) {
+ godot_rect2i raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ Rect2i *dest = (Rect2i *)&raw_dest;
+ *dest = *self;
+ return raw_dest;
+}
+
godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self) {
godot_vector3 raw_dest;
const Variant *self = (const Variant *)p_self;
@@ -295,6 +369,14 @@ godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self) {
return raw_dest;
}
+godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self) {
+ godot_vector3i raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ *dest = *self;
+ return raw_dest;
+}
+
godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self) {
godot_transform2d raw_dest;
const Variant *self = (const Variant *)p_self;
@@ -367,6 +449,22 @@ godot_rid GDAPI godot_variant_as_rid(const godot_variant *p_self) {
return raw_dest;
}
+godot_callable GDAPI godot_variant_as_callable(const godot_variant *p_self) {
+ godot_callable raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ Callable *dest = (Callable *)&raw_dest;
+ *dest = *self;
+ return raw_dest;
+}
+
+godot_signal GDAPI godot_variant_as_signal(const godot_variant *p_self) {
+ godot_signal raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ Signal *dest = (Signal *)&raw_dest;
+ *dest = *self;
+ return raw_dest;
+}
+
godot_object GDAPI *godot_variant_as_object(const godot_variant *p_self) {
const Variant *self = (const Variant *)p_self;
Object *dest;
@@ -399,8 +497,8 @@ godot_packed_byte_array GDAPI godot_variant_as_packed_byte_array(const godot_var
return raw_dest;
}
-godot_packed_int_array GDAPI godot_variant_as_packed_int_array(const godot_variant *p_self) {
- godot_packed_int_array raw_dest;
+godot_packed_int32_array GDAPI godot_variant_as_packed_int32_array(const godot_variant *p_self) {
+ godot_packed_int32_array raw_dest;
const Variant *self = (const Variant *)p_self;
PackedInt32Array *dest = (PackedInt32Array *)&raw_dest;
memnew_placement(dest, PackedInt32Array(self->operator PackedInt32Array())); // operator = is overloaded by PackedInt32Array
@@ -408,8 +506,17 @@ godot_packed_int_array GDAPI godot_variant_as_packed_int_array(const godot_varia
return raw_dest;
}
-godot_packed_real_array GDAPI godot_variant_as_packed_real_array(const godot_variant *p_self) {
- godot_packed_real_array raw_dest;
+godot_packed_int64_array GDAPI godot_variant_as_packed_int64_array(const godot_variant *p_self) {
+ godot_packed_int64_array raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ PackedInt64Array *dest = (PackedInt64Array *)&raw_dest;
+ memnew_placement(dest, PackedInt64Array(self->operator PackedInt64Array())); // operator = is overloaded by PackedInt64Array
+ *dest = *self;
+ return raw_dest;
+}
+
+godot_packed_float32_array GDAPI godot_variant_as_packed_float32_array(const godot_variant *p_self) {
+ godot_packed_float32_array raw_dest;
const Variant *self = (const Variant *)p_self;
PackedFloat32Array *dest = (PackedFloat32Array *)&raw_dest;
memnew_placement(dest, PackedFloat32Array(self->operator PackedFloat32Array())); // operator = is overloaded by PackedFloat32Array
@@ -417,6 +524,15 @@ godot_packed_real_array GDAPI godot_variant_as_packed_real_array(const godot_var
return raw_dest;
}
+godot_packed_float64_array GDAPI godot_variant_as_packed_float64_array(const godot_variant *p_self) {
+ godot_packed_float64_array raw_dest;
+ const Variant *self = (const Variant *)p_self;
+ PackedFloat64Array *dest = (PackedFloat64Array *)&raw_dest;
+ memnew_placement(dest, PackedFloat64Array(self->operator PackedFloat64Array())); // operator = is overloaded by PackedFloat64Array
+ *dest = *self;
+ return raw_dest;
+}
+
godot_packed_string_array GDAPI godot_variant_as_packed_string_array(const godot_variant *p_self) {
godot_packed_string_array raw_dest;
const Variant *self = (const Variant *)p_self;
@@ -460,7 +576,9 @@ godot_variant GDAPI godot_variant_call(godot_variant *p_self, const godot_string
godot_variant raw_dest;
Variant *dest = (Variant *)&raw_dest;
Callable::CallError error;
- memnew_placement_custom(dest, Variant, Variant(self->call(*method, args, p_argcount, error)));
+ Variant ret;
+ self->call(*method, args, p_argcount, ret, error);
+ memnew_placement_custom(dest, Variant, Variant(ret));
if (r_error) {
r_error->error = (godot_variant_call_error_error)error.error;
r_error->argument = error.argument;
@@ -487,6 +605,11 @@ godot_bool GDAPI godot_variant_operator_less(const godot_variant *p_self, const
return self->operator<(*other);
}
+uint32_t GDAPI godot_variant_hash(const godot_variant *p_self) {
+ const Variant *self = (const Variant *)p_self;
+ return self->hash();
+}
+
godot_bool GDAPI godot_variant_hash_compare(const godot_variant *p_self, const godot_variant *p_other) {
const Variant *self = (const Variant *)p_self;
const Variant *other = (const Variant *)p_other;
diff --git a/modules/gdnative/gdnative/vector2.cpp b/modules/gdnative/gdnative/vector2.cpp
index dc273e7951..6f42935228 100644
--- a/modules/gdnative/gdnative/vector2.cpp
+++ b/modules/gdnative/gdnative/vector2.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,14 +31,18 @@
#include "gdnative/vector2.h"
#include "core/math/vector2.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
-void GDAPI godot_vector2_new(godot_vector2 *r_dest, const godot_real p_x, const godot_real p_y) {
+static_assert(sizeof(godot_vector2) == sizeof(Vector2), "Vector2 size mismatch");
+static_assert(sizeof(godot_vector2i) == sizeof(Vector2i), "Vector2i size mismatch");
+
+// Vector2
+void GDAPI godot_vector2_new(godot_vector2 *r_dest, const godot_real p_x, const godot_real p_y) {
Vector2 *dest = (Vector2 *)r_dest;
*dest = Vector2(p_x, p_y);
}
@@ -50,6 +54,13 @@ godot_string GDAPI godot_vector2_as_string(const godot_vector2 *p_self) {
return ret;
}
+godot_vector2i GDAPI godot_vector2_as_vector2i(const godot_vector2 *p_self) {
+ godot_vector2i dest;
+ const Vector2 *self = (const Vector2 *)p_self;
+ *((Vector2i *)&dest) = Vector2i(*self);
+ return dest;
+}
+
godot_vector2 GDAPI godot_vector2_normalized(const godot_vector2 *p_self) {
godot_vector2 dest;
const Vector2 *self = (const Vector2 *)p_self;
@@ -143,10 +154,10 @@ godot_vector2 GDAPI godot_vector2_rotated(const godot_vector2 *p_self, const god
return dest;
}
-godot_vector2 GDAPI godot_vector2_tangent(const godot_vector2 *p_self) {
+godot_vector2 GDAPI godot_vector2_orthogonal(const godot_vector2 *p_self) {
godot_vector2 dest;
const Vector2 *self = (const Vector2 *)p_self;
- *((Vector2 *)&dest) = self->tangent();
+ *((Vector2 *)&dest) = self->orthogonal();
return dest;
}
@@ -157,6 +168,13 @@ godot_vector2 GDAPI godot_vector2_floor(const godot_vector2 *p_self) {
return dest;
}
+godot_vector2 GDAPI godot_vector2_sign(const godot_vector2 *p_self) {
+ godot_vector2 dest;
+ const Vector2 *self = (const Vector2 *)p_self;
+ *((Vector2 *)&dest) = self->sign();
+ return dest;
+}
+
godot_vector2 GDAPI godot_vector2_snapped(const godot_vector2 *p_self, const godot_vector2 *p_by) {
godot_vector2 dest;
const Vector2 *self = (const Vector2 *)p_self;
@@ -307,6 +325,138 @@ godot_real GDAPI godot_vector2_get_y(const godot_vector2 *p_self) {
return self->y;
}
+// Vector2i
+
+void GDAPI godot_vector2i_new(godot_vector2i *r_dest, const godot_int p_x, const godot_int p_y) {
+ Vector2i *dest = (Vector2i *)r_dest;
+ *dest = Vector2i(p_x, p_y);
+}
+
+godot_string GDAPI godot_vector2i_as_string(const godot_vector2i *p_self) {
+ godot_string ret;
+ const Vector2i *self = (const Vector2i *)p_self;
+ memnew_placement(&ret, String(*self));
+ return ret;
+}
+
+godot_vector2 GDAPI godot_vector2i_as_vector2(const godot_vector2i *p_self) {
+ godot_vector2 dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *((Vector2 *)&dest) = Vector2(*self);
+ return dest;
+}
+
+godot_real GDAPI godot_vector2i_aspect(const godot_vector2i *p_self) {
+ const Vector2i *self = (const Vector2i *)p_self;
+ return self->aspect();
+}
+
+godot_vector2i GDAPI godot_vector2i_abs(const godot_vector2i *p_self) {
+ godot_vector2i dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *((Vector2i *)&dest) = self->abs();
+ return dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_sign(const godot_vector2i *p_self) {
+ godot_vector2i dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *((Vector2i *)&dest) = self->sign();
+ return dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_add(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ *dest = *self + *b;
+ return raw_dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_subtract(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ *dest = *self - *b;
+ return raw_dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_multiply_vector(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ *dest = *self * *b;
+ return raw_dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_multiply_scalar(const godot_vector2i *p_self, const godot_int p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *dest = *self * p_b;
+ return raw_dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_divide_vector(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ *dest = *self / *b;
+ return raw_dest;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_divide_scalar(const godot_vector2i *p_self, const godot_int p_b) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *dest = *self / p_b;
+ return raw_dest;
+}
+
+godot_bool GDAPI godot_vector2i_operator_equal(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ return *self == *b;
+}
+
+godot_bool GDAPI godot_vector2i_operator_less(const godot_vector2i *p_self, const godot_vector2i *p_b) {
+ const Vector2i *self = (const Vector2i *)p_self;
+ const Vector2i *b = (const Vector2i *)p_b;
+ return *self < *b;
+}
+
+godot_vector2i GDAPI godot_vector2i_operator_neg(const godot_vector2i *p_self) {
+ godot_vector2i raw_dest;
+ Vector2i *dest = (Vector2i *)&raw_dest;
+ const Vector2i *self = (const Vector2i *)p_self;
+ *dest = -(*self);
+ return raw_dest;
+}
+
+void GDAPI godot_vector2i_set_x(godot_vector2i *p_self, const godot_int p_x) {
+ Vector2i *self = (Vector2i *)p_self;
+ self->x = p_x;
+}
+
+void GDAPI godot_vector2i_set_y(godot_vector2i *p_self, const godot_int p_y) {
+ Vector2i *self = (Vector2i *)p_self;
+ self->y = p_y;
+}
+
+godot_int GDAPI godot_vector2i_get_x(const godot_vector2i *p_self) {
+ const Vector2i *self = (const Vector2i *)p_self;
+ return self->x;
+}
+
+godot_int GDAPI godot_vector2i_get_y(const godot_vector2i *p_self) {
+ const Vector2i *self = (const Vector2i *)p_self;
+ return self->y;
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/gdnative/vector3.cpp b/modules/gdnative/gdnative/vector3.cpp
index bb27ad5a00..75aeb59c87 100644
--- a/modules/gdnative/gdnative/vector3.cpp
+++ b/modules/gdnative/gdnative/vector3.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,15 +30,19 @@
#include "gdnative/vector3.h"
-#include "core/variant.h"
-#include "core/vector.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
#ifdef __cplusplus
extern "C" {
#endif
-void GDAPI godot_vector3_new(godot_vector3 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z) {
+static_assert(sizeof(godot_vector3) == sizeof(Vector3), "Vector3 size mismatch");
+static_assert(sizeof(godot_vector3i) == sizeof(Vector3i), "Vector3i size mismatch");
+
+// Vector3
+void GDAPI godot_vector3_new(godot_vector3 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z) {
Vector3 *dest = (Vector3 *)r_dest;
*dest = Vector3(p_x, p_y, p_z);
}
@@ -50,6 +54,13 @@ godot_string GDAPI godot_vector3_as_string(const godot_vector3 *p_self) {
return ret;
}
+godot_vector3i GDAPI godot_vector3_as_vector3i(const godot_vector3 *p_self) {
+ godot_vector3i dest;
+ const Vector3 *self = (const Vector3 *)p_self;
+ *((Vector3i *)&dest) = Vector3i(*self);
+ return dest;
+}
+
godot_int GDAPI godot_vector3_min_axis(const godot_vector3 *p_self) {
const Vector3 *self = (const Vector3 *)p_self;
return self->min_axis();
@@ -168,6 +179,13 @@ godot_vector3 GDAPI godot_vector3_abs(const godot_vector3 *p_self) {
return dest;
}
+godot_vector3 GDAPI godot_vector3_sign(const godot_vector3 *p_self) {
+ godot_vector3 dest;
+ const Vector3 *self = (const Vector3 *)p_self;
+ *((Vector3 *)&dest) = self->sign();
+ return dest;
+}
+
godot_vector3 GDAPI godot_vector3_floor(const godot_vector3 *p_self) {
godot_vector3 dest;
const Vector3 *self = (const Vector3 *)p_self;
@@ -314,6 +332,133 @@ godot_real GDAPI godot_vector3_get_axis(const godot_vector3 *p_self, const godot
return self->get_axis(p_axis);
}
+// Vector3i
+
+void GDAPI godot_vector3i_new(godot_vector3i *r_dest, const godot_int p_x, const godot_int p_y, const godot_int p_z) {
+ Vector3i *dest = (Vector3i *)r_dest;
+ *dest = Vector3i(p_x, p_y, p_z);
+}
+
+godot_string GDAPI godot_vector3i_as_string(const godot_vector3i *p_self) {
+ godot_string ret;
+ const Vector3i *self = (const Vector3i *)p_self;
+ memnew_placement(&ret, String(*self));
+ return ret;
+}
+
+godot_vector3 GDAPI godot_vector3i_as_vector3(const godot_vector3i *p_self) {
+ godot_vector3 dest;
+ const Vector3i *self = (const Vector3i *)p_self;
+ *((Vector3 *)&dest) = Vector3(*self);
+ return dest;
+}
+
+godot_int GDAPI godot_vector3i_min_axis(const godot_vector3i *p_self) {
+ const Vector3i *self = (const Vector3i *)p_self;
+ return self->min_axis();
+}
+
+godot_int GDAPI godot_vector3i_max_axis(const godot_vector3i *p_self) {
+ const Vector3i *self = (const Vector3i *)p_self;
+ return self->max_axis();
+}
+
+godot_vector3i GDAPI godot_vector3i_abs(const godot_vector3i *p_self) {
+ godot_vector3i dest;
+ const Vector3i *self = (const Vector3i *)p_self;
+ *((Vector3i *)&dest) = self->abs();
+ return dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_sign(const godot_vector3i *p_self) {
+ godot_vector3i dest;
+ const Vector3i *self = (const Vector3i *)p_self;
+ *((Vector3i *)&dest) = self->sign();
+ return dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_add(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ *dest = *self + *b;
+ return raw_dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_subtract(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ *dest = *self - *b;
+ return raw_dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_multiply_vector(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ *dest = *self * *b;
+ return raw_dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_multiply_scalar(const godot_vector3i *p_self, const godot_int p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ *dest = *self * p_b;
+ return raw_dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_divide_vector(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ *dest = *self / *b;
+ return raw_dest;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_divide_scalar(const godot_vector3i *p_self, const godot_int p_b) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ Vector3i *self = (Vector3i *)p_self;
+ *dest = *self / p_b;
+ return raw_dest;
+}
+
+godot_bool GDAPI godot_vector3i_operator_equal(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ return *self == *b;
+}
+
+godot_bool GDAPI godot_vector3i_operator_less(const godot_vector3i *p_self, const godot_vector3i *p_b) {
+ Vector3i *self = (Vector3i *)p_self;
+ const Vector3i *b = (const Vector3i *)p_b;
+ return *self < *b;
+}
+
+godot_vector3i GDAPI godot_vector3i_operator_neg(const godot_vector3i *p_self) {
+ godot_vector3i raw_dest;
+ Vector3i *dest = (Vector3i *)&raw_dest;
+ const Vector3i *self = (const Vector3i *)p_self;
+ *dest = -(*self);
+ return raw_dest;
+}
+
+void GDAPI godot_vector3i_set_axis(godot_vector3i *p_self, const godot_vector3_axis p_axis, const godot_int p_val) {
+ Vector3i *self = (Vector3i *)p_self;
+ self->set_axis(p_axis, p_val);
+}
+
+godot_int GDAPI godot_vector3i_get_axis(const godot_vector3i *p_self, const godot_vector3_axis p_axis) {
+ const Vector3i *self = (const Vector3i *)p_self;
+ return self->get_axis(p_axis);
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json
index d5ab62dc61..a29a0808ca 100644
--- a/modules/gdnative/gdnative_api.json
+++ b/modules/gdnative/gdnative_api.json
@@ -2,1130 +2,595 @@
"core": {
"type": "CORE",
"version": {
- "major": 1,
+ "major": 4,
"minor": 0
},
- "next": {
- "type": "CORE",
- "version": {
- "major": 1,
- "minor": 1
- },
- "next": {
- "type": "CORE",
- "version": {
- "major": 1,
- "minor": 2
- },
- "next": null,
- "api": [
- {
- "name": "godot_dictionary_duplicate",
- "return_type": "godot_dictionary",
- "arguments": [
- ["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"]
- ]
- },
- {
- "name": "godot_string_count",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"],
- ["godot_int", "p_to"]
- ]
- },
- {
- "name": "godot_string_countn",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"],
- ["godot_int", "p_to"]
- ]
- },
- {
- "name": "godot_vector3_direction_to",
- "return_type": "godot_vector3",
- "arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_to"]
- ]
- },
- {
- "name": "godot_vector2_direction_to",
- "return_type": "godot_vector2",
- "arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
- ]
- },
- {
- "name": "godot_array_slice",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_int", "p_begin"],
- ["const godot_int", "p_end"],
- ["const godot_int", "p_step"],
- ["const godot_bool", "p_deep"]
- ]
- },
- {
- "name": "godot_packed_byte_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_byte_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_int_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_int_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_real_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_real_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_string_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_string_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_vector2_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_vector2_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_vector3_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_vector3_array *", "p_self"]
- ]
- },
- {
- "name": "godot_packed_color_array_empty",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_packed_color_array *", "p_self"]
- ]
- },
- {
- "name": "godot_get_class_tag",
- "return_type": "void *",
- "arguments": [
- ["const godot_string_name *", "p_class"]
- ]
- },
- {
- "name": "godot_object_cast_to",
- "return_type": "godot_object *",
- "arguments": [
- ["const godot_object *", "p_object"],
- ["void *", "p_class_tag"]
- ]
- },
- {
- "name": "godot_instance_from_id",
- "return_type": "godot_object *",
- "arguments": [
- ["godot_int", "p_instance_id"]
- ]
- }
- ]
- },
- "api": [
- {
- "name": "godot_color_to_abgr32",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_to_abgr64",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_to_argb64",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_to_rgba64",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_darkened",
- "return_type": "godot_color",
- "arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_real", "p_amount"]
- ]
- },
- {
- "name": "godot_color_from_hsv",
- "return_type": "godot_color",
- "arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_real", "p_h"],
- ["const godot_real", "p_s"],
- ["const godot_real", "p_v"],
- ["const godot_real", "p_a"]
- ]
- },
- {
- "name": "godot_color_lightened",
- "return_type": "godot_color",
- "arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_real", "p_amount"]
- ]
- },
- {
- "name": "godot_array_duplicate",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_bool", "p_deep"]
- ]
- },
- {
- "name": "godot_array_max",
- "return_type": "godot_variant",
- "arguments": [
- ["const godot_array *", "p_self"]
- ]
- },
- {
- "name": "godot_array_min",
- "return_type": "godot_variant",
- "arguments": [
- ["const godot_array *", "p_self"]
- ]
- },
- {
- "name": "godot_array_shuffle",
- "return_type": "void",
- "arguments": [
- ["godot_array *", "p_self"]
- ]
- },
- {
- "name": "godot_basis_slerp",
- "return_type": "godot_basis",
- "arguments": [
- ["const godot_basis *", "p_self"],
- ["const godot_basis *", "p_b"],
- ["const godot_real", "p_t"]
- ]
- },
- {
- "name": "godot_dictionary_get_with_default",
- "return_type": "godot_variant",
- "arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"],
- ["const godot_variant *", "p_default"]
- ]
- },
- {
- "name": "godot_dictionary_erase_with_return",
- "return_type": "bool",
- "arguments": [
- ["godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
- ]
- },
- {
- "name": "godot_node_path_get_as_property_path",
- "return_type": "godot_node_path",
- "arguments": [
- ["const godot_node_path *", "p_self"]
- ]
- },
- {
- "name": "godot_quat_set_axis_angle",
- "return_type": "void",
- "arguments": [
- ["godot_quat *", "p_self"],
- ["const godot_vector3 *", "p_axis"],
- ["const godot_real", "p_angle"]
- ]
- },
- {
- "name": "godot_rect2_grow_individual",
- "return_type": "godot_rect2",
- "arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_real", "p_left"],
- ["const godot_real", "p_top"],
- ["const godot_real", "p_right"],
- ["const godot_real", "p_bottom"]
- ]
- },
- {
- "name": "godot_rect2_grow_margin",
- "return_type": "godot_rect2",
- "arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_int", "p_margin"],
- ["const godot_real", "p_by"]
- ]
- },
- {
- "name": "godot_rect2_abs",
- "return_type": "godot_rect2",
- "arguments": [
- ["const godot_rect2 *", "p_self"]
- ]
- },
- {
- "name": "godot_string_dedent",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"]
- ]
- },
- {
- "name": "godot_string_trim_prefix",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_prefix"]
- ]
- },
- {
- "name": "godot_string_trim_suffix",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_suffix"]
- ]
- },
- {
- "name": "godot_string_rstrip",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_chars"]
- ]
- },
- {
- "name": "godot_string_rsplit",
- "return_type": "godot_packed_string_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_divisor"],
- ["const godot_bool", "p_allow_empty"],
- ["const godot_int", "p_maxsplit"]
- ]
- },
- {
- "name": "godot_basis_get_quat",
- "return_type": "godot_quat",
- "arguments": [
- ["const godot_basis *", "p_self"]
- ]
- },
- {
- "name": "godot_basis_set_quat",
- "return_type": "void",
- "arguments": [
- ["godot_basis *", "p_self"],
- ["const godot_quat *", "p_quat"]
- ]
- },
- {
- "name": "godot_basis_set_axis_angle_scale",
- "return_type": "void",
- "arguments": [
- ["godot_basis *", "p_self"],
- ["const godot_vector3 *", "p_axis"],
- ["godot_real", "p_phi"],
- ["const godot_vector3 *", "p_scale"]
- ]
- },
- {
- "name": "godot_basis_set_euler_scale",
- "return_type": "void",
- "arguments": [
- ["godot_basis *", "p_self"],
- ["const godot_vector3 *", "p_euler"],
- ["const godot_vector3 *", "p_scale"]
- ]
- },
- {
- "name": "godot_basis_set_quat_scale",
- "return_type": "void",
- "arguments": [
- ["godot_basis *", "p_self"],
- ["const godot_quat *", "p_quat"],
- ["const godot_vector3 *", "p_scale"]
- ]
- },
- {
- "name": "godot_quat_new_with_basis",
- "return_type": "void",
- "arguments": [
- ["godot_quat *", "r_dest"],
- ["const godot_basis *", "p_basis"]
- ]
- },
- {
- "name": "godot_quat_new_with_euler",
- "return_type": "void",
- "arguments": [
- ["godot_quat *", "r_dest"],
- ["const godot_vector3 *", "p_euler"]
- ]
- },
- {
- "name": "godot_transform_new_with_quat",
- "return_type": "void",
- "arguments": [
- ["godot_transform *", "r_dest"],
- ["const godot_quat *", "p_quat"]
- ]
- },
- {
- "name": "godot_variant_get_operator_name",
- "return_type": "godot_string",
- "arguments": [
- ["godot_variant_operator", "p_op"]
- ]
- },
- {
- "name": "godot_variant_evaluate",
- "return_type": "void",
- "arguments": [
- ["godot_variant_operator", "p_op"],
- ["const godot_variant *", "p_a"],
- ["const godot_variant *", "p_b"],
- ["godot_variant *", "r_ret"],
- ["godot_bool *", "r_valid"]
- ]
- }
- ]
- },
+ "next": null,
"api": [
{
- "name": "godot_color_new_rgba",
- "return_type": "void",
- "arguments": [
- ["godot_color *", "r_dest"],
- ["const godot_real", "p_r"],
- ["const godot_real", "p_g"],
- ["const godot_real", "p_b"],
- ["const godot_real", "p_a"]
- ]
- },
- {
- "name": "godot_color_new_rgb",
- "return_type": "void",
- "arguments": [
- ["godot_color *", "r_dest"],
- ["const godot_real", "p_r"],
- ["const godot_real", "p_g"],
- ["const godot_real", "p_b"]
- ]
- },
- {
- "name": "godot_color_get_r",
- "return_type": "godot_real",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_set_r",
- "return_type": "void",
- "arguments": [
- ["godot_color *", "p_self"],
- ["const godot_real", "r"]
- ]
- },
- {
- "name": "godot_color_get_g",
- "return_type": "godot_real",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_set_g",
+ "name": "godot_aabb_new",
"return_type": "void",
"arguments": [
- ["godot_color *", "p_self"],
- ["const godot_real", "g"]
+ ["godot_aabb *", "r_dest"],
+ ["const godot_vector3 *", "p_pos"],
+ ["const godot_vector3 *", "p_size"]
]
},
{
- "name": "godot_color_get_b",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_position",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_set_b",
+ "name": "godot_aabb_set_position",
"return_type": "void",
"arguments": [
- ["godot_color *", "p_self"],
- ["const godot_real", "b"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_v"]
]
},
{
- "name": "godot_color_get_a",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_size",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_set_a",
+ "name": "godot_aabb_set_size",
"return_type": "void",
"arguments": [
- ["godot_color *", "p_self"],
- ["const godot_real", "a"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_v"]
]
},
{
- "name": "godot_color_get_h",
- "return_type": "godot_real",
+ "name": "godot_aabb_as_string",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_get_s",
- "return_type": "godot_real",
+ "name": "godot_aabb_abs",
+ "return_type": "godot_aabb",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_get_v",
+ "name": "godot_aabb_get_area",
"return_type": "godot_real",
"arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_as_string",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_color *", "p_self"]
- ]
- },
- {
- "name": "godot_color_to_rgba32",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_to_argb32",
- "return_type": "godot_int",
+ "name": "godot_aabb_has_no_area",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_inverted",
- "return_type": "godot_color",
+ "name": "godot_aabb_has_no_surface",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_color_contrasted",
- "return_type": "godot_color",
+ "name": "godot_aabb_intersects",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_aabb *", "p_with"]
]
},
{
- "name": "godot_color_lerp",
- "return_type": "godot_color",
+ "name": "godot_aabb_encloses",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_color *", "p_b"],
- ["const godot_real", "p_t"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_aabb *", "p_with"]
]
},
{
- "name": "godot_color_blend",
- "return_type": "godot_color",
+ "name": "godot_aabb_merge",
+ "return_type": "godot_aabb",
"arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_color *", "p_over"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_aabb *", "p_with"]
]
},
{
- "name": "godot_color_to_html",
- "return_type": "godot_string",
+ "name": "godot_aabb_intersection",
+ "return_type": "godot_aabb",
"arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_bool", "p_with_alpha"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_aabb *", "p_with"]
]
},
{
- "name": "godot_color_operator_equal",
+ "name": "godot_aabb_intersects_plane",
"return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_color *", "p_b"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_plane *", "p_plane"]
]
},
{
- "name": "godot_color_operator_less",
+ "name": "godot_aabb_intersects_segment",
"return_type": "godot_bool",
"arguments": [
- ["const godot_color *", "p_self"],
- ["const godot_color *", "p_b"]
- ]
- },
- {
- "name": "godot_vector2_new",
- "return_type": "void",
- "arguments": [
- ["godot_vector2 *", "r_dest"],
- ["const godot_real", "p_x"],
- ["const godot_real", "p_y"]
- ]
- },
- {
- "name": "godot_vector2_as_string",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_vector2 *", "p_self"]
- ]
- },
- {
- "name": "godot_vector2_normalized",
- "return_type": "godot_vector2",
- "arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_from"],
+ ["const godot_vector3 *", "p_to"]
]
},
{
- "name": "godot_vector2_length",
- "return_type": "godot_real",
+ "name": "godot_aabb_has_point",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_point"]
]
},
{
- "name": "godot_vector2_angle",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_support",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_dir"]
]
},
{
- "name": "godot_vector2_length_squared",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_longest_axis",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_is_normalized",
- "return_type": "godot_bool",
+ "name": "godot_aabb_get_longest_axis_index",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_distance_to",
+ "name": "godot_aabb_get_longest_axis_size",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_distance_squared_to",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_shortest_axis",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_angle_to",
- "return_type": "godot_real",
+ "name": "godot_aabb_get_shortest_axis_index",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_angle_to_point",
+ "name": "godot_aabb_get_shortest_axis_size",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
- ]
- },
- {
- "name": "godot_vector2_lerp",
- "return_type": "godot_vector2",
- "arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"],
- ["const godot_real", "p_t"]
- ]
- },
- {
- "name": "godot_vector2_cubic_interpolate",
- "return_type": "godot_vector2",
- "arguments": [
- ["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"]
+ ["const godot_aabb *", "p_self"]
]
},
{
- "name": "godot_vector2_rotated",
- "return_type": "godot_vector2",
+ "name": "godot_aabb_expand",
+ "return_type": "godot_aabb",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_real", "p_phi"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_vector3 *", "p_to_point"]
]
},
{
- "name": "godot_vector2_tangent",
- "return_type": "godot_vector2",
+ "name": "godot_aabb_grow",
+ "return_type": "godot_aabb",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_real", "p_by"]
]
},
{
- "name": "godot_vector2_floor",
- "return_type": "godot_vector2",
+ "name": "godot_aabb_get_endpoint",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_vector2_snapped",
- "return_type": "godot_vector2",
+ "name": "godot_aabb_operator_equal",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_by"]
+ ["const godot_aabb *", "p_self"],
+ ["const godot_aabb *", "p_b"]
]
},
{
- "name": "godot_vector2_aspect",
- "return_type": "godot_real",
+ "name": "godot_array_new",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["godot_array *", "r_dest"]
]
},
{
- "name": "godot_vector2_dot",
- "return_type": "godot_real",
+ "name": "godot_array_new_copy",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_with"]
+ ["godot_array *", "r_dest"],
+ ["const godot_array *", "p_src"]
]
},
{
- "name": "godot_vector2_slide",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_color_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_n"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_color_array *", "p_pca"]
]
},
{
- "name": "godot_vector2_bounce",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_vector3_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_n"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_vector3_array *", "p_pv3a"]
]
},
{
- "name": "godot_vector2_reflect",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_vector2_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_n"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_vector2_array *", "p_pv2a"]
]
},
{
- "name": "godot_vector2_abs",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_vector2i_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_vector2i_array *", "p_pv2a"]
]
},
{
- "name": "godot_vector2_clamped",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_string_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_real", "p_length"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_string_array *", "p_psa"]
]
},
{
- "name": "godot_vector2_operator_add",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_float32_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_float32_array *", "p_pra"]
]
},
{
- "name": "godot_vector2_operator_subtract",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_float64_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_float64_array *", "p_pra"]
]
},
{
- "name": "godot_vector2_operator_multiply_vector",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_int32_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_int32_array *", "p_pia"]
]
},
{
- "name": "godot_vector2_operator_multiply_scalar",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_int64_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_real", "p_b"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_int64_array *", "p_pia"]
]
},
{
- "name": "godot_vector2_operator_divide_vector",
- "return_type": "godot_vector2",
+ "name": "godot_array_new_packed_byte_array",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["godot_array *", "r_dest"],
+ ["const godot_packed_byte_array *", "p_pba"]
]
},
{
- "name": "godot_vector2_operator_divide_scalar",
- "return_type": "godot_vector2",
+ "name": "godot_array_set",
+ "return_type": "void",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_real", "p_b"]
+ ["godot_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_vector2_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_array_get",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["const godot_array *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_vector2_operator_less",
- "return_type": "godot_bool",
+ "name": "godot_array_operator_index",
+ "return_type": "godot_variant *",
"arguments": [
- ["const godot_vector2 *", "p_self"],
- ["const godot_vector2 *", "p_b"]
+ ["godot_array *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_vector2_operator_neg",
- "return_type": "godot_vector2",
+ "name": "godot_array_operator_index_const",
+ "return_type": "const godot_variant *",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_array *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_vector2_set_x",
+ "name": "godot_array_append",
"return_type": "void",
"arguments": [
- ["godot_vector2 *", "p_self"],
- ["const godot_real", "p_x"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_vector2_set_y",
+ "name": "godot_array_clear",
"return_type": "void",
"arguments": [
- ["godot_vector2 *", "p_self"],
- ["const godot_real", "p_y"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_vector2_get_x",
- "return_type": "godot_real",
+ "name": "godot_array_count",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_vector2_get_y",
- "return_type": "godot_real",
+ "name": "godot_array_duplicate",
+ "return_type": "godot_array",
"arguments": [
- ["const godot_vector2 *", "p_self"]
+ ["const godot_array *", "p_self"],
+ ["const godot_bool", "p_deep"]
]
},
{
- "name": "godot_quat_new",
- "return_type": "void",
+ "name": "godot_array_is_empty",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_quat *", "r_dest"],
- ["const godot_real", "p_x"],
- ["const godot_real", "p_y"],
- ["const godot_real", "p_z"],
- ["const godot_real", "p_w"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_new_with_axis_angle",
+ "name": "godot_array_erase",
"return_type": "void",
"arguments": [
- ["godot_quat *", "r_dest"],
- ["const godot_vector3 *", "p_axis"],
- ["const godot_real", "p_angle"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_quat_get_x",
- "return_type": "godot_real",
+ "name": "godot_array_front",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_set_x",
- "return_type": "void",
+ "name": "godot_array_back",
+ "return_type": "godot_variant",
"arguments": [
- ["godot_quat *", "p_self"],
- ["const godot_real", "val"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_get_y",
- "return_type": "godot_real",
+ "name": "godot_array_find",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["const godot_array *", "p_self"],
+ ["const godot_variant *", "p_what"],
+ ["const godot_int", "p_from"]
]
},
{
- "name": "godot_quat_set_y",
- "return_type": "void",
+ "name": "godot_array_find_last",
+ "return_type": "godot_int",
"arguments": [
- ["godot_quat *", "p_self"],
- ["const godot_real", "val"]
+ ["const godot_array *", "p_self"],
+ ["const godot_variant *", "p_what"]
]
},
{
- "name": "godot_quat_get_z",
- "return_type": "godot_real",
+ "name": "godot_array_has",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["const godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_quat_set_z",
- "return_type": "void",
+ "name": "godot_array_hash",
+ "return_type": "godot_int",
"arguments": [
- ["godot_quat *", "p_self"],
- ["const godot_real", "val"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_get_w",
- "return_type": "godot_real",
+ "name": "godot_array_insert",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"],
+ ["const godot_int", "p_pos"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_quat_set_w",
+ "name": "godot_array_invert",
"return_type": "void",
"arguments": [
- ["godot_quat *", "p_self"],
- ["const godot_real", "val"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_as_string",
- "return_type": "godot_string",
+ "name": "godot_array_max",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_length",
- "return_type": "godot_real",
+ "name": "godot_array_min",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_length_squared",
- "return_type": "godot_real",
+ "name": "godot_array_pop_back",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_normalized",
- "return_type": "godot_quat",
+ "name": "godot_array_pop_front",
+ "return_type": "godot_variant",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_is_normalized",
- "return_type": "godot_bool",
+ "name": "godot_array_push_back",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_quat_inverse",
- "return_type": "godot_quat",
+ "name": "godot_array_push_front",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"]
]
},
{
- "name": "godot_quat_dot",
- "return_type": "godot_real",
+ "name": "godot_array_remove",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"]
+ ["godot_array *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_quat_xform",
- "return_type": "godot_vector3",
+ "name": "godot_array_resize",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_vector3 *", "p_v"]
+ ["godot_array *", "p_self"],
+ ["const godot_int", "p_size"]
]
},
{
- "name": "godot_quat_slerp",
- "return_type": "godot_quat",
+ "name": "godot_array_rfind",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"],
- ["const godot_real", "p_t"]
+ ["const godot_array *", "p_self"],
+ ["const godot_variant *", "p_what"],
+ ["const godot_int", "p_from"]
]
},
{
- "name": "godot_quat_slerpni",
- "return_type": "godot_quat",
+ "name": "godot_array_size",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"],
- ["const godot_real", "p_t"]
+ ["const godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_cubic_slerp",
- "return_type": "godot_quat",
+ "name": "godot_array_shuffle",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"],
- ["const godot_quat *", "p_pre_a"],
- ["const godot_quat *", "p_post_b"],
- ["const godot_real", "p_t"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_operator_multiply",
- "return_type": "godot_quat",
+ "name": "godot_array_slice",
+ "return_type": "godot_array",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_real", "p_b"]
+ ["const godot_array *", "p_self"],
+ ["const godot_int", "p_begin"],
+ ["const godot_int", "p_end"],
+ ["const godot_int", "p_step"],
+ ["const godot_bool", "p_deep"]
]
},
{
- "name": "godot_quat_operator_add",
- "return_type": "godot_quat",
+ "name": "godot_array_sort",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"]
+ ["godot_array *", "p_self"]
]
},
{
- "name": "godot_quat_operator_subtract",
- "return_type": "godot_quat",
+ "name": "godot_array_sort_custom",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"]
+ ["godot_array *", "p_self"],
+ ["godot_object *", "p_obj"],
+ ["const godot_string *", "p_func"]
]
},
{
- "name": "godot_quat_operator_divide",
- "return_type": "godot_quat",
+ "name": "godot_array_bsearch",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_real", "p_b"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"],
+ ["const godot_bool", "p_before"]
]
},
{
- "name": "godot_quat_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_array_bsearch_custom",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_quat *", "p_self"],
- ["const godot_quat *", "p_b"]
+ ["godot_array *", "p_self"],
+ ["const godot_variant *", "p_value"],
+ ["godot_object *", "p_obj"],
+ ["const godot_string *", "p_func"],
+ ["const godot_bool", "p_before"]
]
},
{
- "name": "godot_quat_operator_neg",
- "return_type": "godot_quat",
+ "name": "godot_array_destroy",
+ "return_type": "void",
"arguments": [
- ["const godot_quat *", "p_self"]
+ ["godot_array *", "p_self"]
]
},
{
@@ -1366,294 +831,796 @@
]
},
{
- "name": "godot_vector3_new",
+ "name": "godot_basis_slerp",
+ "return_type": "godot_basis",
+ "arguments": [
+ ["const godot_basis *", "p_self"],
+ ["const godot_basis *", "p_b"],
+ ["const godot_real", "p_t"]
+ ]
+ },
+ {
+ "name": "godot_basis_get_quat",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_basis *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_basis_set_quat",
"return_type": "void",
"arguments": [
- ["godot_vector3 *", "r_dest"],
- ["const godot_real", "p_x"],
- ["const godot_real", "p_y"],
- ["const godot_real", "p_z"]
+ ["godot_basis *", "p_self"],
+ ["const godot_quat *", "p_quat"]
]
},
{
- "name": "godot_vector3_as_string",
+ "name": "godot_basis_set_axis_angle_scale",
+ "return_type": "void",
+ "arguments": [
+ ["godot_basis *", "p_self"],
+ ["const godot_vector3 *", "p_axis"],
+ ["godot_real", "p_phi"],
+ ["const godot_vector3 *", "p_scale"]
+ ]
+ },
+ {
+ "name": "godot_basis_set_euler_scale",
+ "return_type": "void",
+ "arguments": [
+ ["godot_basis *", "p_self"],
+ ["const godot_vector3 *", "p_euler"],
+ ["const godot_vector3 *", "p_scale"]
+ ]
+ },
+ {
+ "name": "godot_basis_set_quat_scale",
+ "return_type": "void",
+ "arguments": [
+ ["godot_basis *", "p_self"],
+ ["const godot_quat *", "p_quat"],
+ ["const godot_vector3 *", "p_scale"]
+ ]
+ },
+ {
+ "name": "godot_callable_new_with_object",
+ "return_type": "void",
+ "arguments": [
+ ["godot_callable *", "r_dest"],
+ ["const godot_object *", "p_object"],
+ ["const godot_string_name *", "p_method"]
+ ]
+ },
+ {
+ "name": "godot_callable_new_with_object_id",
+ "return_type": "void",
+ "arguments": [
+ ["godot_callable *", "r_dest"],
+ ["uint64_t", "p_objectid"],
+ ["const godot_string_name *", "p_method"]
+ ]
+ },
+ {
+ "name": "godot_callable_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_callable *", "r_dest"],
+ ["const godot_callable *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_callable_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_call",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_callable *", "p_self"],
+ ["const godot_variant **", "p_arguments"],
+ ["godot_int", "p_argcount"],
+ ["godot_variant *", "r_return_value"]
+ ]
+ },
+ {
+ "name": "godot_callable_call_deferred",
+ "return_type": "void",
+ "arguments": [
+ ["const godot_callable *", "p_self"],
+ ["const godot_variant **", "p_arguments"],
+ ["godot_int", "p_argcount"]
+ ]
+ },
+ {
+ "name": "godot_callable_is_null",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_is_custom",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_is_standard",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_get_object",
+ "return_type": "godot_object *",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_get_object_id",
+ "return_type": "uint64_t",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_get_method",
+ "return_type": "godot_string_name",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_hash",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const godot_callable *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_callable_as_string",
"return_type": "godot_string",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_callable *", "p_self"]
]
},
{
- "name": "godot_vector3_min_axis",
+ "name": "godot_callable_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_callable *", "p_self"],
+ ["const godot_callable *", "p_other"]
+ ]
+ },
+ {
+ "name": "godot_callable_operator_less",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_callable *", "p_self"],
+ ["const godot_callable *", "p_other"]
+ ]
+ },
+ {
+ "name": "godot_signal_new_with_object",
+ "return_type": "void",
+ "arguments": [
+ ["godot_signal *", "r_dest"],
+ ["const godot_object *", "p_object"],
+ ["const godot_string_name *", "p_method"]
+ ]
+ },
+ {
+ "name": "godot_signal_new_with_object_id",
+ "return_type": "void",
+ "arguments": [
+ ["godot_signal *", "r_dest"],
+ ["uint64_t", "p_objectid"],
+ ["const godot_string_name *", "p_method"]
+ ]
+ },
+ {
+ "name": "godot_signal_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_signal *", "r_dest"],
+ ["const godot_signal *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_signal_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_signal *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_signal_emit",
"return_type": "godot_int",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_signal *", "p_self"],
+ ["const godot_variant **", "p_arguments"],
+ ["godot_int", "p_argcount"]
]
},
{
- "name": "godot_vector3_max_axis",
+ "name": "godot_signal_connect",
"return_type": "godot_int",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["godot_signal *", "p_self"],
+ ["const godot_callable *", "p_callable"],
+ ["const godot_array *", "p_binds"],
+ ["uint32_t", "p_flags"]
]
},
{
- "name": "godot_vector3_length",
- "return_type": "godot_real",
+ "name": "godot_signal_disconnect",
+ "return_type": "void",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["godot_signal *", "p_self"],
+ ["const godot_callable *", "p_callable"]
]
},
{
- "name": "godot_vector3_length_squared",
- "return_type": "godot_real",
+ "name": "godot_signal_is_null",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_is_normalized",
+ "name": "godot_signal_is_connected",
"return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_signal *", "p_self"],
+ ["const godot_callable *", "p_callable"]
]
},
{
- "name": "godot_vector3_normalized",
- "return_type": "godot_vector3",
+ "name": "godot_signal_get_connections",
+ "return_type": "godot_array",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_inverse",
- "return_type": "godot_vector3",
+ "name": "godot_signal_get_object",
+ "return_type": "godot_object *",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_snapped",
- "return_type": "godot_vector3",
+ "name": "godot_signal_get_object_id",
+ "return_type": "uint64_t",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_by"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_rotated",
- "return_type": "godot_vector3",
+ "name": "godot_signal_get_name",
+ "return_type": "godot_string_name",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_axis"],
- ["const godot_real", "p_phi"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_lerp",
- "return_type": "godot_vector3",
+ "name": "godot_signal_as_string",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"],
- ["const godot_real", "p_t"]
+ ["const godot_signal *", "p_self"]
]
},
{
- "name": "godot_vector3_cubic_interpolate",
- "return_type": "godot_vector3",
+ "name": "godot_signal_operator_equal",
+ "return_type": "godot_bool",
"arguments": [
- ["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"]
+ ["const godot_signal *", "p_self"],
+ ["const godot_signal *", "p_other"]
]
},
{
- "name": "godot_vector3_dot",
+ "name": "godot_signal_operator_less",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_signal *", "p_self"],
+ ["const godot_signal *", "p_other"]
+ ]
+ },
+ {
+ "name": "godot_color_new_rgba",
+ "return_type": "void",
+ "arguments": [
+ ["godot_color *", "r_dest"],
+ ["const godot_real", "p_r"],
+ ["const godot_real", "p_g"],
+ ["const godot_real", "p_b"],
+ ["const godot_real", "p_a"]
+ ]
+ },
+ {
+ "name": "godot_color_new_rgb",
+ "return_type": "void",
+ "arguments": [
+ ["godot_color *", "r_dest"],
+ ["const godot_real", "p_r"],
+ ["const godot_real", "p_g"],
+ ["const godot_real", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_color_get_r",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_cross",
- "return_type": "godot_vector3",
+ "name": "godot_color_set_r",
+ "return_type": "void",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["godot_color *", "p_self"],
+ ["const godot_real", "r"]
]
},
{
- "name": "godot_vector3_outer",
- "return_type": "godot_basis",
+ "name": "godot_color_get_g",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_to_diagonal_matrix",
- "return_type": "godot_basis",
+ "name": "godot_color_set_g",
+ "return_type": "void",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["godot_color *", "p_self"],
+ ["const godot_real", "g"]
]
},
{
- "name": "godot_vector3_abs",
- "return_type": "godot_vector3",
+ "name": "godot_color_get_b",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_floor",
- "return_type": "godot_vector3",
+ "name": "godot_color_set_b",
+ "return_type": "void",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["godot_color *", "p_self"],
+ ["const godot_real", "b"]
]
},
{
- "name": "godot_vector3_ceil",
- "return_type": "godot_vector3",
+ "name": "godot_color_get_a",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_distance_to",
+ "name": "godot_color_set_a",
+ "return_type": "void",
+ "arguments": [
+ ["godot_color *", "p_self"],
+ ["const godot_real", "a"]
+ ]
+ },
+ {
+ "name": "godot_color_get_h",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_distance_squared_to",
+ "name": "godot_color_get_s",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_angle_to",
+ "name": "godot_color_get_v",
"return_type": "godot_real",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_to"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_slide",
- "return_type": "godot_vector3",
+ "name": "godot_color_as_string",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_n"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_bounce",
- "return_type": "godot_vector3",
+ "name": "godot_color_to_rgba32",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_n"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_reflect",
- "return_type": "godot_vector3",
+ "name": "godot_color_to_argb32",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_n"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_operator_add",
- "return_type": "godot_vector3",
+ "name": "godot_color_inverted",
+ "return_type": "godot_color",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"]
]
},
{
- "name": "godot_vector3_operator_subtract",
- "return_type": "godot_vector3",
+ "name": "godot_color_lerp",
+ "return_type": "godot_color",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"],
+ ["const godot_color *", "p_b"],
+ ["const godot_real", "p_t"]
]
},
{
- "name": "godot_vector3_operator_multiply_vector",
- "return_type": "godot_vector3",
+ "name": "godot_color_blend",
+ "return_type": "godot_color",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"],
+ ["const godot_color *", "p_over"]
]
},
{
- "name": "godot_vector3_operator_multiply_scalar",
- "return_type": "godot_vector3",
+ "name": "godot_color_to_html",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_real", "p_b"]
+ ["const godot_color *", "p_self"],
+ ["const godot_bool", "p_with_alpha"]
]
},
{
- "name": "godot_vector3_operator_divide_vector",
- "return_type": "godot_vector3",
+ "name": "godot_color_operator_equal",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_color *", "p_self"],
+ ["const godot_color *", "p_b"]
]
},
{
- "name": "godot_vector3_operator_divide_scalar",
- "return_type": "godot_vector3",
+ "name": "godot_color_operator_less",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_real", "p_b"]
+ ["const godot_color *", "p_self"],
+ ["const godot_color *", "p_b"]
]
},
{
- "name": "godot_vector3_operator_equal",
+ "name": "godot_color_to_abgr32",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_color *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_color_to_abgr64",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_color *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_color_to_argb64",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_color *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_color_to_rgba64",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_color *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_color_darkened",
+ "return_type": "godot_color",
+ "arguments": [
+ ["const godot_color *", "p_self"],
+ ["const godot_real", "p_amount"]
+ ]
+ },
+ {
+ "name": "godot_color_from_hsv",
+ "return_type": "godot_color",
+ "arguments": [
+ ["const godot_color *", "p_self"],
+ ["const godot_real", "p_h"],
+ ["const godot_real", "p_s"],
+ ["const godot_real", "p_v"],
+ ["const godot_real", "p_a"]
+ ]
+ },
+ {
+ "name": "godot_color_lightened",
+ "return_type": "godot_color",
+ "arguments": [
+ ["const godot_color *", "p_self"],
+ ["const godot_real", "p_amount"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_dictionary *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_dictionary *", "r_dest"],
+ ["const godot_dictionary *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_size",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_is_empty",
"return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_dictionary *", "p_self"]
]
},
{
- "name": "godot_vector3_operator_less",
+ "name": "godot_dictionary_clear",
+ "return_type": "void",
+ "arguments": [
+ ["godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_has",
"return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3 *", "p_b"]
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
]
},
{
- "name": "godot_vector3_operator_neg",
- "return_type": "godot_vector3",
+ "name": "godot_dictionary_has_all",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_vector3 *", "p_self"]
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_array *", "p_keys"]
]
},
{
- "name": "godot_vector3_set_axis",
+ "name": "godot_dictionary_erase",
"return_type": "void",
"arguments": [
- ["godot_vector3 *", "p_self"],
- ["const godot_vector3_axis", "p_axis"],
- ["const godot_real", "p_val"]
+ ["godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
]
},
{
- "name": "godot_vector3_get_axis",
- "return_type": "godot_real",
+ "name": "godot_dictionary_hash",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_vector3 *", "p_self"],
- ["const godot_vector3_axis", "p_axis"]
+ ["const godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_keys",
+ "return_type": "godot_array",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_values",
+ "return_type": "godot_array",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_get",
+ "return_type": "godot_variant",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_set",
+ "return_type": "void",
+ "arguments": [
+ ["godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"],
+ ["const godot_variant *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_operator_index",
+ "return_type": "godot_variant *",
+ "arguments": [
+ ["godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_operator_index_const",
+ "return_type": "const godot_variant *",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_next",
+ "return_type": "godot_variant *",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_dictionary *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_to_json",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_duplicate",
+ "return_type": "godot_dictionary",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_bool", "p_deep"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_get_with_default",
+ "return_type": "godot_variant",
+ "arguments": [
+ ["const godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"],
+ ["const godot_variant *", "p_default"]
+ ]
+ },
+ {
+ "name": "godot_dictionary_erase_with_return",
+ "return_type": "bool",
+ "arguments": [
+ ["godot_dictionary *", "p_self"],
+ ["const godot_variant *", "p_key"]
+ ]
+ },
+ {
+ "name": "godot_node_path_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_node_path *", "r_dest"],
+ ["const godot_string *", "p_from"]
+ ]
+ },
+ {
+ "name": "godot_node_path_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_node_path *", "r_dest"],
+ ["const godot_node_path *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_node_path_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_as_string",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_is_absolute",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_name_count",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_name",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_node_path *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_subname_count",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_subname",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_node_path *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_concatenated_subnames",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_node_path_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_node_path *", "p_self"],
+ ["const godot_node_path *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_node_path_get_as_property_path",
+ "return_type": "godot_node_path",
+ "arguments": [
+ ["const godot_node_path *", "p_self"]
]
},
{
@@ -1680,6 +1647,13 @@
]
},
{
+ "name": "godot_packed_byte_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_byte_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_byte_array_append",
"return_type": "void",
"arguments": [
@@ -1705,6 +1679,21 @@
]
},
{
+ "name": "godot_packed_byte_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_byte_array *", "p_self"],
+ ["const uint8_t", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_byte_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_byte_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_byte_array_invert",
"return_type": "void",
"arguments": [
@@ -1736,6 +1725,20 @@
]
},
{
+ "name": "godot_packed_byte_array_ptr",
+ "return_type": "const uint8_t *",
+ "arguments": [
+ ["const godot_packed_byte_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_byte_array_ptrw",
+ "return_type": "uint8_t *",
+ "arguments": [
+ ["godot_packed_byte_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_byte_array_set",
"return_type": "void",
"arguments": [
@@ -1767,223 +1770,587 @@
]
},
{
- "name": "godot_packed_int_array_new",
+ "name": "godot_packed_int32_array_new",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "r_dest"]
+ ["godot_packed_int32_array *", "r_dest"]
]
},
{
- "name": "godot_packed_int_array_new_copy",
+ "name": "godot_packed_int32_array_new_copy",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "r_dest"],
- ["const godot_packed_int_array *", "p_src"]
+ ["godot_packed_int32_array *", "r_dest"],
+ ["const godot_packed_int32_array *", "p_src"]
]
},
{
- "name": "godot_packed_int_array_new_with_array",
+ "name": "godot_packed_int32_array_new_with_array",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "r_dest"],
+ ["godot_packed_int32_array *", "r_dest"],
["const godot_array *", "p_a"]
]
},
{
- "name": "godot_packed_int_array_append",
+ "name": "godot_packed_int32_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_int32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_append",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
- ["const godot_int", "p_data"]
+ ["godot_packed_int32_array *", "p_self"],
+ ["const int32_t", "p_data"]
]
},
{
- "name": "godot_packed_int_array_append_array",
+ "name": "godot_packed_int32_array_append_array",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
- ["const godot_packed_int_array *", "p_array"]
+ ["godot_packed_int32_array *", "p_self"],
+ ["const godot_packed_int32_array *", "p_array"]
]
},
{
- "name": "godot_packed_int_array_insert",
+ "name": "godot_packed_int32_array_insert",
"return_type": "godot_error",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
+ ["godot_packed_int32_array *", "p_self"],
["const godot_int", "p_idx"],
- ["const godot_int", "p_data"]
+ ["const int32_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_int32_array *", "p_self"],
+ ["const int32_t", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int32_array *", "p_self"]
]
},
{
- "name": "godot_packed_int_array_invert",
+ "name": "godot_packed_int32_array_invert",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"]
+ ["godot_packed_int32_array *", "p_self"]
]
},
{
- "name": "godot_packed_int_array_push_back",
+ "name": "godot_packed_int32_array_push_back",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
- ["const godot_int", "p_data"]
+ ["godot_packed_int32_array *", "p_self"],
+ ["const int32_t", "p_data"]
]
},
{
- "name": "godot_packed_int_array_remove",
+ "name": "godot_packed_int32_array_remove",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
+ ["godot_packed_int32_array *", "p_self"],
["const godot_int", "p_idx"]
]
},
{
- "name": "godot_packed_int_array_resize",
+ "name": "godot_packed_int32_array_resize",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
+ ["godot_packed_int32_array *", "p_self"],
["const godot_int", "p_size"]
]
},
{
- "name": "godot_packed_int_array_set",
+ "name": "godot_packed_int32_array_ptr",
+ "return_type": "const int32_t *",
+ "arguments": [
+ ["const godot_packed_int32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_ptrw",
+ "return_type": "int32_t *",
+ "arguments": [
+ ["godot_packed_int32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_set",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"],
+ ["godot_packed_int32_array *", "p_self"],
["const godot_int", "p_idx"],
- ["const godot_int", "p_data"]
+ ["const int32_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_get",
+ "return_type": "int32_t",
+ "arguments": [
+ ["const godot_packed_int32_array *", "p_self"],
+ ["const godot_int", "p_idx"]
]
},
{
- "name": "godot_packed_int_array_get",
+ "name": "godot_packed_int32_array_size",
"return_type": "godot_int",
"arguments": [
- ["const godot_packed_int_array *", "p_self"],
+ ["const godot_packed_int32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int32_array_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "r_dest"],
+ ["const godot_packed_int64_array *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_new_with_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "r_dest"],
+ ["const godot_array *", "p_a"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_int64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_append",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const int64_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_append_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const godot_packed_int64_array *", "p_array"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_insert",
+ "return_type": "godot_error",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const int64_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const int64_t", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_invert",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_push_back",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const int64_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_remove",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_resize",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const godot_int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_ptr",
+ "return_type": "const int64_t *",
+ "arguments": [
+ ["const godot_packed_int64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_ptrw",
+ "return_type": "int64_t *",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_set",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_int64_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const int64_t", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_int64_array_get",
+ "return_type": "int64_t",
+ "arguments": [
+ ["const godot_packed_int64_array *", "p_self"],
["const godot_int", "p_idx"]
]
},
{
- "name": "godot_packed_int_array_size",
+ "name": "godot_packed_int64_array_size",
"return_type": "godot_int",
"arguments": [
- ["const godot_packed_int_array *", "p_self"]
+ ["const godot_packed_int64_array *", "p_self"]
]
},
{
- "name": "godot_packed_int_array_destroy",
+ "name": "godot_packed_int64_array_destroy",
"return_type": "void",
"arguments": [
- ["godot_packed_int_array *", "p_self"]
+ ["godot_packed_int64_array *", "p_self"]
]
},
{
- "name": "godot_packed_real_array_new",
+ "name": "godot_packed_float32_array_new",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "r_dest"]
+ ["godot_packed_float32_array *", "r_dest"]
]
},
{
- "name": "godot_packed_real_array_new_copy",
+ "name": "godot_packed_float32_array_new_copy",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "r_dest"],
- ["const godot_packed_real_array *", "p_src"]
+ ["godot_packed_float32_array *", "r_dest"],
+ ["const godot_packed_float32_array *", "p_src"]
]
},
{
- "name": "godot_packed_real_array_new_with_array",
+ "name": "godot_packed_float32_array_new_with_array",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "r_dest"],
+ ["godot_packed_float32_array *", "r_dest"],
["const godot_array *", "p_a"]
]
},
{
- "name": "godot_packed_real_array_append",
+ "name": "godot_packed_float32_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_float32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float32_array_append",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
- ["const godot_real", "p_data"]
+ ["godot_packed_float32_array *", "p_self"],
+ ["const float", "p_data"]
]
},
{
- "name": "godot_packed_real_array_append_array",
+ "name": "godot_packed_float32_array_append_array",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
- ["const godot_packed_real_array *", "p_array"]
+ ["godot_packed_float32_array *", "p_self"],
+ ["const godot_packed_float32_array *", "p_array"]
]
},
{
- "name": "godot_packed_real_array_insert",
+ "name": "godot_packed_float32_array_insert",
"return_type": "godot_error",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
+ ["godot_packed_float32_array *", "p_self"],
["const godot_int", "p_idx"],
- ["const godot_real", "p_data"]
+ ["const float", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_float32_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_float32_array *", "p_self"],
+ ["const float", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_float32_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float32_array *", "p_self"]
]
},
{
- "name": "godot_packed_real_array_invert",
+ "name": "godot_packed_float32_array_invert",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"]
+ ["godot_packed_float32_array *", "p_self"]
]
},
{
- "name": "godot_packed_real_array_push_back",
+ "name": "godot_packed_float32_array_push_back",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
- ["const godot_real", "p_data"]
+ ["godot_packed_float32_array *", "p_self"],
+ ["const float", "p_data"]
]
},
{
- "name": "godot_packed_real_array_remove",
+ "name": "godot_packed_float32_array_remove",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
+ ["godot_packed_float32_array *", "p_self"],
["const godot_int", "p_idx"]
]
},
{
- "name": "godot_packed_real_array_resize",
+ "name": "godot_packed_float32_array_resize",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
+ ["godot_packed_float32_array *", "p_self"],
["const godot_int", "p_size"]
]
},
{
- "name": "godot_packed_real_array_set",
+ "name": "godot_packed_float32_array_ptr",
+ "return_type": "const float *",
+ "arguments": [
+ ["const godot_packed_float32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float32_array_ptrw",
+ "return_type": "float *",
+ "arguments": [
+ ["godot_packed_float32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float32_array_set",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"],
+ ["godot_packed_float32_array *", "p_self"],
["const godot_int", "p_idx"],
- ["const godot_real", "p_data"]
+ ["const float", "p_data"]
]
},
{
- "name": "godot_packed_real_array_get",
- "return_type": "godot_real",
+ "name": "godot_packed_float32_array_get",
+ "return_type": "float",
"arguments": [
- ["const godot_packed_real_array *", "p_self"],
+ ["const godot_packed_float32_array *", "p_self"],
["const godot_int", "p_idx"]
]
},
{
- "name": "godot_packed_real_array_size",
+ "name": "godot_packed_float32_array_size",
"return_type": "godot_int",
"arguments": [
- ["const godot_packed_real_array *", "p_self"]
+ ["const godot_packed_float32_array *", "p_self"]
]
},
{
- "name": "godot_packed_real_array_destroy",
+ "name": "godot_packed_float32_array_destroy",
"return_type": "void",
"arguments": [
- ["godot_packed_real_array *", "p_self"]
+ ["godot_packed_float32_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "r_dest"],
+ ["const godot_packed_float64_array *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_new_with_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "r_dest"],
+ ["const godot_array *", "p_a"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_append",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const double", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_append_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const godot_packed_float64_array *", "p_array"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_insert",
+ "return_type": "godot_error",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const double", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const double", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_invert",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_push_back",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const double", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_remove",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_resize",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const godot_int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_ptr",
+ "return_type": "const double *",
+ "arguments": [
+ ["const godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_ptrw",
+ "return_type": "double *",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_set",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const double", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_get",
+ "return_type": "double",
+ "arguments": [
+ ["const godot_packed_float64_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_size",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_packed_float64_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_float64_array_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_float64_array *", "p_self"]
]
},
{
@@ -2010,6 +2377,13 @@
]
},
{
+ "name": "godot_packed_string_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_string_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_string_array_append",
"return_type": "void",
"arguments": [
@@ -2035,6 +2409,21 @@
]
},
{
+ "name": "godot_packed_string_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_string_array *", "p_self"],
+ ["const godot_string *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_string_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_string_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_string_array_invert",
"return_type": "void",
"arguments": [
@@ -2066,6 +2455,20 @@
]
},
{
+ "name": "godot_packed_string_array_ptr",
+ "return_type": "const godot_string *",
+ "arguments": [
+ ["const godot_packed_string_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_string_array_ptrw",
+ "return_type": "godot_string *",
+ "arguments": [
+ ["godot_packed_string_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_string_array_set",
"return_type": "void",
"arguments": [
@@ -2120,6 +2523,13 @@
]
},
{
+ "name": "godot_packed_vector2_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_vector2_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector2_array_append",
"return_type": "void",
"arguments": [
@@ -2145,6 +2555,21 @@
]
},
{
+ "name": "godot_packed_vector2_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_vector2_array *", "p_self"],
+ ["const godot_vector2 *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector2_array_invert",
"return_type": "void",
"arguments": [
@@ -2176,6 +2601,20 @@
]
},
{
+ "name": "godot_packed_vector2_array_ptr",
+ "return_type": "const godot_vector2 *",
+ "arguments": [
+ ["const godot_packed_vector2_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2_array_ptrw",
+ "return_type": "godot_vector2 *",
+ "arguments": [
+ ["godot_packed_vector2_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector2_array_set",
"return_type": "void",
"arguments": [
@@ -2207,6 +2646,152 @@
]
},
{
+ "name": "godot_packed_vector2i_array_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "r_dest"],
+ ["const godot_packed_vector2i_array *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_new_with_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "r_dest"],
+ ["const godot_array *", "p_a"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_append",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_vector2i *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_append_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_packed_vector2i_array *", "p_array"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_insert",
+ "return_type": "godot_error",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const godot_vector2i *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_vector2i *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_invert",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_push_back",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_vector2i *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_remove",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_resize",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_ptr",
+ "return_type": "const godot_vector2i *",
+ "arguments": [
+ ["const godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_ptrw",
+ "return_type": "godot_vector2i *",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_set",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const godot_vector2i *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_get",
+ "return_type": "godot_vector2i",
+ "arguments": [
+ ["const godot_packed_vector2i_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_size",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector2i_array_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector2i_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector3_array_new",
"return_type": "void",
"arguments": [
@@ -2230,6 +2815,13 @@
]
},
{
+ "name": "godot_packed_vector3_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_vector3_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector3_array_append",
"return_type": "void",
"arguments": [
@@ -2255,6 +2847,21 @@
]
},
{
+ "name": "godot_packed_vector3_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_vector3_array *", "p_self"],
+ ["const godot_vector3 *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector3_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_vector3_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector3_array_invert",
"return_type": "void",
"arguments": [
@@ -2286,6 +2893,20 @@
]
},
{
+ "name": "godot_packed_vector3_array_ptr",
+ "return_type": "const godot_vector3 *",
+ "arguments": [
+ ["const godot_packed_vector3_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_vector3_array_ptrw",
+ "return_type": "godot_vector3 *",
+ "arguments": [
+ ["godot_packed_vector3_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_vector3_array_set",
"return_type": "void",
"arguments": [
@@ -2340,6 +2961,13 @@
]
},
{
+ "name": "godot_packed_color_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_color_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_color_array_append",
"return_type": "void",
"arguments": [
@@ -2365,6 +2993,21 @@
]
},
{
+ "name": "godot_packed_color_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_color_array *", "p_self"],
+ ["const godot_color *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_color_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_color_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_color_array_invert",
"return_type": "void",
"arguments": [
@@ -2396,6 +3039,20 @@
]
},
{
+ "name": "godot_packed_color_array_ptr",
+ "return_type": "const godot_color *",
+ "arguments": [
+ ["const godot_packed_color_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_color_array_ptrw",
+ "return_type": "godot_color *",
+ "arguments": [
+ ["godot_packed_color_array *", "p_self"]
+ ]
+ },
+ {
"name": "godot_packed_color_array_set",
"return_type": "void",
"arguments": [
@@ -2427,1090 +3084,2198 @@
]
},
{
- "name": "godot_array_new",
+ "name": "godot_plane_new_with_reals",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"]
+ ["godot_plane *", "r_dest"],
+ ["const godot_real", "p_a"],
+ ["const godot_real", "p_b"],
+ ["const godot_real", "p_c"],
+ ["const godot_real", "p_d"]
]
},
{
- "name": "godot_array_new_copy",
+ "name": "godot_plane_new_with_vectors",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_array *", "p_src"]
+ ["godot_plane *", "r_dest"],
+ ["const godot_vector3 *", "p_v1"],
+ ["const godot_vector3 *", "p_v2"],
+ ["const godot_vector3 *", "p_v3"]
]
},
{
- "name": "godot_array_new_packed_color_array",
+ "name": "godot_plane_new_with_normal",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_color_array *", "p_pca"]
+ ["godot_plane *", "r_dest"],
+ ["const godot_vector3 *", "p_normal"],
+ ["const godot_real", "p_d"]
]
},
{
- "name": "godot_array_new_packed_vector3_array",
+ "name": "godot_plane_as_string",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_normalized",
+ "return_type": "godot_plane",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_center",
+ "return_type": "godot_vector3",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_is_point_over",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["const godot_vector3 *", "p_point"]
+ ]
+ },
+ {
+ "name": "godot_plane_distance_to",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["const godot_vector3 *", "p_point"]
+ ]
+ },
+ {
+ "name": "godot_plane_has_point",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["const godot_vector3 *", "p_point"],
+ ["const godot_real", "p_epsilon"]
+ ]
+ },
+ {
+ "name": "godot_plane_project",
+ "return_type": "godot_vector3",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["const godot_vector3 *", "p_point"]
+ ]
+ },
+ {
+ "name": "godot_plane_intersect_3",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["godot_vector3 *", "r_dest"],
+ ["const godot_plane *", "p_b"],
+ ["const godot_plane *", "p_c"]
+ ]
+ },
+ {
+ "name": "godot_plane_intersects_ray",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["godot_vector3 *", "r_dest"],
+ ["const godot_vector3 *", "p_from"],
+ ["const godot_vector3 *", "p_dir"]
+ ]
+ },
+ {
+ "name": "godot_plane_intersects_segment",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["godot_vector3 *", "r_dest"],
+ ["const godot_vector3 *", "p_begin"],
+ ["const godot_vector3 *", "p_end"]
+ ]
+ },
+ {
+ "name": "godot_plane_operator_neg",
+ "return_type": "godot_plane",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_plane *", "p_self"],
+ ["const godot_plane *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_plane_set_normal",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_vector3_array *", "p_pv3a"]
+ ["godot_plane *", "p_self"],
+ ["const godot_vector3 *", "p_normal"]
]
},
{
- "name": "godot_array_new_packed_vector2_array",
+ "name": "godot_plane_get_normal",
+ "return_type": "godot_vector3",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_get_d",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_plane *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_plane_set_d",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_vector2_array *", "p_pv2a"]
+ ["godot_plane *", "p_self"],
+ ["const godot_real", "p_d"]
]
},
{
- "name": "godot_array_new_packed_string_array",
+ "name": "godot_quat_new",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_string_array *", "p_psa"]
+ ["godot_quat *", "r_dest"],
+ ["const godot_real", "p_x"],
+ ["const godot_real", "p_y"],
+ ["const godot_real", "p_z"],
+ ["const godot_real", "p_w"]
]
},
{
- "name": "godot_array_new_packed_real_array",
+ "name": "godot_quat_new_with_axis_angle",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_real_array *", "p_pra"]
+ ["godot_quat *", "r_dest"],
+ ["const godot_vector3 *", "p_axis"],
+ ["const godot_real", "p_angle"]
]
},
{
- "name": "godot_array_new_packed_int_array",
+ "name": "godot_quat_new_with_basis",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_int_array *", "p_pia"]
+ ["godot_quat *", "r_dest"],
+ ["const godot_basis *", "p_basis"]
]
},
{
- "name": "godot_array_new_packed_byte_array",
+ "name": "godot_quat_new_with_euler",
"return_type": "void",
"arguments": [
- ["godot_array *", "r_dest"],
- ["const godot_packed_byte_array *", "p_pba"]
+ ["godot_quat *", "r_dest"],
+ ["const godot_vector3 *", "p_euler"]
]
},
{
- "name": "godot_array_set",
+ "name": "godot_quat_get_x",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_quat_set_x",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_int", "p_idx"],
- ["const godot_variant *", "p_value"]
+ ["godot_quat *", "p_self"],
+ ["const godot_real", "val"]
]
},
{
- "name": "godot_array_get",
- "return_type": "godot_variant",
+ "name": "godot_quat_get_y",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_operator_index",
- "return_type": "godot_variant *",
+ "name": "godot_quat_set_y",
+ "return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["godot_quat *", "p_self"],
+ ["const godot_real", "val"]
]
},
{
- "name": "godot_array_operator_index_const",
- "return_type": "const godot_variant *",
+ "name": "godot_quat_get_z",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_append",
+ "name": "godot_quat_set_z",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["godot_quat *", "p_self"],
+ ["const godot_real", "val"]
]
},
{
- "name": "godot_array_clear",
+ "name": "godot_quat_get_w",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_quat_set_w",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"]
+ ["godot_quat *", "p_self"],
+ ["const godot_real", "val"]
]
},
{
- "name": "godot_array_count",
- "return_type": "godot_int",
+ "name": "godot_quat_set_axis_angle",
+ "return_type": "void",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["godot_quat *", "p_self"],
+ ["const godot_vector3 *", "p_axis"],
+ ["const godot_real", "p_angle"]
+ ]
+ },
+ {
+ "name": "godot_quat_as_string",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_quat_length",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_quat_length_squared",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_empty",
+ "name": "godot_quat_normalized",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_quat_is_normalized",
"return_type": "godot_bool",
"arguments": [
- ["const godot_array *", "p_self"]
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_erase",
- "return_type": "void",
+ "name": "godot_quat_inverse",
+ "return_type": "godot_quat",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_front",
- "return_type": "godot_variant",
+ "name": "godot_quat_dot",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_array *", "p_self"]
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"]
]
},
{
- "name": "godot_array_back",
- "return_type": "godot_variant",
+ "name": "godot_quat_xform",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_array *", "p_self"]
+ ["const godot_quat *", "p_self"],
+ ["const godot_vector3 *", "p_v"]
]
},
{
- "name": "godot_array_find",
- "return_type": "godot_int",
+ "name": "godot_quat_slerp",
+ "return_type": "godot_quat",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_variant *", "p_what"],
- ["const godot_int", "p_from"]
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"],
+ ["const godot_real", "p_t"]
]
},
{
- "name": "godot_array_find_last",
- "return_type": "godot_int",
+ "name": "godot_quat_slerpni",
+ "return_type": "godot_quat",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_variant *", "p_what"]
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"],
+ ["const godot_real", "p_t"]
]
},
{
- "name": "godot_array_has",
+ "name": "godot_quat_cubic_slerp",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"],
+ ["const godot_quat *", "p_pre_a"],
+ ["const godot_quat *", "p_post_b"],
+ ["const godot_real", "p_t"]
+ ]
+ },
+ {
+ "name": "godot_quat_operator_multiply",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"],
+ ["const godot_real", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_quat_operator_add",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_quat_operator_subtract",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_quat_operator_divide",
+ "return_type": "godot_quat",
+ "arguments": [
+ ["const godot_quat *", "p_self"],
+ ["const godot_real", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_quat_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["const godot_quat *", "p_self"],
+ ["const godot_quat *", "p_b"]
]
},
{
- "name": "godot_array_hash",
- "return_type": "godot_int",
+ "name": "godot_quat_operator_neg",
+ "return_type": "godot_quat",
"arguments": [
- ["const godot_array *", "p_self"]
+ ["const godot_quat *", "p_self"]
]
},
{
- "name": "godot_array_insert",
+ "name": "godot_rect2_new_with_position_and_size",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_int", "p_pos"],
- ["const godot_variant *", "p_value"]
+ ["godot_rect2 *", "r_dest"],
+ ["const godot_vector2 *", "p_pos"],
+ ["const godot_vector2 *", "p_size"]
]
},
{
- "name": "godot_array_invert",
+ "name": "godot_rect2_new",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"]
+ ["godot_rect2 *", "r_dest"],
+ ["const godot_real", "p_x"],
+ ["const godot_real", "p_y"],
+ ["const godot_real", "p_width"],
+ ["const godot_real", "p_height"]
]
},
{
- "name": "godot_array_pop_back",
- "return_type": "godot_variant",
+ "name": "godot_rect2_as_rect2i",
+ "return_type": "godot_rect2i",
"arguments": [
- ["godot_array *", "p_self"]
+ ["const godot_rect2 *", "p_self"]
]
},
{
- "name": "godot_array_pop_front",
- "return_type": "godot_variant",
+ "name": "godot_rect2_as_string",
+ "return_type": "godot_string",
"arguments": [
- ["godot_array *", "p_self"]
+ ["const godot_rect2 *", "p_self"]
]
},
{
- "name": "godot_array_push_back",
+ "name": "godot_rect2_get_area",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2_grow_individual",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_real", "p_left"],
+ ["const godot_real", "p_top"],
+ ["const godot_real", "p_right"],
+ ["const godot_real", "p_bottom"]
+ ]
+ },
+ {
+ "name": "godot_rect2_grow_side",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_int", "p_side"],
+ ["const godot_real", "p_by"]
+ ]
+ },
+ {
+ "name": "godot_rect2_abs",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2_intersects",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_rect2 *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2_encloses",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_rect2 *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2_has_no_area",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2_intersection",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_rect2 *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2_merge",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_rect2 *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2_has_point",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_vector2 *", "p_point"]
+ ]
+ },
+ {
+ "name": "godot_rect2_grow",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_real", "p_by"]
+ ]
+ },
+ {
+ "name": "godot_rect2_expand",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
+ ]
+ },
+ {
+ "name": "godot_rect2_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"],
+ ["const godot_rect2 *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2_get_position",
+ "return_type": "godot_vector2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2_get_size",
+ "return_type": "godot_vector2",
+ "arguments": [
+ ["const godot_rect2 *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2_set_position",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["godot_rect2 *", "p_self"],
+ ["const godot_vector2 *", "p_pos"]
]
},
{
- "name": "godot_array_push_front",
+ "name": "godot_rect2_set_size",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"]
+ ["godot_rect2 *", "p_self"],
+ ["const godot_vector2 *", "p_size"]
]
},
{
- "name": "godot_array_remove",
+ "name": "godot_rect2i_new_with_position_and_size",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["godot_rect2i *", "r_dest"],
+ ["const godot_vector2i *", "p_pos"],
+ ["const godot_vector2i *", "p_size"]
]
},
{
- "name": "godot_array_resize",
+ "name": "godot_rect2i_new",
"return_type": "void",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_int", "p_size"]
+ ["godot_rect2i *", "r_dest"],
+ ["const godot_int", "p_x"],
+ ["const godot_int", "p_y"],
+ ["const godot_int", "p_width"],
+ ["const godot_int", "p_height"]
]
},
{
- "name": "godot_array_rfind",
- "return_type": "godot_int",
+ "name": "godot_rect2i_as_string",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_array *", "p_self"],
- ["const godot_variant *", "p_what"],
- ["const godot_int", "p_from"]
+ ["const godot_rect2i *", "p_self"]
]
},
{
- "name": "godot_array_size",
+ "name": "godot_rect2i_as_rect2",
+ "return_type": "godot_rect2",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_get_area",
"return_type": "godot_int",
"arguments": [
- ["const godot_array *", "p_self"]
+ ["const godot_rect2i *", "p_self"]
]
},
{
- "name": "godot_array_sort",
- "return_type": "void",
+ "name": "godot_rect2i_intersects",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_array *", "p_self"]
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_rect2i *", "p_b"]
]
},
{
- "name": "godot_array_sort_custom",
- "return_type": "void",
+ "name": "godot_rect2i_encloses",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_array *", "p_self"],
- ["godot_object *", "p_obj"],
- ["const godot_string *", "p_func"]
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_rect2i *", "p_b"]
]
},
{
- "name": "godot_array_bsearch",
- "return_type": "godot_int",
+ "name": "godot_rect2i_has_no_area",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"],
- ["const godot_bool", "p_before"]
+ ["const godot_rect2i *", "p_self"]
]
},
{
- "name": "godot_array_bsearch_custom",
- "return_type": "godot_int",
+ "name": "godot_rect2i_intersection",
+ "return_type": "godot_rect2i",
"arguments": [
- ["godot_array *", "p_self"],
- ["const godot_variant *", "p_value"],
- ["godot_object *", "p_obj"],
- ["const godot_string *", "p_func"],
- ["const godot_bool", "p_before"]
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_rect2i *", "p_b"]
]
},
{
- "name": "godot_array_destroy",
- "return_type": "void",
+ "name": "godot_rect2i_merge",
+ "return_type": "godot_rect2i",
"arguments": [
- ["godot_array *", "p_self"]
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_rect2i *", "p_b"]
]
},
{
- "name": "godot_dictionary_new",
- "return_type": "void",
+ "name": "godot_rect2i_has_point",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_dictionary *", "r_dest"]
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_vector2i *", "p_point"]
]
},
{
- "name": "godot_dictionary_new_copy",
+ "name": "godot_rect2i_grow",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_int", "p_by"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_grow_individual",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_int", "p_left"],
+ ["const godot_int", "p_top"],
+ ["const godot_int", "p_right"],
+ ["const godot_int", "p_bottom"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_grow_side",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_int", "p_side"],
+ ["const godot_int", "p_by"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_abs",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_expand",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_vector2i *", "p_to"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_operator_equal",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"],
+ ["const godot_rect2i *", "p_b"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_get_position",
+ "return_type": "godot_vector2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_get_size",
+ "return_type": "godot_vector2i",
+ "arguments": [
+ ["const godot_rect2i *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_rect2i_set_position",
"return_type": "void",
"arguments": [
- ["godot_dictionary *", "r_dest"],
- ["const godot_dictionary *", "p_src"]
+ ["godot_rect2i *", "p_self"],
+ ["const godot_vector2i *", "p_pos"]
]
},
{
- "name": "godot_dictionary_destroy",
+ "name": "godot_rect2i_set_size",
"return_type": "void",
"arguments": [
- ["godot_dictionary *", "p_self"]
+ ["godot_rect2i *", "p_self"],
+ ["const godot_vector2i *", "p_size"]
]
},
{
- "name": "godot_dictionary_size",
- "return_type": "godot_int",
+ "name": "godot_rid_new",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["godot_rid *", "r_dest"]
]
},
{
- "name": "godot_dictionary_empty",
- "return_type": "godot_bool",
+ "name": "godot_rid_get_id",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["const godot_rid *", "p_self"]
]
},
{
- "name": "godot_dictionary_clear",
+ "name": "godot_rid_new_with_resource",
"return_type": "void",
"arguments": [
- ["godot_dictionary *", "p_self"]
+ ["godot_rid *", "r_dest"],
+ ["const godot_object *", "p_from"]
]
},
{
- "name": "godot_dictionary_has",
+ "name": "godot_rid_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["const godot_rid *", "p_self"],
+ ["const godot_rid *", "p_b"]
]
},
{
- "name": "godot_dictionary_has_all",
+ "name": "godot_rid_operator_less",
"return_type": "godot_bool",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_array *", "p_keys"]
+ ["const godot_rid *", "p_self"],
+ ["const godot_rid *", "p_b"]
]
},
{
- "name": "godot_dictionary_erase",
+ "name": "godot_char_string_length",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_char_string *", "p_cs"]
+ ]
+ },
+ {
+ "name": "godot_char_string_get_data",
+ "return_type": "const char *",
+ "arguments": [
+ ["const godot_char_string *", "p_cs"]
+ ]
+ },
+ {
+ "name": "godot_char_string_destroy",
"return_type": "void",
"arguments": [
- ["godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["godot_char_string *", "p_cs"]
]
},
{
- "name": "godot_dictionary_hash",
+ "name": "godot_char16_string_length",
"return_type": "godot_int",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["const godot_char16_string *", "p_cs"]
]
},
{
- "name": "godot_dictionary_keys",
- "return_type": "godot_array",
+ "name": "godot_char16_string_get_data",
+ "return_type": "const char16_t *",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["const godot_char16_string *", "p_cs"]
]
},
{
- "name": "godot_dictionary_values",
- "return_type": "godot_array",
+ "name": "godot_char16_string_destroy",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["godot_char16_string *", "p_cs"]
]
},
{
- "name": "godot_dictionary_get",
- "return_type": "godot_variant",
+ "name": "godot_string_new",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["godot_string *", "r_dest"]
]
},
{
- "name": "godot_dictionary_set",
+ "name": "godot_string_new_copy",
"return_type": "void",
"arguments": [
- ["godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"],
- ["const godot_variant *", "p_value"]
+ ["godot_string *", "r_dest"],
+ ["const godot_string *", "p_src"]
]
},
{
- "name": "godot_dictionary_operator_index",
- "return_type": "godot_variant *",
+ "name": "godot_string_new_with_latin1_chars",
+ "return_type": "void",
"arguments": [
- ["godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["godot_string *", "r_dest"],
+ ["const char *", "p_contents"]
]
},
{
- "name": "godot_dictionary_operator_index_const",
- "return_type": "const godot_variant *",
+ "name": "godot_string_new_with_utf8_chars",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["godot_string *", "r_dest"],
+ ["const char *", "p_contents"]
]
},
{
- "name": "godot_dictionary_next",
- "return_type": "godot_variant *",
+ "name": "godot_string_new_with_utf16_chars",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_variant *", "p_key"]
+ ["godot_string *", "r_dest"],
+ ["const char16_t *", "p_contents"]
]
},
{
- "name": "godot_dictionary_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_string_new_with_utf32_chars",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"],
- ["const godot_dictionary *", "p_b"]
+ ["godot_string *", "r_dest"],
+ ["const char32_t *", "p_contents"]
]
},
{
- "name": "godot_dictionary_to_json",
- "return_type": "godot_string",
+ "name": "godot_string_new_with_wide_chars",
+ "return_type": "void",
"arguments": [
- ["const godot_dictionary *", "p_self"]
+ ["godot_string *", "r_dest"],
+ ["const wchar_t *", "p_contents"]
]
},
{
- "name": "godot_node_path_new",
+ "name": "godot_string_new_with_latin1_chars_and_len",
"return_type": "void",
"arguments": [
- ["godot_node_path *", "r_dest"],
- ["const godot_string *", "p_from"]
+ ["godot_string *", "r_dest"],
+ ["const char *", "p_contents"],
+ ["const int", "p_size"]
]
},
{
- "name": "godot_node_path_new_copy",
+ "name": "godot_string_new_with_utf8_chars_and_len",
"return_type": "void",
"arguments": [
- ["godot_node_path *", "r_dest"],
- ["const godot_node_path *", "p_src"]
+ ["godot_string *", "r_dest"],
+ ["const char *", "p_contents"],
+ ["const int", "p_size"]
]
},
{
- "name": "godot_node_path_destroy",
+ "name": "godot_string_new_with_utf16_chars_and_len",
"return_type": "void",
"arguments": [
- ["godot_node_path *", "p_self"]
+ ["godot_string *", "r_dest"],
+ ["const char16_t *", "p_contents"],
+ ["const int", "p_size"]
]
},
{
- "name": "godot_node_path_as_string",
- "return_type": "godot_string",
+ "name": "godot_string_new_with_utf32_chars_and_len",
+ "return_type": "void",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["godot_string *", "r_dest"],
+ ["const char32_t *", "p_contents"],
+ ["const int", "p_size"]
]
},
{
- "name": "godot_node_path_is_absolute",
+ "name": "godot_string_new_with_wide_chars_and_len",
+ "return_type": "void",
+ "arguments": [
+ ["godot_string *", "r_dest"],
+ ["const wchar_t *", "p_contents"],
+ ["const int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_string_operator_index",
+ "return_type": "const godot_char_type *",
+ "arguments": [
+ ["godot_string *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_string_operator_index_const",
+ "return_type": "godot_char_type",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_string_get_data",
+ "return_type": "const godot_char_type *",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_b"]
]
},
{
- "name": "godot_node_path_get_name_count",
- "return_type": "godot_int",
+ "name": "godot_string_operator_less",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_b"]
]
},
{
- "name": "godot_node_path_get_name",
+ "name": "godot_string_operator_plus",
"return_type": "godot_string",
"arguments": [
- ["const godot_node_path *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_b"]
]
},
{
- "name": "godot_node_path_get_subname_count",
+ "name": "godot_string_count",
"return_type": "godot_int",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"],
+ ["godot_int", "p_to"]
]
},
{
- "name": "godot_node_path_get_subname",
+ "name": "godot_string_countn",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"],
+ ["godot_int", "p_to"]
+ ]
+ },
+ {
+ "name": "godot_string_dedent",
"return_type": "godot_string",
"arguments": [
- ["const godot_node_path *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_node_path_get_concatenated_subnames",
+ "name": "godot_string_length",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_casecmp_to",
+ "return_type": "signed char",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_str"]
+ ]
+ },
+ {
+ "name": "godot_string_nocasecmp_to",
+ "return_type": "signed char",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_str"]
+ ]
+ },
+ {
+ "name": "godot_string_naturalnocasecmp_to",
+ "return_type": "signed char",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_str"]
+ ]
+ },
+ {
+ "name": "godot_string_begins_with",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_string"]
+ ]
+ },
+ {
+ "name": "godot_string_begins_with_char_array",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const char *", "p_char_array"]
+ ]
+ },
+ {
+ "name": "godot_string_bigrams",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_chr",
"return_type": "godot_string",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["godot_char_type", "p_character"]
]
},
{
- "name": "godot_node_path_is_empty",
+ "name": "godot_string_ends_with",
"return_type": "godot_bool",
"arguments": [
- ["const godot_node_path *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_string"]
]
},
{
- "name": "godot_node_path_operator_equal",
+ "name": "godot_string_ends_with_char_array",
"return_type": "godot_bool",
"arguments": [
- ["const godot_node_path *", "p_self"],
- ["const godot_node_path *", "p_b"]
+ ["const godot_string *", "p_self"],
+ ["const char *", "p_char_array"]
]
},
{
- "name": "godot_plane_new_with_reals",
- "return_type": "void",
+ "name": "godot_string_find",
+ "return_type": "godot_int",
"arguments": [
- ["godot_plane *", "r_dest"],
- ["const godot_real", "p_a"],
- ["const godot_real", "p_b"],
- ["const godot_real", "p_c"],
- ["const godot_real", "p_d"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"]
]
},
{
- "name": "godot_plane_new_with_vectors",
- "return_type": "void",
+ "name": "godot_string_find_from",
+ "return_type": "godot_int",
"arguments": [
- ["godot_plane *", "r_dest"],
- ["const godot_vector3 *", "p_v1"],
- ["const godot_vector3 *", "p_v2"],
- ["const godot_vector3 *", "p_v3"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"]
]
},
{
- "name": "godot_plane_new_with_normal",
- "return_type": "void",
+ "name": "godot_string_findmk",
+ "return_type": "godot_int",
"arguments": [
- ["godot_plane *", "r_dest"],
- ["const godot_vector3 *", "p_normal"],
- ["const godot_real", "p_d"]
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_keys"]
]
},
{
- "name": "godot_plane_as_string",
+ "name": "godot_string_findmk_from",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_keys"],
+ ["godot_int", "p_from"]
+ ]
+ },
+ {
+ "name": "godot_string_findmk_from_in_place",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_keys"],
+ ["godot_int", "p_from"],
+ ["godot_int *", "r_key"]
+ ]
+ },
+ {
+ "name": "godot_string_findn",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"]
+ ]
+ },
+ {
+ "name": "godot_string_findn_from",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"]
+ ]
+ },
+ {
+ "name": "godot_string_format",
"return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_variant *", "p_values"]
]
},
{
- "name": "godot_plane_normalized",
- "return_type": "godot_plane",
+ "name": "godot_string_format_with_custom_placeholder",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_variant *", "p_values"],
+ ["const char *", "p_placeholder"]
]
},
{
- "name": "godot_plane_center",
- "return_type": "godot_vector3",
+ "name": "godot_string_hex_encode_buffer",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["const uint8_t *", "p_buffer"],
+ ["godot_int", "p_len"]
]
},
{
- "name": "godot_plane_get_any_point",
- "return_type": "godot_vector3",
+ "name": "godot_string_insert",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_at_pos"],
+ ["const godot_string *", "p_string"]
]
},
{
- "name": "godot_plane_is_point_over",
+ "name": "godot_string_is_numeric",
"return_type": "godot_bool",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["const godot_vector3 *", "p_point"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_plane_distance_to",
- "return_type": "godot_real",
+ "name": "godot_string_is_subsequence_of",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["const godot_vector3 *", "p_point"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_string"]
]
},
{
- "name": "godot_plane_has_point",
+ "name": "godot_string_is_subsequence_ofi",
"return_type": "godot_bool",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["const godot_vector3 *", "p_point"],
- ["const godot_real", "p_epsilon"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_string"]
]
},
{
- "name": "godot_plane_project",
- "return_type": "godot_vector3",
+ "name": "godot_string_lpad",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["const godot_vector3 *", "p_point"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_min_length"]
]
},
{
- "name": "godot_plane_intersect_3",
- "return_type": "godot_bool",
+ "name": "godot_string_lpad_with_custom_character",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["godot_vector3 *", "r_dest"],
- ["const godot_plane *", "p_b"],
- ["const godot_plane *", "p_c"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_min_length"],
+ ["const godot_string *", "p_character"]
]
},
{
- "name": "godot_plane_intersects_ray",
+ "name": "godot_string_match",
"return_type": "godot_bool",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["godot_vector3 *", "r_dest"],
- ["const godot_vector3 *", "p_from"],
- ["const godot_vector3 *", "p_dir"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_wildcard"]
]
},
{
- "name": "godot_plane_intersects_segment",
+ "name": "godot_string_matchn",
"return_type": "godot_bool",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["godot_vector3 *", "r_dest"],
- ["const godot_vector3 *", "p_begin"],
- ["const godot_vector3 *", "p_end"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_wildcard"]
]
},
{
- "name": "godot_plane_operator_neg",
- "return_type": "godot_plane",
+ "name": "godot_string_md5",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["const uint8_t *", "p_md5"]
]
},
{
- "name": "godot_plane_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_string_num",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"],
- ["const godot_plane *", "p_b"]
+ ["double", "p_num"]
]
},
{
- "name": "godot_plane_set_normal",
- "return_type": "void",
+ "name": "godot_string_num_int64",
+ "return_type": "godot_string",
"arguments": [
- ["godot_plane *", "p_self"],
- ["const godot_vector3 *", "p_normal"]
+ ["int64_t", "p_num"],
+ ["godot_int", "p_base"]
]
},
{
- "name": "godot_plane_get_normal",
- "return_type": "godot_vector3",
+ "name": "godot_string_num_int64_capitalized",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["int64_t", "p_num"],
+ ["godot_int", "p_base"],
+ ["godot_bool", "p_capitalize_hex"]
]
},
{
- "name": "godot_plane_get_d",
- "return_type": "godot_real",
+ "name": "godot_string_num_real",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_plane *", "p_self"]
+ ["double", "p_num"]
]
},
{
- "name": "godot_plane_set_d",
- "return_type": "void",
+ "name": "godot_string_num_scientific",
+ "return_type": "godot_string",
"arguments": [
- ["godot_plane *", "p_self"],
- ["const godot_real", "p_d"]
+ ["double", "p_num"]
]
},
{
- "name": "godot_rect2_new_with_position_and_size",
- "return_type": "void",
+ "name": "godot_string_num_with_decimals",
+ "return_type": "godot_string",
"arguments": [
- ["godot_rect2 *", "r_dest"],
- ["const godot_vector2 *", "p_pos"],
- ["const godot_vector2 *", "p_size"]
+ ["double", "p_num"],
+ ["godot_int", "p_decimals"]
]
},
{
- "name": "godot_rect2_new",
- "return_type": "void",
+ "name": "godot_string_pad_decimals",
+ "return_type": "godot_string",
"arguments": [
- ["godot_rect2 *", "r_dest"],
- ["const godot_real", "p_x"],
- ["const godot_real", "p_y"],
- ["const godot_real", "p_width"],
- ["const godot_real", "p_height"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_digits"]
]
},
{
- "name": "godot_rect2_as_string",
+ "name": "godot_string_pad_zeros",
"return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_digits"]
]
},
{
- "name": "godot_rect2_get_area",
+ "name": "godot_string_replace_first",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_key"],
+ ["const godot_string *", "p_with"]
+ ]
+ },
+ {
+ "name": "godot_string_replace",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_key"],
+ ["const godot_string *", "p_with"]
+ ]
+ },
+ {
+ "name": "godot_string_replacen",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_key"],
+ ["const godot_string *", "p_with"]
+ ]
+ },
+ {
+ "name": "godot_string_rfind",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"]
+ ]
+ },
+ {
+ "name": "godot_string_rfindn",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"]
+ ]
+ },
+ {
+ "name": "godot_string_rfind_from",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"]
+ ]
+ },
+ {
+ "name": "godot_string_rfindn_from",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_what"],
+ ["godot_int", "p_from"]
+ ]
+ },
+ {
+ "name": "godot_string_rpad",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_min_length"]
+ ]
+ },
+ {
+ "name": "godot_string_rpad_with_custom_character",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_min_length"],
+ ["const godot_string *", "p_character"]
+ ]
+ },
+ {
+ "name": "godot_string_similarity",
"return_type": "godot_real",
"arguments": [
- ["const godot_rect2 *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_string"]
]
},
{
- "name": "godot_rect2_intersects",
- "return_type": "godot_bool",
+ "name": "godot_string_sprintf",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_rect2 *", "p_b"]
+ ["const godot_string *", "p_self"],
+ ["const godot_array *", "p_values"],
+ ["godot_bool *", "p_error"]
]
},
{
- "name": "godot_rect2_encloses",
- "return_type": "godot_bool",
+ "name": "godot_string_substr",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_rect2 *", "p_b"]
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_from"],
+ ["godot_int", "p_chars"]
]
},
{
- "name": "godot_rect2_has_no_area",
- "return_type": "godot_bool",
+ "name": "godot_string_to_int",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_rect2 *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rect2_clip",
- "return_type": "godot_rect2",
+ "name": "godot_string_to_float",
+ "return_type": "double",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_rect2 *", "p_b"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rect2_merge",
- "return_type": "godot_rect2",
+ "name": "godot_string_camelcase_to_underscore",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_rect2 *", "p_b"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rect2_has_point",
- "return_type": "godot_bool",
+ "name": "godot_string_camelcase_to_underscore_lowercased",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_vector2 *", "p_point"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rect2_grow",
- "return_type": "godot_rect2",
+ "name": "godot_string_capitalize",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_real", "p_by"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rect2_expand",
- "return_type": "godot_rect2",
+ "name": "godot_string_char_to_float",
+ "return_type": "double",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_vector2 *", "p_to"]
+ ["const char *", "p_what"]
]
},
{
- "name": "godot_rect2_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_string_wchar_to_float",
+ "return_type": "double",
"arguments": [
- ["const godot_rect2 *", "p_self"],
- ["const godot_rect2 *", "p_b"]
+ ["const wchar_t *", "p_str"],
+ ["const wchar_t **", "r_end"]
]
},
{
- "name": "godot_rect2_get_position",
- "return_type": "godot_vector2",
+ "name": "godot_string_char_to_int",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_rect2 *", "p_self"]
+ ["const char *", "p_what"]
]
},
{
- "name": "godot_rect2_get_size",
- "return_type": "godot_vector2",
+ "name": "godot_string_wchar_to_int",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_rect2 *", "p_self"]
+ ["const wchar_t *", "p_str"]
]
},
{
- "name": "godot_rect2_set_position",
- "return_type": "void",
+ "name": "godot_string_char_to_int_with_len",
+ "return_type": "godot_int",
"arguments": [
- ["godot_rect2 *", "p_self"],
- ["const godot_vector2 *", "p_pos"]
+ ["const char *", "p_what"],
+ ["godot_int", "p_len"]
]
},
{
- "name": "godot_rect2_set_size",
- "return_type": "void",
+ "name": "godot_string_wchar_to_int_with_len",
+ "return_type": "godot_int",
"arguments": [
- ["godot_rect2 *", "p_self"],
- ["const godot_vector2 *", "p_size"]
+ ["const wchar_t *", "p_str"],
+ ["int", "p_len"]
]
},
{
- "name": "godot_aabb_new",
- "return_type": "void",
+ "name": "godot_string_hex_to_int",
+ "return_type": "godot_int",
"arguments": [
- ["godot_aabb *", "r_dest"],
- ["const godot_vector3 *", "p_pos"],
- ["const godot_vector3 *", "p_size"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_position",
- "return_type": "godot_vector3",
+ "name": "godot_string_hex_to_int_with_prefix",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_set_position",
- "return_type": "void",
+ "name": "godot_string_get_slice_count",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_v"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
]
},
{
- "name": "godot_aabb_get_size",
- "return_type": "godot_vector3",
+ "name": "godot_string_get_slice",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"],
+ ["godot_int", "p_slice"]
]
},
{
- "name": "godot_aabb_set_size",
- "return_type": "void",
+ "name": "godot_string_get_slicec",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_v"]
+ ["const godot_string *", "p_self"],
+ ["godot_char_type", "p_splitter"],
+ ["godot_int", "p_slice"]
]
},
{
- "name": "godot_aabb_as_string",
+ "name": "godot_string_split",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_allow_empty",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_with_maxsplit",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"],
+ ["const godot_bool", "p_allow_empty"],
+ ["const godot_int", "p_maxsplit"]
+ ]
+ },
+ {
+ "name": "godot_string_rsplit",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_rsplit_allow_empty",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_rsplit_with_maxsplit",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"],
+ ["const godot_bool", "p_allow_empty"],
+ ["const godot_int", "p_maxsplit"]
+ ]
+ },
+ {
+ "name": "godot_string_split_floats",
+ "return_type": "godot_packed_float32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_floats_allow_empty",
+ "return_type": "godot_packed_float32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_floats_mk",
+ "return_type": "godot_packed_float32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_splitters"]
+ ]
+ },
+ {
+ "name": "godot_string_split_floats_mk_allow_empty",
+ "return_type": "godot_packed_float32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_splitters"]
+ ]
+ },
+ {
+ "name": "godot_string_split_ints",
+ "return_type": "godot_packed_int32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_ints_allow_empty",
+ "return_type": "godot_packed_int32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_splitter"]
+ ]
+ },
+ {
+ "name": "godot_string_split_ints_mk",
+ "return_type": "godot_packed_int32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_splitters"]
+ ]
+ },
+ {
+ "name": "godot_string_split_ints_mk_allow_empty",
+ "return_type": "godot_packed_int32_array",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_splitters"]
+ ]
+ },
+ {
+ "name": "godot_string_split_spaces",
+ "return_type": "godot_packed_string_array",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_lstrip",
"return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_chars"]
]
},
{
- "name": "godot_aabb_get_area",
- "return_type": "godot_real",
+ "name": "godot_string_rstrip",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_chars"]
]
},
{
- "name": "godot_aabb_has_no_area",
+ "name": "godot_string_trim_prefix",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_prefix"]
+ ]
+ },
+ {
+ "name": "godot_string_trim_suffix",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_suffix"]
+ ]
+ },
+ {
+ "name": "godot_string_char_lowercase",
+ "return_type": "godot_char_type",
+ "arguments": [
+ ["godot_char_type", "p_char"]
+ ]
+ },
+ {
+ "name": "godot_string_char_uppercase",
+ "return_type": "godot_char_type",
+ "arguments": [
+ ["godot_char_type", "p_char"]
+ ]
+ },
+ {
+ "name": "godot_string_to_lower",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_to_upper",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_get_basename",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_get_extension",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_left",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_pos"]
+ ]
+ },
+ {
+ "name": "godot_string_ord_at",
+ "return_type": "godot_char_type",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_string_plus_file",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_file"]
+ ]
+ },
+ {
+ "name": "godot_string_right",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_pos"]
+ ]
+ },
+ {
+ "name": "godot_string_repeat",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_int", "p_count"]
+ ]
+ },
+ {
+ "name": "godot_string_strip_edges",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_bool", "p_left"],
+ ["godot_bool", "p_right"]
+ ]
+ },
+ {
+ "name": "godot_string_strip_escapes",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_erase",
+ "return_type": "void",
+ "arguments": [
+ ["godot_string *", "p_self"],
+ ["godot_int", "p_pos"],
+ ["godot_int", "p_chars"]
+ ]
+ },
+ {
+ "name": "godot_string_ascii",
+ "return_type": "godot_char_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_latin1",
+ "return_type": "godot_char_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_utf8",
+ "return_type": "godot_char_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_parse_utf8",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["godot_string *", "p_self"],
+ ["const char *", "p_utf8"]
]
},
{
- "name": "godot_aabb_has_no_surface",
+ "name": "godot_string_parse_utf8_with_len",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["godot_string *", "p_self"],
+ ["const char *", "p_utf8"],
+ ["godot_int", "p_len"]
]
},
{
- "name": "godot_aabb_intersects",
+ "name": "godot_string_utf16",
+ "return_type": "godot_char16_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_parse_utf16",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_aabb *", "p_with"]
+ ["godot_string *", "p_self"],
+ ["const char16_t *", "p_utf16"]
]
},
{
- "name": "godot_aabb_encloses",
+ "name": "godot_string_parse_utf16_with_len",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_aabb *", "p_with"]
+ ["godot_string *", "p_self"],
+ ["const char16_t *", "p_utf16"],
+ ["godot_int", "p_len"]
]
},
{
- "name": "godot_aabb_merge",
- "return_type": "godot_aabb",
+ "name": "godot_string_hash",
+ "return_type": "uint32_t",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_aabb *", "p_with"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_intersection",
- "return_type": "godot_aabb",
+ "name": "godot_string_hash64",
+ "return_type": "uint64_t",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_aabb *", "p_with"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_intersects_plane",
+ "name": "godot_string_hash_chars",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const char *", "p_cstr"]
+ ]
+ },
+ {
+ "name": "godot_string_hash_chars_with_len",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const char *", "p_cstr"],
+ ["godot_int", "p_len"]
+ ]
+ },
+ {
+ "name": "godot_string_hash_wide_chars",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const wchar_t *", "p_str"]
+ ]
+ },
+ {
+ "name": "godot_string_hash_wide_chars_with_len",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const wchar_t *", "p_str"],
+ ["godot_int", "p_len"]
+ ]
+ },
+ {
+ "name": "godot_string_md5_buffer",
+ "return_type": "godot_packed_byte_array",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_md5_text",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_sha1_buffer",
+ "return_type": "godot_packed_byte_array",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_sha1_text",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_sha256_buffer",
+ "return_type": "godot_packed_byte_array",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_sha256_text",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_is_empty",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_plane *", "p_plane"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_intersects_segment",
+ "name": "godot_string_get_base_dir",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_get_file",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_humanize_size",
+ "return_type": "godot_string",
+ "arguments": [
+ ["uint64_t", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_string_is_abs_path",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_from"],
- ["const godot_vector3 *", "p_to"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_has_point",
+ "name": "godot_string_is_rel_path",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_point"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_support",
- "return_type": "godot_vector3",
+ "name": "godot_string_is_resource_file",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_dir"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_longest_axis",
- "return_type": "godot_vector3",
+ "name": "godot_string_path_to",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_path"]
]
},
{
- "name": "godot_aabb_get_longest_axis_index",
- "return_type": "godot_int",
+ "name": "godot_string_path_to_file",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"],
+ ["const godot_string *", "p_path"]
]
},
{
- "name": "godot_aabb_get_longest_axis_size",
- "return_type": "godot_real",
+ "name": "godot_string_simplify_path",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_shortest_axis",
- "return_type": "godot_vector3",
+ "name": "godot_string_c_escape",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_shortest_axis_index",
- "return_type": "godot_int",
+ "name": "godot_string_c_escape_multiline",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_shortest_axis_size",
- "return_type": "godot_real",
+ "name": "godot_string_c_unescape",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_expand",
- "return_type": "godot_aabb",
+ "name": "godot_string_http_escape",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_vector3 *", "p_to_point"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_grow",
- "return_type": "godot_aabb",
+ "name": "godot_string_http_unescape",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_real", "p_by"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_get_endpoint",
- "return_type": "godot_vector3",
+ "name": "godot_string_json_escape",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_aabb_operator_equal",
+ "name": "godot_string_xml_escape",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_xml_escape_with_quotes",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_xml_unescape",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_percent_decode",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_percent_encode",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_join",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["const godot_packed_string_array *", "p_parts"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_filename",
"return_type": "godot_bool",
"arguments": [
- ["const godot_aabb *", "p_self"],
- ["const godot_aabb *", "p_b"]
+ ["const godot_string *", "p_self"]
]
},
{
- "name": "godot_rid_new",
+ "name": "godot_string_is_valid_float",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_hex_number",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"],
+ ["godot_bool", "p_with_prefix"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_html_color",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_identifier",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_integer",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_is_valid_ip_address",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_string *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_destroy",
"return_type": "void",
"arguments": [
- ["godot_rid *", "r_dest"]
+ ["godot_string *", "p_self"]
]
},
{
- "name": "godot_rid_get_id",
- "return_type": "godot_int",
+ "name": "godot_string_name_new",
+ "return_type": "void",
"arguments": [
- ["const godot_rid *", "p_self"]
+ ["godot_string_name *", "r_dest"],
+ ["const godot_string *", "p_name"]
]
},
{
- "name": "godot_rid_new_with_resource",
+ "name": "godot_string_name_new_data",
"return_type": "void",
"arguments": [
- ["godot_rid *", "r_dest"],
- ["const godot_object *", "p_from"]
+ ["godot_string_name *", "r_dest"],
+ ["const char *", "p_name"]
]
},
{
- "name": "godot_rid_operator_equal",
+ "name": "godot_string_name_get_name",
+ "return_type": "godot_string",
+ "arguments": [
+ ["const godot_string_name *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_name_get_hash",
+ "return_type": "uint32_t",
+ "arguments": [
+ ["const godot_string_name *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_name_get_data_unique_pointer",
+ "return_type": "const void *",
+ "arguments": [
+ ["const godot_string_name *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_string_name_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_rid *", "p_self"],
- ["const godot_rid *", "p_b"]
+ ["const godot_string_name *", "p_self"],
+ ["const godot_string_name *", "p_other"]
]
},
{
- "name": "godot_rid_operator_less",
+ "name": "godot_string_name_operator_less",
"return_type": "godot_bool",
"arguments": [
- ["const godot_rid *", "p_self"],
- ["const godot_rid *", "p_b"]
+ ["const godot_string_name *", "p_self"],
+ ["const godot_string_name *", "p_other"]
+ ]
+ },
+ {
+ "name": "godot_string_name_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_string_name *", "p_self"]
]
},
{
@@ -3525,6 +5290,14 @@
]
},
{
+ "name": "godot_transform_new_with_quat",
+ "return_type": "void",
+ "arguments": [
+ ["godot_transform *", "r_dest"],
+ ["const godot_quat *", "p_quat"]
+ ]
+ },
+ {
"name": "godot_transform_new",
"return_type": "void",
"arguments": [
@@ -3931,6 +5704,14 @@
]
},
{
+ "name": "godot_variant_new_string_name",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_string_name *", "p_s"]
+ ]
+ },
+ {
"name": "godot_variant_new_vector2",
"return_type": "void",
"arguments": [
@@ -3939,6 +5720,14 @@
]
},
{
+ "name": "godot_variant_new_vector2i",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_vector2i *", "p_v2"]
+ ]
+ },
+ {
"name": "godot_variant_new_rect2",
"return_type": "void",
"arguments": [
@@ -3947,6 +5736,14 @@
]
},
{
+ "name": "godot_variant_new_rect2i",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_rect2i *", "p_rect2"]
+ ]
+ },
+ {
"name": "godot_variant_new_vector3",
"return_type": "void",
"arguments": [
@@ -3955,6 +5752,14 @@
]
},
{
+ "name": "godot_variant_new_vector3i",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_vector3i *", "p_v3"]
+ ]
+ },
+ {
"name": "godot_variant_new_transform2d",
"return_type": "void",
"arguments": [
@@ -4035,6 +5840,22 @@
]
},
{
+ "name": "godot_variant_new_callable",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_callable *", "p_cb"]
+ ]
+ },
+ {
+ "name": "godot_variant_new_signal",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_signal *", "p_signal"]
+ ]
+ },
+ {
"name": "godot_variant_new_dictionary",
"return_type": "void",
"arguments": [
@@ -4059,19 +5880,35 @@
]
},
{
- "name": "godot_variant_new_packed_int_array",
+ "name": "godot_variant_new_packed_int32_array",
"return_type": "void",
"arguments": [
["godot_variant *", "r_dest"],
- ["const godot_packed_int_array *", "p_pia"]
+ ["const godot_packed_int32_array *", "p_pia"]
]
},
{
- "name": "godot_variant_new_packed_real_array",
+ "name": "godot_variant_new_packed_int64_array",
"return_type": "void",
"arguments": [
["godot_variant *", "r_dest"],
- ["const godot_packed_real_array *", "p_pra"]
+ ["const godot_packed_int64_array *", "p_pia"]
+ ]
+ },
+ {
+ "name": "godot_variant_new_packed_float32_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_packed_float32_array *", "p_pra"]
+ ]
+ },
+ {
+ "name": "godot_variant_new_packed_float64_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_variant *", "r_dest"],
+ ["const godot_packed_float64_array *", "p_pra"]
]
},
{
@@ -4142,6 +5979,13 @@
]
},
{
+ "name": "godot_variant_as_string_name",
+ "return_type": "godot_string_name",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
"name": "godot_variant_as_vector2",
"return_type": "godot_vector2",
"arguments": [
@@ -4149,6 +5993,13 @@
]
},
{
+ "name": "godot_variant_as_vector2i",
+ "return_type": "godot_vector2i",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
"name": "godot_variant_as_rect2",
"return_type": "godot_rect2",
"arguments": [
@@ -4156,6 +6007,13 @@
]
},
{
+ "name": "godot_variant_as_rect2i",
+ "return_type": "godot_rect2i",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
"name": "godot_variant_as_vector3",
"return_type": "godot_vector3",
"arguments": [
@@ -4163,6 +6021,13 @@
]
},
{
+ "name": "godot_variant_as_vector3i",
+ "return_type": "godot_vector3i",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
"name": "godot_variant_as_transform2d",
"return_type": "godot_transform2d",
"arguments": [
@@ -4233,6 +6098,20 @@
]
},
{
+ "name": "godot_variant_as_callable",
+ "return_type": "godot_callable",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_variant_as_signal",
+ "return_type": "godot_signal",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
"name": "godot_variant_as_dictionary",
"return_type": "godot_dictionary",
"arguments": [
@@ -4254,15 +6133,29 @@
]
},
{
- "name": "godot_variant_as_packed_int_array",
- "return_type": "godot_packed_int_array",
+ "name": "godot_variant_as_packed_int32_array",
+ "return_type": "godot_packed_int32_array",
"arguments": [
["const godot_variant *", "p_self"]
]
},
{
- "name": "godot_variant_as_packed_real_array",
- "return_type": "godot_packed_real_array",
+ "name": "godot_variant_as_packed_int64_array",
+ "return_type": "godot_packed_int64_array",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_variant_as_packed_float32_array",
+ "return_type": "godot_packed_float32_array",
+ "arguments": [
+ ["const godot_variant *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_variant_as_packed_float64_array",
+ "return_type": "godot_packed_float64_array",
"arguments": [
["const godot_variant *", "p_self"]
]
@@ -4315,15 +6208,14 @@
]
},
{
- "name": "godot_variant_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_variant_hash",
+ "return_type": "uint32_t",
"arguments": [
- ["const godot_variant *", "p_self"],
- ["const godot_variant *", "p_other"]
+ ["const godot_variant *", "p_self"]
]
},
{
- "name": "godot_variant_operator_less",
+ "name": "godot_variant_operator_equal",
"return_type": "godot_bool",
"arguments": [
["const godot_variant *", "p_self"],
@@ -4331,7 +6223,7 @@
]
},
{
- "name": "godot_variant_hash_compare",
+ "name": "godot_variant_operator_less",
"return_type": "godot_bool",
"arguments": [
["const godot_variant *", "p_self"],
@@ -4339,1236 +6231,1005 @@
]
},
{
- "name": "godot_variant_booleanize",
- "return_type": "godot_bool",
- "arguments": [
- ["const godot_variant *", "p_self"]
- ]
- },
- {
- "name": "godot_variant_destroy",
- "return_type": "void",
- "arguments": [
- ["godot_variant *", "p_self"]
- ]
- },
- {
- "name": "godot_char_string_length",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_char_string *", "p_cs"]
- ]
- },
- {
- "name": "godot_char_string_get_data",
- "return_type": "const char *",
+ "name": "godot_variant_get_operator_name",
+ "return_type": "godot_string",
"arguments": [
- ["const godot_char_string *", "p_cs"]
+ ["godot_variant_operator", "p_op"]
]
},
{
- "name": "godot_char_string_destroy",
+ "name": "godot_variant_evaluate",
"return_type": "void",
"arguments": [
- ["godot_char_string *", "p_cs"]
+ ["godot_variant_operator", "p_op"],
+ ["const godot_variant *", "p_a"],
+ ["const godot_variant *", "p_b"],
+ ["godot_variant *", "r_ret"],
+ ["godot_bool *", "r_valid"]
]
},
{
- "name": "godot_string_new",
- "return_type": "void",
+ "name": "godot_variant_hash_compare",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_string *", "r_dest"]
+ ["const godot_variant *", "p_self"],
+ ["const godot_variant *", "p_other"]
]
},
{
- "name": "godot_string_new_copy",
- "return_type": "void",
+ "name": "godot_variant_booleanize",
+ "return_type": "godot_bool",
"arguments": [
- ["godot_string *", "r_dest"],
- ["const godot_string *", "p_src"]
+ ["const godot_variant *", "p_self"]
]
},
{
- "name": "godot_string_new_with_wide_string",
+ "name": "godot_variant_destroy",
"return_type": "void",
"arguments": [
- ["godot_string *", "r_dest"],
- ["const wchar_t *", "p_contents"],
- ["const int", "p_size"]
+ ["godot_variant *", "p_self"]
]
},
{
- "name": "godot_string_operator_index",
- "return_type": "const wchar_t *",
+ "name": "godot_vector2_as_vector2i",
+ "return_type": "godot_vector2i",
"arguments": [
- ["godot_string *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_operator_index_const",
- "return_type": "wchar_t",
+ "name": "godot_vector2_sign",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_int", "p_idx"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_wide_str",
- "return_type": "const wchar_t *",
+ "name": "godot_vector2_move_toward",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"],
+ ["const godot_real", "p_delta"]
]
},
{
- "name": "godot_string_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_vector2_direction_to",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_b"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
]
},
{
- "name": "godot_string_operator_less",
- "return_type": "godot_bool",
+ "name": "godot_vector2_new",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_b"]
+ ["godot_vector2 *", "r_dest"],
+ ["const godot_real", "p_x"],
+ ["const godot_real", "p_y"]
]
},
{
- "name": "godot_string_operator_plus",
+ "name": "godot_vector2_as_string",
"return_type": "godot_string",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_b"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_length",
- "return_type": "godot_int",
+ "name": "godot_vector2_normalized",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_casecmp_to",
- "return_type": "signed char",
+ "name": "godot_vector2_length",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_str"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_nocasecmp_to",
- "return_type": "signed char",
+ "name": "godot_vector2_angle",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_str"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_naturalnocasecmp_to",
- "return_type": "signed char",
+ "name": "godot_vector2_length_squared",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_str"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_begins_with",
+ "name": "godot_vector2_is_normalized",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_string"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_begins_with_char_array",
- "return_type": "godot_bool",
+ "name": "godot_vector2_distance_to",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const char *", "p_char_array"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
]
},
{
- "name": "godot_string_bigrams",
- "return_type": "godot_array",
+ "name": "godot_vector2_distance_squared_to",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
]
},
{
- "name": "godot_string_chr",
- "return_type": "godot_string",
+ "name": "godot_vector2_angle_to",
+ "return_type": "godot_real",
"arguments": [
- ["wchar_t", "p_character"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
]
},
{
- "name": "godot_string_ends_with",
- "return_type": "godot_bool",
+ "name": "godot_vector2_angle_to_point",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_string"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"]
]
},
{
- "name": "godot_string_find",
- "return_type": "godot_int",
+ "name": "godot_vector2_lerp",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"],
+ ["const godot_real", "p_t"]
]
},
{
- "name": "godot_string_find_from",
- "return_type": "godot_int",
+ "name": "godot_vector2_cubic_interpolate",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"]
+ ["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"]
]
},
{
- "name": "godot_string_findmk",
- "return_type": "godot_int",
+ "name": "godot_vector2_rotated",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_keys"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_real", "p_phi"]
]
},
{
- "name": "godot_string_findmk_from",
- "return_type": "godot_int",
+ "name": "godot_vector2_orthogonal",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_keys"],
- ["godot_int", "p_from"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_findmk_from_in_place",
- "return_type": "godot_int",
+ "name": "godot_vector2_floor",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_keys"],
- ["godot_int", "p_from"],
- ["godot_int *", "r_key"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_findn",
- "return_type": "godot_int",
+ "name": "godot_vector2_snapped",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_by"]
]
},
{
- "name": "godot_string_findn_from",
- "return_type": "godot_int",
+ "name": "godot_vector2_aspect",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_find_last",
- "return_type": "godot_int",
+ "name": "godot_vector2_dot",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_with"]
]
},
{
- "name": "godot_string_format",
- "return_type": "godot_string",
+ "name": "godot_vector2_slide",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_variant *", "p_values"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_n"]
]
},
{
- "name": "godot_string_format_with_custom_placeholder",
- "return_type": "godot_string",
+ "name": "godot_vector2_bounce",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_variant *", "p_values"],
- ["const char *", "p_placeholder"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_n"]
]
},
{
- "name": "godot_string_hex_encode_buffer",
- "return_type": "godot_string",
+ "name": "godot_vector2_reflect",
+ "return_type": "godot_vector2",
"arguments": [
- ["const uint8_t *", "p_buffer"],
- ["godot_int", "p_len"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_n"]
]
},
{
- "name": "godot_string_hex_to_int",
- "return_type": "godot_int",
+ "name": "godot_vector2_abs",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_hex_to_int_without_prefix",
- "return_type": "godot_int",
+ "name": "godot_vector2_clamped",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_real", "p_length"]
]
},
{
- "name": "godot_string_insert",
- "return_type": "godot_string",
+ "name": "godot_vector2_operator_add",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_at_pos"],
- ["godot_string", "p_string"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_is_numeric",
- "return_type": "godot_bool",
+ "name": "godot_vector2_operator_subtract",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_is_subsequence_of",
- "return_type": "godot_bool",
+ "name": "godot_vector2_operator_multiply_vector",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_string"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_is_subsequence_ofi",
- "return_type": "godot_bool",
+ "name": "godot_vector2_operator_multiply_scalar",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_string"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_real", "p_b"]
]
},
{
- "name": "godot_string_lpad",
- "return_type": "godot_string",
+ "name": "godot_vector2_operator_divide_vector",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_min_length"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_lpad_with_custom_character",
- "return_type": "godot_string",
+ "name": "godot_vector2_operator_divide_scalar",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_min_length"],
- ["const godot_string *", "p_character"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_real", "p_b"]
]
},
{
- "name": "godot_string_match",
+ "name": "godot_vector2_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_wildcard"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_matchn",
+ "name": "godot_vector2_operator_less",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_wildcard"]
- ]
- },
- {
- "name": "godot_string_md5",
- "return_type": "godot_string",
- "arguments": [
- ["const uint8_t *", "p_md5"]
- ]
- },
- {
- "name": "godot_string_num",
- "return_type": "godot_string",
- "arguments": [
- ["double", "p_num"]
- ]
- },
- {
- "name": "godot_string_num_int64",
- "return_type": "godot_string",
- "arguments": [
- ["int64_t", "p_num"],
- ["godot_int", "p_base"]
- ]
- },
- {
- "name": "godot_string_num_int64_capitalized",
- "return_type": "godot_string",
- "arguments": [
- ["int64_t", "p_num"],
- ["godot_int", "p_base"],
- ["godot_bool", "p_capitalize_hex"]
- ]
- },
- {
- "name": "godot_string_num_real",
- "return_type": "godot_string",
- "arguments": [
- ["double", "p_num"]
- ]
- },
- {
- "name": "godot_string_num_scientific",
- "return_type": "godot_string",
- "arguments": [
- ["double", "p_num"]
- ]
- },
- {
- "name": "godot_string_num_with_decimals",
- "return_type": "godot_string",
- "arguments": [
- ["double", "p_num"],
- ["godot_int", "p_decimals"]
- ]
- },
- {
- "name": "godot_string_pad_decimals",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_digits"]
- ]
- },
- {
- "name": "godot_string_pad_zeros",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_digits"]
- ]
- },
- {
- "name": "godot_string_replace_first",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_key"],
- ["godot_string", "p_with"]
- ]
- },
- {
- "name": "godot_string_replace",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_key"],
- ["godot_string", "p_with"]
- ]
- },
- {
- "name": "godot_string_replacen",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_key"],
- ["godot_string", "p_with"]
- ]
- },
- {
- "name": "godot_string_rfind",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"]
- ]
- },
- {
- "name": "godot_string_rfindn",
- "return_type": "godot_int",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"]
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_b"]
]
},
{
- "name": "godot_string_rfind_from",
- "return_type": "godot_int",
+ "name": "godot_vector2_operator_neg",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_rfindn_from",
- "return_type": "godot_int",
+ "name": "godot_vector2_set_x",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_what"],
- ["godot_int", "p_from"]
+ ["godot_vector2 *", "p_self"],
+ ["const godot_real", "p_x"]
]
},
{
- "name": "godot_string_rpad",
- "return_type": "godot_string",
+ "name": "godot_vector2_set_y",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_min_length"]
+ ["godot_vector2 *", "p_self"],
+ ["const godot_real", "p_y"]
]
},
{
- "name": "godot_string_rpad_with_custom_character",
- "return_type": "godot_string",
+ "name": "godot_vector2_get_x",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_min_length"],
- ["const godot_string *", "p_character"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_similarity",
+ "name": "godot_vector2_get_y",
"return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_string"]
+ ["const godot_vector2 *", "p_self"]
]
},
{
- "name": "godot_string_sprintf",
- "return_type": "godot_string",
+ "name": "godot_vector2i_new",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_values"],
- ["godot_bool *", "p_error"]
+ ["godot_vector2i *", "r_dest"],
+ ["const godot_int", "p_x"],
+ ["const godot_int", "p_y"]
]
},
{
- "name": "godot_string_substr",
+ "name": "godot_vector2i_as_string",
"return_type": "godot_string",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_from"],
- ["godot_int", "p_chars"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_to_double",
- "return_type": "double",
+ "name": "godot_vector2i_as_vector2",
+ "return_type": "godot_vector2",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_to_float",
+ "name": "godot_vector2i_aspect",
"return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_to_int",
- "return_type": "godot_int",
+ "name": "godot_vector2i_abs",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_camelcase_to_underscore",
- "return_type": "godot_string",
+ "name": "godot_vector2i_sign",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_camelcase_to_underscore_lowercased",
- "return_type": "godot_string",
+ "name": "godot_vector2i_operator_add",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_capitalize",
- "return_type": "godot_string",
+ "name": "godot_vector2i_operator_subtract",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_char_to_double",
- "return_type": "double",
+ "name": "godot_vector2i_operator_multiply_vector",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const char *", "p_what"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_char_to_int",
- "return_type": "godot_int",
+ "name": "godot_vector2i_operator_multiply_scalar",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const char *", "p_what"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_int", "p_b"]
]
},
{
- "name": "godot_string_wchar_to_int",
- "return_type": "int64_t",
+ "name": "godot_vector2i_operator_divide_vector",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const wchar_t *", "p_str"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_char_to_int_with_len",
- "return_type": "godot_int",
+ "name": "godot_vector2i_operator_divide_scalar",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const char *", "p_what"],
- ["godot_int", "p_len"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_int", "p_b"]
]
},
{
- "name": "godot_string_char_to_int64_with_len",
- "return_type": "int64_t",
+ "name": "godot_vector2i_operator_equal",
+ "return_type": "godot_bool",
"arguments": [
- ["const wchar_t *", "p_str"],
- ["int", "p_len"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_hex_to_int64",
- "return_type": "int64_t",
+ "name": "godot_vector2i_operator_less",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"],
+ ["const godot_vector2i *", "p_b"]
]
},
{
- "name": "godot_string_hex_to_int64_with_prefix",
- "return_type": "int64_t",
+ "name": "godot_vector2i_operator_neg",
+ "return_type": "godot_vector2i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_to_int64",
- "return_type": "int64_t",
+ "name": "godot_vector2i_set_x",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["godot_vector2i *", "p_self"],
+ ["const godot_int", "p_x"]
]
},
{
- "name": "godot_string_unicode_char_to_double",
- "return_type": "double",
+ "name": "godot_vector2i_set_y",
+ "return_type": "void",
"arguments": [
- ["const wchar_t *", "p_str"],
- ["const wchar_t **", "r_end"]
+ ["godot_vector2i *", "p_self"],
+ ["const godot_int", "p_y"]
]
},
{
- "name": "godot_string_get_slice_count",
+ "name": "godot_vector2i_get_x",
"return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_get_slice",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["godot_string", "p_splitter"],
- ["godot_int", "p_slice"]
- ]
- },
- {
- "name": "godot_string_get_slicec",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["wchar_t", "p_splitter"],
- ["godot_int", "p_slice"]
- ]
- },
- {
- "name": "godot_string_split",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_split_allow_empty",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_split_floats",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_split_floats_allows_empty",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_split_floats_mk",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_splitters"]
- ]
- },
- {
- "name": "godot_string_split_floats_mk_allows_empty",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_splitters"]
- ]
- },
- {
- "name": "godot_string_split_ints",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_split_ints_allows_empty",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_splitter"]
- ]
- },
- {
- "name": "godot_string_split_ints_mk",
- "return_type": "godot_array",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_splitters"]
- ]
- },
- {
- "name": "godot_string_split_ints_mk_allows_empty",
- "return_type": "godot_array",
+ "name": "godot_vector2i_get_y",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_array *", "p_splitters"]
+ ["const godot_vector2i *", "p_self"]
]
},
{
- "name": "godot_string_split_spaces",
- "return_type": "godot_array",
+ "name": "godot_vector3_as_vector3i",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_char_lowercase",
- "return_type": "wchar_t",
+ "name": "godot_vector3_sign",
+ "return_type": "godot_vector3",
"arguments": [
- ["wchar_t", "p_char"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_char_uppercase",
- "return_type": "wchar_t",
+ "name": "godot_vector3_move_toward",
+ "return_type": "godot_vector3",
"arguments": [
- ["wchar_t", "p_char"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_to"],
+ ["const godot_real", "p_delta"]
]
},
{
- "name": "godot_string_to_lower",
- "return_type": "godot_string",
+ "name": "godot_vector3_direction_to",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_to"]
]
},
{
- "name": "godot_string_to_upper",
- "return_type": "godot_string",
+ "name": "godot_vector3_new",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["godot_vector3 *", "r_dest"],
+ ["const godot_real", "p_x"],
+ ["const godot_real", "p_y"],
+ ["const godot_real", "p_z"]
]
},
{
- "name": "godot_string_get_basename",
+ "name": "godot_vector3_as_string",
"return_type": "godot_string",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_get_extension",
- "return_type": "godot_string",
+ "name": "godot_vector3_min_axis",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_left",
- "return_type": "godot_string",
+ "name": "godot_vector3_max_axis",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_pos"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_ord_at",
- "return_type": "wchar_t",
+ "name": "godot_vector3_length",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_idx"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_plus_file",
- "return_type": "godot_string",
+ "name": "godot_vector3_length_squared",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_file"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_right",
- "return_type": "godot_string",
+ "name": "godot_vector3_is_normalized",
+ "return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_pos"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_strip_edges",
- "return_type": "godot_string",
+ "name": "godot_vector3_normalized",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_bool", "p_left"],
- ["godot_bool", "p_right"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_strip_escapes",
- "return_type": "godot_string",
+ "name": "godot_vector3_inverse",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_erase",
- "return_type": "void",
+ "name": "godot_vector3_snapped",
+ "return_type": "godot_vector3",
"arguments": [
- ["godot_string *", "p_self"],
- ["godot_int", "p_pos"],
- ["godot_int", "p_chars"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_by"]
]
},
{
- "name": "godot_string_ascii",
- "return_type": "godot_char_string",
+ "name": "godot_vector3_rotated",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_axis"],
+ ["const godot_real", "p_phi"]
]
},
{
- "name": "godot_string_ascii_extended",
- "return_type": "godot_char_string",
+ "name": "godot_vector3_lerp",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"],
+ ["const godot_real", "p_t"]
]
},
{
- "name": "godot_string_utf8",
- "return_type": "godot_char_string",
+ "name": "godot_vector3_cubic_interpolate",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["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"]
]
},
{
- "name": "godot_string_parse_utf8",
- "return_type": "godot_bool",
+ "name": "godot_vector3_dot",
+ "return_type": "godot_real",
"arguments": [
- ["godot_string *", "p_self"],
- ["const char *", "p_utf8"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_parse_utf8_with_len",
- "return_type": "godot_bool",
+ "name": "godot_vector3_cross",
+ "return_type": "godot_vector3",
"arguments": [
- ["godot_string *", "p_self"],
- ["const char *", "p_utf8"],
- ["godot_int", "p_len"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_chars_to_utf8",
- "return_type": "godot_string",
+ "name": "godot_vector3_outer",
+ "return_type": "godot_basis",
"arguments": [
- ["const char *", "p_utf8"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_chars_to_utf8_with_len",
- "return_type": "godot_string",
+ "name": "godot_vector3_to_diagonal_matrix",
+ "return_type": "godot_basis",
"arguments": [
- ["const char *", "p_utf8"],
- ["godot_int", "p_len"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_hash",
- "return_type": "uint32_t",
+ "name": "godot_vector3_abs",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_hash64",
- "return_type": "uint64_t",
+ "name": "godot_vector3_floor",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_hash_chars",
- "return_type": "uint32_t",
+ "name": "godot_vector3_ceil",
+ "return_type": "godot_vector3",
"arguments": [
- ["const char *", "p_cstr"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_hash_chars_with_len",
- "return_type": "uint32_t",
+ "name": "godot_vector3_distance_to",
+ "return_type": "godot_real",
"arguments": [
- ["const char *", "p_cstr"],
- ["godot_int", "p_len"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_hash_utf8_chars",
- "return_type": "uint32_t",
+ "name": "godot_vector3_distance_squared_to",
+ "return_type": "godot_real",
"arguments": [
- ["const wchar_t *", "p_str"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_hash_utf8_chars_with_len",
- "return_type": "uint32_t",
+ "name": "godot_vector3_angle_to",
+ "return_type": "godot_real",
"arguments": [
- ["const wchar_t *", "p_str"],
- ["godot_int", "p_len"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_to"]
]
},
{
- "name": "godot_string_md5_buffer",
- "return_type": "godot_packed_byte_array",
+ "name": "godot_vector3_slide",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_n"]
]
},
{
- "name": "godot_string_md5_text",
- "return_type": "godot_string",
+ "name": "godot_vector3_bounce",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_n"]
]
},
{
- "name": "godot_string_sha256_buffer",
- "return_type": "godot_packed_byte_array",
+ "name": "godot_vector3_reflect",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_n"]
]
},
{
- "name": "godot_string_sha256_text",
- "return_type": "godot_string",
+ "name": "godot_vector3_operator_add",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_empty",
- "return_type": "godot_bool",
+ "name": "godot_vector3_operator_subtract",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_get_base_dir",
- "return_type": "godot_string",
+ "name": "godot_vector3_operator_multiply_vector",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_get_file",
- "return_type": "godot_string",
+ "name": "godot_vector3_operator_multiply_scalar",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_real", "p_b"]
]
},
{
- "name": "godot_string_humanize_size",
- "return_type": "godot_string",
+ "name": "godot_vector3_operator_divide_vector",
+ "return_type": "godot_vector3",
"arguments": [
- ["size_t", "p_size"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_is_abs_path",
- "return_type": "godot_bool",
+ "name": "godot_vector3_operator_divide_scalar",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_real", "p_b"]
]
},
{
- "name": "godot_string_is_rel_path",
+ "name": "godot_vector3_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_is_resource_file",
+ "name": "godot_vector3_operator_less",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"]
- ]
- },
- {
- "name": "godot_string_path_to",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_path"]
- ]
- },
- {
- "name": "godot_string_path_to_file",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"],
- ["const godot_string *", "p_path"]
- ]
- },
- {
- "name": "godot_string_simplify_path",
- "return_type": "godot_string",
- "arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_b"]
]
},
{
- "name": "godot_string_c_escape",
- "return_type": "godot_string",
+ "name": "godot_vector3_operator_neg",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"]
]
},
{
- "name": "godot_string_c_escape_multiline",
- "return_type": "godot_string",
+ "name": "godot_vector3_set_axis",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["godot_vector3 *", "p_self"],
+ ["const godot_vector3_axis", "p_axis"],
+ ["const godot_real", "p_val"]
]
},
{
- "name": "godot_string_c_unescape",
- "return_type": "godot_string",
+ "name": "godot_vector3_get_axis",
+ "return_type": "godot_real",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3_axis", "p_axis"]
]
},
{
- "name": "godot_string_http_escape",
- "return_type": "godot_string",
+ "name": "godot_vector3i_new",
+ "return_type": "void",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["godot_vector3i *", "r_dest"],
+ ["const godot_int", "p_x"],
+ ["const godot_int", "p_y"],
+ ["const godot_int", "p_z"]
]
},
{
- "name": "godot_string_http_unescape",
+ "name": "godot_vector3i_as_string",
"return_type": "godot_string",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_json_escape",
- "return_type": "godot_string",
+ "name": "godot_vector3i_as_vector3",
+ "return_type": "godot_vector3",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_word_wrap",
- "return_type": "godot_string",
+ "name": "godot_vector3i_min_axis",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_int", "p_chars_per_line"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_xml_escape",
- "return_type": "godot_string",
+ "name": "godot_vector3i_max_axis",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_xml_escape_with_quotes",
- "return_type": "godot_string",
+ "name": "godot_vector3i_abs",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_xml_unescape",
- "return_type": "godot_string",
+ "name": "godot_vector3i_sign",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_percent_decode",
- "return_type": "godot_string",
+ "name": "godot_vector3i_operator_add",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_percent_encode",
- "return_type": "godot_string",
+ "name": "godot_vector3i_operator_subtract",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_is_valid_float",
- "return_type": "godot_bool",
+ "name": "godot_vector3i_operator_multiply_vector",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_is_valid_hex_number",
- "return_type": "godot_bool",
+ "name": "godot_vector3i_operator_multiply_scalar",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"],
- ["godot_bool", "p_with_prefix"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_int", "p_b"]
]
},
{
- "name": "godot_string_is_valid_html_color",
- "return_type": "godot_bool",
+ "name": "godot_vector3i_operator_divide_vector",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_is_valid_identifier",
- "return_type": "godot_bool",
+ "name": "godot_vector3i_operator_divide_scalar",
+ "return_type": "godot_vector3i",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_int", "p_b"]
]
},
{
- "name": "godot_string_is_valid_integer",
+ "name": "godot_vector3i_operator_equal",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_is_valid_ip_address",
+ "name": "godot_vector3i_operator_less",
"return_type": "godot_bool",
"arguments": [
- ["const godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3i *", "p_b"]
]
},
{
- "name": "godot_string_destroy",
- "return_type": "void",
+ "name": "godot_vector3i_operator_neg",
+ "return_type": "godot_vector3i",
"arguments": [
- ["godot_string *", "p_self"]
+ ["const godot_vector3i *", "p_self"]
]
},
{
- "name": "godot_string_name_new",
+ "name": "godot_vector3i_set_axis",
"return_type": "void",
"arguments": [
- ["godot_string_name *", "r_dest"],
- ["const godot_string *", "p_name"]
- ]
- },
- {
- "name": "godot_string_name_new_data",
- "return_type": "void",
- "arguments": [
- ["godot_string_name *", "r_dest"],
- ["const char *", "p_name"]
+ ["godot_vector3i *", "p_self"],
+ ["const godot_vector3_axis", "p_axis"],
+ ["const godot_int", "p_val"]
]
},
{
- "name": "godot_string_name_get_name",
- "return_type": "godot_string",
+ "name": "godot_vector3i_get_axis",
+ "return_type": "godot_int",
"arguments": [
- ["const godot_string_name *", "p_self"]
+ ["const godot_vector3i *", "p_self"],
+ ["const godot_vector3_axis", "p_axis"]
]
},
{
- "name": "godot_string_name_get_hash",
- "return_type": "uint32_t",
+ "name": "godot_global_get_singleton",
+ "return_type": "godot_object *",
"arguments": [
- ["const godot_string_name *", "p_self"]
+ ["char *", "p_name"]
]
},
{
- "name": "godot_string_name_get_data_unique_pointer",
- "return_type": "const void *",
+ "name": "godot_get_class_tag",
+ "return_type": "void *",
"arguments": [
- ["const godot_string_name *", "p_self"]
+ ["const godot_string_name *", "p_class"]
]
},
{
- "name": "godot_string_name_operator_equal",
- "return_type": "godot_bool",
+ "name": "godot_object_cast_to",
+ "return_type": "godot_object *",
"arguments": [
- ["const godot_string_name *", "p_self"],
- ["const godot_string_name *", "p_other"]
+ ["const godot_object *", "p_object"],
+ ["void *", "p_class_tag"]
]
},
{
- "name": "godot_string_name_operator_less",
- "return_type": "godot_bool",
+ "name": "godot_object_get_instance_id",
+ "return_type": "uint64_t",
"arguments": [
- ["const godot_string_name *", "p_self"],
- ["const godot_string_name *", "p_other"]
+ ["const godot_object *", "p_object"]
]
},
{
- "name": "godot_string_name_destroy",
- "return_type": "void",
+ "name": "godot_instance_from_id",
+ "return_type": "godot_object *",
"arguments": [
- ["godot_string_name *", "p_self"]
+ ["uint64_t", "p_instance_id"]
]
},
{
@@ -5579,13 +7240,6 @@
]
},
{
- "name": "godot_global_get_singleton",
- "return_type": "godot_object *",
- "arguments": [
- ["char *", "p_name"]
- ]
- },
- {
"name": "godot_method_bind_get_method",
"return_type": "godot_method_bind *",
"arguments": [
@@ -5691,132 +7345,10 @@
"name": "nativescript",
"type": "NATIVESCRIPT",
"version": {
- "major": 1,
+ "major": 4,
"minor": 0
},
- "next": {
- "type": "NATIVESCRIPT",
- "version": {
- "major": 1,
- "minor": 1
- },
- "next": null,
- "api": [
- {
- "name": "godot_nativescript_set_method_argument_information",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["const char *", "p_function_name"],
- ["int", "p_num_args"],
- ["const godot_method_arg *", "p_args"]
- ]
- },
- {
- "name": "godot_nativescript_set_class_documentation",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["godot_string", "p_documentation"]
- ]
- },
- {
- "name": "godot_nativescript_set_method_documentation",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["const char *", "p_function_name"],
- ["godot_string", "p_documentation"]
- ]
- },
- {
- "name": "godot_nativescript_set_property_documentation",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["const char *", "p_path"],
- ["godot_string", "p_documentation"]
- ]
- },
- {
- "name": "godot_nativescript_set_signal_documentation",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["const char *", "p_signal_name"],
- ["godot_string", "p_documentation"]
- ]
- },
- {
- "name": "godot_nativescript_set_global_type_tag",
- "return_type": "void",
- "arguments": [
- ["int", "p_idx"],
- ["const char *", "p_name"],
- ["const void *", "p_type_tag"]
- ]
- },
- {
- "name": "godot_nativescript_get_global_type_tag",
- "return_type": "const void *",
- "arguments": [
- ["int", "p_idx"],
- ["const char *", "p_name"]
- ]
- },
- {
- "name": "godot_nativescript_set_type_tag",
- "return_type": "void",
- "arguments": [
- ["void *", "p_gdnative_handle"],
- ["const char *", "p_name"],
- ["const void *", "p_type_tag"]
- ]
- },
- {
- "name": "godot_nativescript_get_type_tag",
- "return_type": "const void *",
- "arguments": [
- ["const godot_object *", "p_object"]
- ]
- },
- {
- "name": "godot_nativescript_register_instance_binding_data_functions",
- "return_type": "int",
- "arguments": [
- ["godot_instance_binding_functions", "p_binding_functions"]
- ]
- },
- {
- "name": "godot_nativescript_unregister_instance_binding_data_functions",
- "return_type": "void",
- "arguments": [
- ["int", "p_idx"]
- ]
- },
- {
- "name": "godot_nativescript_get_instance_binding_data",
- "return_type": "void *",
- "arguments": [
- ["int", "p_idx"],
- ["godot_object *", "p_object"]
- ]
- },
- {
- "name": "godot_nativescript_profiling_add_data",
- "return_type": "void",
- "arguments": [
- ["const char *", "p_signature"],
- ["uint64_t", "p_line"]
- ]
- }
- ]
- },
+ "next": null,
"api": [
{
"name": "godot_nativescript_register_class",
@@ -5825,8 +7357,8 @@
["void *", "p_gdnative_handle"],
["const char *", "p_name"],
["const char *", "p_base"],
- ["godot_instance_create_func", "p_create_func"],
- ["godot_instance_destroy_func", "p_destroy_func"]
+ ["godot_nativescript_instance_create_func", "p_create_func"],
+ ["godot_nativescript_instance_destroy_func", "p_destroy_func"]
]
},
{
@@ -5836,8 +7368,8 @@
["void *", "p_gdnative_handle"],
["const char *", "p_name"],
["const char *", "p_base"],
- ["godot_instance_create_func", "p_create_func"],
- ["godot_instance_destroy_func", "p_destroy_func"]
+ ["godot_nativescript_instance_create_func", "p_create_func"],
+ ["godot_nativescript_instance_destroy_func", "p_destroy_func"]
]
},
{
@@ -5847,8 +7379,19 @@
["void *", "p_gdnative_handle"],
["const char *", "p_name"],
["const char *", "p_function_name"],
- ["godot_method_attributes", "p_attr"],
- ["godot_instance_method", "p_method"]
+ ["godot_nativescript_method_attributes", "p_attr"],
+ ["godot_nativescript_instance_method", "p_method"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_method_argument_information",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["const char *", "p_function_name"],
+ ["int", "p_num_args"],
+ ["const godot_nativescript_method_argument *", "p_args"]
]
},
{
@@ -5858,9 +7401,9 @@
["void *", "p_gdnative_handle"],
["const char *", "p_name"],
["const char *", "p_path"],
- ["godot_property_attributes *", "p_attr"],
- ["godot_property_set_func", "p_set_func"],
- ["godot_property_get_func", "p_get_func"]
+ ["godot_nativescript_property_attributes *", "p_attr"],
+ ["godot_nativescript_property_set_func", "p_set_func"],
+ ["godot_nativescript_property_get_func", "p_get_func"]
]
},
{
@@ -5869,7 +7412,7 @@
"arguments": [
["void *", "p_gdnative_handle"],
["const char *", "p_name"],
- ["const godot_signal *", "p_signal"]
+ ["const godot_nativescript_signal *", "p_signal"]
]
},
{
@@ -5878,6 +7421,108 @@
"arguments": [
["godot_object *", "p_instance"]
]
+ },
+ {
+ "name": "godot_nativescript_set_class_documentation",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["godot_string", "p_documentation"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_method_documentation",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["const char *", "p_function_name"],
+ ["godot_string", "p_documentation"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_property_documentation",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["const char *", "p_path"],
+ ["godot_string", "p_documentation"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_signal_documentation",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["const char *", "p_signal_name"],
+ ["godot_string", "p_documentation"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_global_type_tag",
+ "return_type": "void",
+ "arguments": [
+ ["int", "p_idx"],
+ ["const char *", "p_name"],
+ ["const void *", "p_type_tag"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_get_global_type_tag",
+ "return_type": "const void *",
+ "arguments": [
+ ["int", "p_idx"],
+ ["const char *", "p_name"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_set_type_tag",
+ "return_type": "void",
+ "arguments": [
+ ["void *", "p_gdnative_handle"],
+ ["const char *", "p_name"],
+ ["const void *", "p_type_tag"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_get_type_tag",
+ "return_type": "const void *",
+ "arguments": [
+ ["const godot_object *", "p_object"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_register_instance_binding_data_functions",
+ "return_type": "int",
+ "arguments": [
+ ["godot_nativescript_instance_binding_functions", "p_binding_functions"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_unregister_instance_binding_data_functions",
+ "return_type": "void",
+ "arguments": [
+ ["int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_get_instance_binding_data",
+ "return_type": "void *",
+ "arguments": [
+ ["int", "p_idx"],
+ ["godot_object *", "p_object"]
+ ]
+ },
+ {
+ "name": "godot_nativescript_profiling_add_data",
+ "return_type": "void",
+ "arguments": [
+ ["const char *", "p_signature"],
+ ["uint64_t", "p_line"]
+ ]
}
]
},
@@ -6071,42 +7716,10 @@
"name": "net",
"type": "NET",
"version": {
- "major": 3,
- "minor": 1
- },
- "next": {
- "type": "NET",
- "version": {
- "major": 3,
- "minor": 2
- },
- "next": null,
- "api": [
- {
- "name": "godot_net_set_webrtc_library",
- "return_type": "godot_error",
- "arguments": [
- ["const godot_net_webrtc_library *", "p_library"]
- ]
- },
- {
- "name": "godot_net_bind_webrtc_peer_connection",
- "return_type": "void",
- "arguments": [
- ["godot_object *", "p_obj"],
- ["const godot_net_webrtc_peer_connection *", "p_interface"]
- ]
- },
- {
- "name": "godot_net_bind_webrtc_data_channel",
- "return_type": "void",
- "arguments": [
- ["godot_object *", "p_obj"],
- ["const godot_net_webrtc_data_channel *", "p_interface"]
- ]
- }
- ]
+ "major": 4,
+ "minor": 0
},
+ "next": null,
"api": [
{
"name": "godot_net_bind_stream_peer",
@@ -6131,6 +7744,329 @@
["godot_object *", "p_obj"],
["const godot_net_multiplayer_peer *", "p_interface"]
]
+ },
+ {
+ "name": "godot_net_set_webrtc_library",
+ "return_type": "godot_error",
+ "arguments": [
+ ["const godot_net_webrtc_library *", "p_library"]
+ ]
+ },
+ {
+ "name": "godot_net_bind_webrtc_peer_connection",
+ "return_type": "void",
+ "arguments": [
+ ["godot_object *", "p_obj"],
+ ["const godot_net_webrtc_peer_connection *", "p_interface"]
+ ]
+ },
+ {
+ "name": "godot_net_bind_webrtc_data_channel",
+ "return_type": "void",
+ "arguments": [
+ ["godot_object *", "p_obj"],
+ ["const godot_net_webrtc_data_channel *", "p_interface"]
+ ]
+ }
+ ]
+ },
+ {
+ "name": "text",
+ "type": "TEXT",
+ "version": {
+ "major": 1,
+ "minor": 0
+ },
+ "next": null,
+ "api": [
+ {
+ "name": "godot_text_register_interface",
+ "return_type": "void",
+ "arguments": [
+ ["const godot_text_interface_gdnative *", "p_interface"],
+ ["const godot_string *", "p_name"],
+ ["uint32_t", "p_features"]
+ ]
+ },
+ {
+ "name": "godot_glyph_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_range",
+ "return_type": "godot_vector2i",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_range",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["const godot_vector2i *", "p_range"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_count",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_count",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_int", "p_count"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_repeat",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_repeat",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_int", "p_repeat"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_flags",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_flags",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_int", "p_flags"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_offset",
+ "return_type": "godot_vector2",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_offset",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["const godot_vector2 *", "p_offset"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_advance",
+ "return_type": "godot_real",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_advance",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_real", "p_advance"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_font",
+ "return_type": "godot_rid",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_font",
+ "return_type": "void ",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_rid *", "p_font"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_font_size",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_font_size",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_glyph_get_index",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_glyph *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_glyph_set_index",
+ "return_type": "void",
+ "arguments": [
+ ["godot_glyph *", "p_self"],
+ ["godot_int", "p_index"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_new",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "r_dest"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_new_copy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "r_dest"],
+ ["const godot_packed_glyph_array *", "p_src"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_is_empty",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["const godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_append",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_glyph *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_append_array",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_packed_glyph_array *", "p_array"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_insert",
+ "return_type": "godot_error",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const godot_glyph *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_has",
+ "return_type": "godot_bool",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_glyph *", "p_value"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_sort",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_invert",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_push_back",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_glyph *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_remove",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_resize",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_int", "p_size"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_ptr",
+ "return_type": "const godot_glyph *",
+ "arguments": [
+ ["const godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_ptrw",
+ "return_type": "godot_glyph *",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_set",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"],
+ ["const godot_int", "p_idx"],
+ ["const godot_glyph *", "p_data"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_get",
+ "return_type": "godot_glyph",
+ "arguments": [
+ ["const godot_packed_glyph_array *", "p_self"],
+ ["const godot_int", "p_idx"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_size",
+ "return_type": "godot_int",
+ "arguments": [
+ ["const godot_packed_glyph_array *", "p_self"]
+ ]
+ },
+ {
+ "name": "godot_packed_glyph_array_destroy",
+ "return_type": "void",
+ "arguments": [
+ ["godot_packed_glyph_array *", "p_self"]
+ ]
}
]
}
diff --git a/modules/gdnative/gdnative_builders.py b/modules/gdnative/gdnative_builders.py
index 620935795f..d03298d7a9 100644
--- a/modules/gdnative/gdnative_builders.py
+++ b/modules/gdnative/gdnative_builders.py
@@ -24,6 +24,7 @@ def _build_gdnative_api_struct_header(api):
"#include <net/godot_net.h>",
"#include <pluginscript/godot_pluginscript.h>",
"#include <videodecoder/godot_videodecoder.h>",
+ "#include <text/godot_text.h>",
"",
"#ifdef __cplusplus",
'extern "C" {',
@@ -74,7 +75,7 @@ def _build_gdnative_api_struct_header(api):
ret_val += [
"typedef struct godot_gdnative_core_"
- + ("{0}_{1}".format(core["version"]["major"], core["version"]["minor"]))
+ + "{0}_{1}".format(core["version"]["major"], core["version"]["minor"])
+ "_api_struct {",
"\tunsigned int type;",
"\tgodot_gdnative_api_version version;",
@@ -185,7 +186,7 @@ def _build_gdnative_api_struct_source(api):
ret_val += [
"extern const godot_gdnative_core_"
- + ("{0}_{1}_api_struct api_{0}_{1}".format(core["version"]["major"], core["version"]["minor"]))
+ + "{0}_{1}_api_struct api_{0}_{1}".format(core["version"]["major"], core["version"]["minor"])
+ " = {",
"\tGDNATIVE_" + core["type"] + ",",
"\t{" + str(core["version"]["major"]) + ", " + str(core["version"]["minor"]) + "},",
@@ -228,7 +229,16 @@ def _build_gdnative_api_struct_source(api):
"extern const godot_gdnative_core_api_struct api_struct = {",
"\tGDNATIVE_" + api["core"]["type"] + ",",
"\t{" + str(api["core"]["version"]["major"]) + ", " + str(api["core"]["version"]["minor"]) + "},",
- "\t(const godot_gdnative_api_struct *)&api_1_1,",
+ "\t"
+ + (
+ "nullptr, "
+ if not api["core"]["next"]
+ else (
+ "(const godot_gdnative_api_struct *)& api_{0}_{1},".format(
+ api["core"]["next"]["version"]["major"], api["core"]["next"]["version"]["minor"]
+ )
+ )
+ ),
"\t" + str(len(api["extensions"])) + ",",
"\tgdnative_extensions_pointers,",
]
diff --git a/modules/gdnative/gdnative_library_editor_plugin.cpp b/modules/gdnative/gdnative_library_editor_plugin.cpp
index 10ddd79d3a..d3cca5b1be 100644
--- a/modules/gdnative/gdnative_library_editor_plugin.cpp
+++ b/modules/gdnative/gdnative_library_editor_plugin.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,7 +40,6 @@ void GDNativeLibraryEditor::edit(Ref<GDNativeLibrary> p_library) {
for (Map<String, NativePlatformConfig>::Element *E = platforms.front(); E; E = E->next()) {
for (List<String>::Element *it = E->value().entries.front(); it; it = it->next()) {
-
String target = E->key() + "." + it->get();
TargetConfig ecfg;
ecfg.library = config->get_value("entry", target, "");
@@ -56,19 +55,17 @@ void GDNativeLibraryEditor::_bind_methods() {
}
void GDNativeLibraryEditor::_update_tree() {
-
tree->clear();
TreeItem *root = tree->create_item();
PopupMenu *filter_list = filter->get_popup();
String text = "";
for (int i = 0; i < filter_list->get_item_count(); i++) {
-
if (!filter_list->is_item_checked(i)) {
continue;
}
Map<String, NativePlatformConfig>::Element *E = platforms.find(filter_list->get_item_metadata(i));
- if (!text.empty()) {
+ if (!text.is_empty()) {
text += ", ";
}
text += E->get().name;
@@ -84,7 +81,6 @@ void GDNativeLibraryEditor::_update_tree() {
platform->set_expand_right(0, true);
for (List<String>::Element *it = E->value().entries.front(); it; it = it->next()) {
-
String target = E->key() + "." + it->get();
TreeItem *bit = tree->create_item(platform);
@@ -95,7 +91,7 @@ void GDNativeLibraryEditor::_update_tree() {
bit->add_button(1, get_theme_icon("Folder", "EditorIcons"), BUTTON_SELECT_LIBRARY, false, TTR("Select the dynamic library for this entry"));
String file = entry_configs[target].library;
- if (!file.empty()) {
+ if (!file.is_empty()) {
bit->add_button(1, get_theme_icon("Clear", "EditorIcons"), BUTTON_CLEAR_LIBRARY, false, TTR("Clear"));
}
bit->set_text(1, file);
@@ -125,24 +121,32 @@ void GDNativeLibraryEditor::_update_tree() {
}
void GDNativeLibraryEditor::_on_item_button(Object *item, int column, int id) {
-
String target = Object::cast_to<TreeItem>(item)->get_metadata(0);
String platform = target.substr(0, target.find("."));
String entry = target.substr(platform.length() + 1, target.length());
String section = (id == BUTTON_SELECT_DEPENDENCES || id == BUTTON_CLEAR_DEPENDENCES) ? "dependencies" : "entry";
if (id == BUTTON_SELECT_LIBRARY || id == BUTTON_SELECT_DEPENDENCES) {
-
+ TreeItem *treeItem = Object::cast_to<TreeItem>(item)->get_parent();
EditorFileDialog::FileMode mode = EditorFileDialog::FILE_MODE_OPEN_FILE;
- if (id == BUTTON_SELECT_DEPENDENCES)
+ if (id == BUTTON_SELECT_DEPENDENCES) {
mode = EditorFileDialog::FILE_MODE_OPEN_FILES;
+ } else if (treeItem->get_text(0) == "iOS") {
+ mode = EditorFileDialog::FILE_MODE_OPEN_ANY;
+ }
file_dialog->set_meta("target", target);
file_dialog->set_meta("section", section);
file_dialog->clear_filters();
- file_dialog->add_filter(Object::cast_to<TreeItem>(item)->get_parent()->get_metadata(0));
+
+ String filter_string = treeItem->get_metadata(0);
+ Vector<String> filters = filter_string.split(",", false, 0);
+ for (int i = 0; i < filters.size(); i++) {
+ file_dialog->add_filter(filters[i]);
+ }
+
file_dialog->set_file_mode(mode);
- file_dialog->popup_centered_ratio();
+ file_dialog->popup_file_dialog();
} else if (id == BUTTON_CLEAR_LIBRARY) {
_set_target_value(section, target, "");
@@ -156,24 +160,20 @@ void GDNativeLibraryEditor::_on_item_button(Object *item, int column, int id) {
}
void GDNativeLibraryEditor::_on_library_selected(const String &file) {
-
_set_target_value(file_dialog->get_meta("section"), file_dialog->get_meta("target"), file);
}
void GDNativeLibraryEditor::_on_dependencies_selected(const PackedStringArray &files) {
-
_set_target_value(file_dialog->get_meta("section"), file_dialog->get_meta("target"), files);
}
void GDNativeLibraryEditor::_on_filter_selected(int index) {
-
PopupMenu *filter_list = filter->get_popup();
filter_list->set_item_checked(index, !filter_list->is_item_checked(index));
_update_tree();
}
void GDNativeLibraryEditor::_on_item_collapsed(Object *p_item) {
-
TreeItem *item = Object::cast_to<TreeItem>(p_item);
String name = item->get_text(0);
@@ -185,7 +185,6 @@ void GDNativeLibraryEditor::_on_item_collapsed(Object *p_item) {
}
void GDNativeLibraryEditor::_on_item_activated() {
-
TreeItem *item = tree->get_selected();
if (item && tree->get_selected_column() == 0 && item->get_metadata(0).get_type() == Variant::NIL) {
new_architecture_dialog->set_meta("platform", item->get_metadata(1));
@@ -194,29 +193,27 @@ void GDNativeLibraryEditor::_on_item_activated() {
}
void GDNativeLibraryEditor::_on_create_new_entry() {
-
String platform = new_architecture_dialog->get_meta("platform");
String entry = new_architecture_input->get_text().strip_edges();
- if (!entry.empty()) {
+ if (!entry.is_empty()) {
platforms[platform].entries.push_back(entry);
_update_tree();
}
}
void GDNativeLibraryEditor::_set_target_value(const String &section, const String &target, Variant file) {
- if (section == "entry")
+ if (section == "entry") {
entry_configs[target].library = file;
- else if (section == "dependencies")
+ } else if (section == "dependencies") {
entry_configs[target].dependencies = file;
+ }
_translate_to_config_file();
_update_tree();
}
void GDNativeLibraryEditor::_erase_entry(const String &platform, const String &entry) {
-
if (platforms.has(platform)) {
if (List<String>::Element *E = platforms[platform].entries.find(entry)) {
-
String target = platform + "." + entry;
platforms[platform].entries.erase(E);
@@ -243,19 +240,17 @@ void GDNativeLibraryEditor::_move_entry(const String &platform, const String &en
}
void GDNativeLibraryEditor::_translate_to_config_file() {
-
if (!library.is_null()) {
-
Ref<ConfigFile> config = library->get_config_file();
config->erase_section("entry");
config->erase_section("dependencies");
for (Map<String, NativePlatformConfig>::Element *E = platforms.front(); E; E = E->next()) {
for (List<String>::Element *it = E->value().entries.front(); it; it = it->next()) {
-
String target = E->key() + "." + it->get();
- if (entry_configs[target].library.empty() && entry_configs[target].dependencies.empty())
+ if (entry_configs[target].library.is_empty() && entry_configs[target].dependencies.is_empty()) {
continue;
+ }
config->set_value("entry", target, entry_configs[target].library);
config->set_value("dependencies", target, entry_configs[target].dependencies);
@@ -267,7 +262,6 @@ void GDNativeLibraryEditor::_translate_to_config_file() {
}
GDNativeLibraryEditor::GDNativeLibraryEditor() {
-
{ // Define platforms
NativePlatformConfig platform_windows;
platform_windows.name = "Windows";
@@ -298,7 +292,7 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() {
platforms["Haiku"] = platform_haiku;
NativePlatformConfig platform_uwp;
- platform_uwp.name = "Windows Universal";
+ platform_uwp.name = "UWP";
platform_uwp.entries.push_back("arm");
platform_uwp.entries.push_back("32");
platform_uwp.entries.push_back("64");
@@ -314,23 +308,26 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() {
platform_android.library_extension = "*.so";
platforms["Android"] = platform_android;
- // TODO: Javascript platform is not supported yet
- // NativePlatformConfig platform_html5;
- // platform_html5.name = "HTML5";
- // platform_html5.library_extension = "*.wasm";
- // platforms["Javascript"] = platform_html5;
+ NativePlatformConfig platform_html5;
+ platform_html5.name = "HTML5";
+ platform_html5.entries.push_back("wasm32");
+ platform_html5.library_extension = "*.wasm";
+ platforms["HTML5"] = platform_html5;
NativePlatformConfig platform_ios;
platform_ios.name = "iOS";
platform_ios.entries.push_back("armv7");
platform_ios.entries.push_back("arm64");
- platform_ios.library_extension = "*.dylib";
+ platform_ios.entries.push_back("x86_64");
+ // iOS can use both Static and Dynamic libraries.
+ // Frameworks is actually a folder with files.
+ platform_ios.library_extension = "*.framework; Framework, *.xcframework; Binary Framework, *.a; Static Library, *.dylib; Dynamic Library";
platforms["iOS"] = platform_ios;
}
VBoxContainer *container = memnew(VBoxContainer);
add_child(container);
- container->set_anchors_and_margins_preset(PRESET_WIDE);
+ container->set_anchors_and_offsets_preset(PRESET_WIDE);
HBoxContainer *hbox = memnew(HBoxContainer);
container->add_child(hbox);
@@ -375,6 +372,7 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() {
//file_dialog->set_resizable(true);
add_child(file_dialog);
file_dialog->connect("file_selected", callable_mp(this, &GDNativeLibraryEditor::_on_library_selected));
+ file_dialog->connect("dir_selected", callable_mp(this, &GDNativeLibraryEditor::_on_library_selected));
file_dialog->connect("files_selected", callable_mp(this, &GDNativeLibraryEditor::_on_dependencies_selected));
new_architecture_dialog = memnew(ConfirmationDialog);
@@ -383,37 +381,35 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() {
new_architecture_input = memnew(LineEdit);
new_architecture_dialog->add_child(new_architecture_input);
// new_architecture_dialog->set_custom_minimum_size(Vector2(300, 80) * EDSCALE);
- new_architecture_input->set_anchors_and_margins_preset(PRESET_HCENTER_WIDE, PRESET_MODE_MINSIZE, 5 * EDSCALE);
- new_architecture_dialog->get_ok()->connect("pressed", callable_mp(this, &GDNativeLibraryEditor::_on_create_new_entry));
+ new_architecture_input->set_anchors_and_offsets_preset(PRESET_HCENTER_WIDE, PRESET_MODE_MINSIZE, 5 * EDSCALE);
+ new_architecture_dialog->get_ok_button()->connect("pressed", callable_mp(this, &GDNativeLibraryEditor::_on_create_new_entry));
}
void GDNativeLibraryEditorPlugin::edit(Object *p_node) {
-
Ref<GDNativeLibrary> new_library = Object::cast_to<GDNativeLibrary>(p_node);
- if (new_library.is_valid())
+ if (new_library.is_valid()) {
library_editor->edit(new_library);
+ }
}
bool GDNativeLibraryEditorPlugin::handles(Object *p_node) const {
-
return p_node->is_class("GDNativeLibrary");
}
void GDNativeLibraryEditorPlugin::make_visible(bool p_visible) {
-
if (p_visible) {
button->show();
EditorNode::get_singleton()->make_bottom_panel_item_visible(library_editor);
} else {
- if (library_editor->is_visible_in_tree())
+ if (library_editor->is_visible_in_tree()) {
EditorNode::get_singleton()->hide_bottom_panel();
+ }
button->hide();
}
}
GDNativeLibraryEditorPlugin::GDNativeLibraryEditorPlugin(EditorNode *p_node) {
-
library_editor = memnew(GDNativeLibraryEditor);
library_editor->set_custom_minimum_size(Size2(0, 250 * EDSCALE));
button = p_node->add_bottom_panel_item(TTR("GDNativeLibrary"), library_editor);
diff --git a/modules/gdnative/gdnative_library_editor_plugin.h b/modules/gdnative/gdnative_library_editor_plugin.h
index b1274d08b3..184db3d817 100644
--- a/modules/gdnative/gdnative_library_editor_plugin.h
+++ b/modules/gdnative/gdnative_library_editor_plugin.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,6 @@
#include "gdnative.h"
class GDNativeLibraryEditor : public Control {
-
GDCLASS(GDNativeLibraryEditor, Control);
struct NativePlatformConfig {
@@ -94,7 +93,6 @@ public:
};
class GDNativeLibraryEditorPlugin : public EditorPlugin {
-
GDCLASS(GDNativeLibraryEditorPlugin, EditorPlugin);
GDNativeLibraryEditor *library_editor;
@@ -102,11 +100,11 @@ class GDNativeLibraryEditorPlugin : public EditorPlugin {
Button *button;
public:
- virtual String get_name() const { return "GDNativeLibrary"; }
- bool has_main_screen() const { return false; }
- virtual void edit(Object *p_node);
- virtual bool handles(Object *p_node) const;
- virtual void make_visible(bool p_visible);
+ virtual String get_name() const override { return "GDNativeLibrary"; }
+ bool has_main_screen() const override { return false; }
+ virtual void edit(Object *p_node) override;
+ virtual bool handles(Object *p_node) const override;
+ virtual void make_visible(bool p_visible) override;
GDNativeLibraryEditorPlugin(EditorNode *p_node);
};
diff --git a/modules/gdnative/gdnative_library_singleton_editor.cpp b/modules/gdnative/gdnative_library_singleton_editor.cpp
index 378339ecea..f1b4a9a81b 100644
--- a/modules/gdnative/gdnative_library_singleton_editor.cpp
+++ b/modules/gdnative/gdnative_library_singleton_editor.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
#include "editor/editor_node.h"
Set<String> GDNativeLibrarySingletonEditor::_find_singletons_recursive(EditorFileSystemDirectory *p_dir) {
-
Set<String> file_paths;
// check children
@@ -67,7 +66,6 @@ Set<String> GDNativeLibrarySingletonEditor::_find_singletons_recursive(EditorFil
}
void GDNativeLibrarySingletonEditor::_discover_singletons() {
-
EditorFileSystemDirectory *dir = EditorFileSystem::get_singleton()->get_filesystem();
Set<String> file_paths = _find_singletons_recursive(dir);
@@ -97,7 +95,6 @@ void GDNativeLibrarySingletonEditor::_discover_singletons() {
}
if (changed) {
-
ProjectSettings::get_singleton()->set("gdnative/singletons", files);
_update_libraries(); // So singleton options (i.e. disabled) updates too
ProjectSettings::get_singleton()->save();
@@ -105,7 +102,6 @@ void GDNativeLibrarySingletonEditor::_discover_singletons() {
}
void GDNativeLibrarySingletonEditor::_update_libraries() {
-
updating = true;
libraries->clear();
libraries->create_item(); // root item
@@ -139,19 +135,22 @@ void GDNativeLibrarySingletonEditor::_update_libraries() {
}
// The singletons list changed, we must update the settings
- if (updated_disabled.size() != singletons_disabled.size())
+ if (updated_disabled.size() != singletons_disabled.size()) {
ProjectSettings::get_singleton()->set("gdnative/singletons_disabled", updated_disabled);
+ }
updating = false;
}
void GDNativeLibrarySingletonEditor::_item_edited() {
- if (updating)
+ if (updating) {
return;
+ }
TreeItem *item = libraries->get_edited();
- if (!item)
+ if (!item) {
return;
+ }
bool enabled = item->get_range(1);
String path = item->get_metadata(0);
@@ -169,8 +168,9 @@ void GDNativeLibrarySingletonEditor::_item_edited() {
if (enabled) {
disabled_paths.erase(path);
} else {
- if (disabled_paths.find(path) == -1)
+ if (disabled_paths.find(path) == -1) {
disabled_paths.push_back(path);
+ }
}
undo_redo->create_action(enabled ? TTR("Enabled GDNative Singleton") : TTR("Disabled GDNative Singleton"));
@@ -182,7 +182,6 @@ void GDNativeLibrarySingletonEditor::_item_edited() {
}
void GDNativeLibrarySingletonEditor::_notification(int p_what) {
-
if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (is_visible_in_tree()) {
_update_libraries();
@@ -191,7 +190,6 @@ void GDNativeLibrarySingletonEditor::_notification(int p_what) {
}
void GDNativeLibrarySingletonEditor::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("_update_libraries"), &GDNativeLibrarySingletonEditor::_update_libraries);
}
diff --git a/modules/gdnative/gdnative_library_singleton_editor.h b/modules/gdnative/gdnative_library_singleton_editor.h
index 1a213d8094..5bb823d920 100644
--- a/modules/gdnative/gdnative_library_singleton_editor.h
+++ b/modules/gdnative/gdnative_library_singleton_editor.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/icons/GDNativeLibrary.svg b/modules/gdnative/icons/GDNativeLibrary.svg
index b494c7af6e..0ddfd4e6f2 100644
--- a/modules/gdnative/icons/GDNativeLibrary.svg
+++ b/modules/gdnative/icons/GDNativeLibrary.svg
@@ -1,5 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625v2l2.2578.56445a5 5 0 0 0 .2793.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 .68555.28516l.5625 2.2539v-5.2695a2 2 0 0 1 -1-1.7305 2 2 0 0 1 1-1.7285v-.27148h1 4.5762a5 5 0 0 0 -.11328-.25195l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.5625-2.2539h-2zm2 7v1 5 1h5c.55228 0 1-.4477 1-1v-5c0-.5523-.44772-1-1-1v4l-1-1-1 1v-4z" fill="#e0e0e0"/></svg>
diff --git a/modules/gdnative/icons/NativeScript.svg b/modules/gdnative/icons/NativeScript.svg
index fb9e135627..2224b36b29 100644
--- a/modules/gdnative/icons/NativeScript.svg
+++ b/modules/gdnative/icons/NativeScript.svg
@@ -1,5 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625h3v1 1h2v-.95117a2 2 0 0 1 0-.048828 2 2 0 0 1 2-2 2 2 0 0 1 2 2v1h5v-2l-2.2578-.56445a5 5 0 0 0 -.2793-.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.5625-2.2539h-2zm-6 7v4 4h2a3 3 0 0 0 3-3 3 3 0 0 0 -3-3v-2zm6 0v2h2v-2zm3 2v6h2v-4a1 1 0 0 1 1 1v3h2v-3a3 3 0 0 0 -3-3zm-7 2a1 1 0 0 1 1 1 1 1 0 0 1 -1 1zm4 0v4h2v-4z" fill="#e0e0e0"/></svg>
diff --git a/modules/gdnative/include/android/godot_android.h b/modules/gdnative/include/android/godot_android.h
index 45d4eaff37..867ef9e03a 100644
--- a/modules/gdnative/include/android/godot_android.h
+++ b/modules/gdnative/include/android/godot_android.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/aabb.h b/modules/gdnative/include/gdnative/aabb.h
index 9f41e9d4c6..daf5ebfdd8 100644
--- a/modules/gdnative/include/gdnative/aabb.h
+++ b/modules/gdnative/include/gdnative/aabb.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -69,6 +69,8 @@ void GDAPI godot_aabb_set_size(const godot_aabb *p_self, const godot_vector3 *p_
godot_string GDAPI godot_aabb_as_string(const godot_aabb *p_self);
+godot_aabb GDAPI godot_aabb_abs(const godot_aabb *p_self);
+
godot_real GDAPI godot_aabb_get_area(const godot_aabb *p_self);
godot_bool GDAPI godot_aabb_has_no_area(const godot_aabb *p_self);
diff --git a/modules/gdnative/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h
index e3114e9348..9cc5bdfad5 100644
--- a/modules/gdnative/include/gdnative/array.h
+++ b/modules/gdnative/include/gdnative/array.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -51,7 +51,7 @@ typedef struct {
}
#endif
-#include <gdnative/pool_arrays.h>
+#include <gdnative/packed_arrays.h>
#include <gdnative/variant.h>
#include <gdnative/gdnative.h>
@@ -65,9 +65,12 @@ void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src);
void GDAPI godot_array_new_packed_color_array(godot_array *r_dest, const godot_packed_color_array *p_pca);
void GDAPI godot_array_new_packed_vector3_array(godot_array *r_dest, const godot_packed_vector3_array *p_pv3a);
void GDAPI godot_array_new_packed_vector2_array(godot_array *r_dest, const godot_packed_vector2_array *p_pv2a);
+void GDAPI godot_array_new_packed_vector2i_array(godot_array *r_dest, const godot_packed_vector2i_array *p_pv2a);
void GDAPI godot_array_new_packed_string_array(godot_array *r_dest, const godot_packed_string_array *p_psa);
-void GDAPI godot_array_new_packed_real_array(godot_array *r_dest, const godot_packed_real_array *p_pra);
-void GDAPI godot_array_new_packed_int_array(godot_array *r_dest, const godot_packed_int_array *p_pia);
+void GDAPI godot_array_new_packed_float32_array(godot_array *r_dest, const godot_packed_float32_array *p_pra);
+void GDAPI godot_array_new_packed_float64_array(godot_array *r_dest, const godot_packed_float64_array *p_pra);
+void GDAPI godot_array_new_packed_int32_array(godot_array *r_dest, const godot_packed_int32_array *p_pia);
+void GDAPI godot_array_new_packed_int64_array(godot_array *r_dest, const godot_packed_int64_array *p_pia);
void GDAPI godot_array_new_packed_byte_array(godot_array *r_dest, const godot_packed_byte_array *p_pba);
void GDAPI godot_array_set(godot_array *p_self, const godot_int p_idx, const godot_variant *p_value);
@@ -84,7 +87,7 @@ void GDAPI godot_array_clear(godot_array *p_self);
godot_int GDAPI godot_array_count(const godot_array *p_self, const godot_variant *p_value);
-godot_bool GDAPI godot_array_empty(const godot_array *p_self);
+godot_bool GDAPI godot_array_is_empty(const godot_array *p_self);
void GDAPI godot_array_erase(godot_array *p_self, const godot_variant *p_value);
diff --git a/modules/gdnative/include/gdnative/basis.h b/modules/gdnative/include/gdnative/basis.h
index c7425ebbfa..c6dab4c3c1 100644
--- a/modules/gdnative/include/gdnative/basis.h
+++ b/modules/gdnative/include/gdnative/basis.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/callable.h b/modules/gdnative/include/gdnative/callable.h
new file mode 100644
index 0000000000..b3daaa7d0c
--- /dev/null
+++ b/modules/gdnative/include/gdnative/callable.h
@@ -0,0 +1,126 @@
+/*************************************************************************/
+/* callable.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GODOT_CALLABLE_H
+#define GODOT_CALLABLE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+#define GODOT_CALLABLE_SIZE (16)
+
+#ifndef GODOT_CORE_API_GODOT_CALLABLE_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_CALLABLE_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_CALLABLE_SIZE];
+} godot_callable;
+#endif
+
+#define GODOT_SIGNAL_SIZE (16)
+
+#ifndef GODOT_CORE_API_GODOT_SIGNAL_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_SIGNAL_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_SIGNAL_SIZE];
+} godot_signal;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#include <gdnative/gdnative.h>
+#include <gdnative/string_name.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Callable
+
+void GDAPI godot_callable_new_with_object(godot_callable *r_dest, const godot_object *p_object, const godot_string_name *p_method);
+void GDAPI godot_callable_new_with_object_id(godot_callable *r_dest, uint64_t p_objectid, const godot_string_name *p_method);
+void GDAPI godot_callable_new_copy(godot_callable *r_dest, const godot_callable *p_src);
+
+void GDAPI godot_callable_destroy(godot_callable *p_self);
+
+godot_int GDAPI godot_callable_call(const godot_callable *p_self, const godot_variant **p_arguments, godot_int p_argcount, godot_variant *r_return_value);
+void GDAPI godot_callable_call_deferred(const godot_callable *p_self, const godot_variant **p_arguments, godot_int p_argcount);
+
+godot_bool GDAPI godot_callable_is_null(const godot_callable *p_self);
+godot_bool GDAPI godot_callable_is_custom(const godot_callable *p_self);
+godot_bool GDAPI godot_callable_is_standard(const godot_callable *p_self);
+
+godot_object GDAPI *godot_callable_get_object(const godot_callable *p_self);
+uint64_t GDAPI godot_callable_get_object_id(const godot_callable *p_self);
+godot_string_name GDAPI godot_callable_get_method(const godot_callable *p_self);
+
+uint32_t GDAPI godot_callable_hash(const godot_callable *p_self);
+
+godot_string GDAPI godot_callable_as_string(const godot_callable *p_self);
+
+godot_bool GDAPI godot_callable_operator_equal(const godot_callable *p_self, const godot_callable *p_other);
+godot_bool GDAPI godot_callable_operator_less(const godot_callable *p_self, const godot_callable *p_other);
+
+// Signal
+
+void GDAPI godot_signal_new_with_object(godot_signal *r_dest, const godot_object *p_object, const godot_string_name *p_name);
+void GDAPI godot_signal_new_with_object_id(godot_signal *r_dest, uint64_t p_objectid, const godot_string_name *p_name);
+void GDAPI godot_signal_new_copy(godot_signal *r_dest, const godot_signal *p_src);
+
+void GDAPI godot_signal_destroy(godot_signal *p_self);
+
+godot_int GDAPI godot_signal_emit(const godot_signal *p_self, const godot_variant **p_arguments, godot_int p_argcount);
+
+godot_int GDAPI godot_signal_connect(godot_signal *p_self, const godot_callable *p_callable, const godot_array *p_binds, uint32_t p_flags);
+void GDAPI godot_signal_disconnect(godot_signal *p_self, const godot_callable *p_callable);
+
+godot_bool GDAPI godot_signal_is_null(const godot_signal *p_self);
+godot_bool GDAPI godot_signal_is_connected(const godot_signal *p_self, const godot_callable *p_callable);
+
+godot_array GDAPI godot_signal_get_connections(const godot_signal *p_self);
+
+godot_object GDAPI *godot_signal_get_object(const godot_signal *p_self);
+uint64_t GDAPI godot_signal_get_object_id(const godot_signal *p_self);
+godot_string_name GDAPI godot_signal_get_name(const godot_signal *p_self);
+
+godot_string GDAPI godot_signal_as_string(const godot_signal *p_self);
+
+godot_bool GDAPI godot_signal_operator_equal(const godot_signal *p_self, const godot_signal *p_other);
+godot_bool GDAPI godot_signal_operator_less(const godot_signal *p_self, const godot_signal *p_other);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/modules/gdnative/include/gdnative/color.h b/modules/gdnative/include/gdnative/color.h
index e7737bf8e1..c6ef921ad9 100644
--- a/modules/gdnative/include/gdnative/color.h
+++ b/modules/gdnative/include/gdnative/color.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -93,8 +93,6 @@ godot_int GDAPI godot_color_to_argb32(const godot_color *p_self);
godot_color GDAPI godot_color_inverted(const godot_color *p_self);
-godot_color GDAPI godot_color_contrasted(const godot_color *p_self);
-
godot_color GDAPI godot_color_lerp(const godot_color *p_self, const godot_color *p_b, const godot_real p_t);
godot_color GDAPI godot_color_blend(const godot_color *p_self, const godot_color *p_over);
diff --git a/modules/gdnative/include/gdnative/dictionary.h b/modules/gdnative/include/gdnative/dictionary.h
index 873efaa9bf..3f664567d8 100644
--- a/modules/gdnative/include/gdnative/dictionary.h
+++ b/modules/gdnative/include/gdnative/dictionary.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -67,7 +67,7 @@ godot_dictionary GDAPI godot_dictionary_duplicate(const godot_dictionary *p_self
godot_int GDAPI godot_dictionary_size(const godot_dictionary *p_self);
-godot_bool GDAPI godot_dictionary_empty(const godot_dictionary *p_self);
+godot_bool GDAPI godot_dictionary_is_empty(const godot_dictionary *p_self);
void GDAPI godot_dictionary_clear(godot_dictionary *p_self);
diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h
index 6fdca30122..cc8bf52fe4 100644
--- a/modules/gdnative/include/gdnative/gdnative.h
+++ b/modules/gdnative/include/gdnative/gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -144,15 +144,15 @@ typedef void godot_object;
#include <gdnative/string_name.h>
-////// Vector2
+////// Vector2 & Vector2i
#include <gdnative/vector2.h>
-////// Rect2
+////// Rect2 & Rect2i
#include <gdnative/rect2.h>
-////// Vector3
+////// Vector3 & Vector3i
#include <gdnative/vector3.h>
@@ -192,6 +192,10 @@ typedef void godot_object;
#include <gdnative/rid.h>
+/////// Callable & Signal
+
+#include <gdnative/callable.h>
+
/////// Dictionary
#include <gdnative/dictionary.h>
@@ -200,8 +204,8 @@ typedef void godot_object;
#include <gdnative/array.h>
-// single API file for Pool*Array
-#include <gdnative/pool_arrays.h>
+// single API file for Packed*Array
+#include <gdnative/packed_arrays.h>
void GDAPI godot_object_destroy(godot_object *p_o);
@@ -289,7 +293,9 @@ void GDAPI *godot_get_class_tag(const godot_string_name *p_class);
godot_object GDAPI *godot_object_cast_to(const godot_object *p_object, void *p_class_tag);
// equivalent of GDScript's instance_from_id
-godot_object GDAPI *godot_instance_from_id(godot_int p_instance_id);
+godot_object GDAPI *godot_instance_from_id(uint64_t p_instance_id);
+
+uint64_t GDAPI godot_object_get_instance_id(const godot_object *p_object);
#ifdef __cplusplus
}
diff --git a/modules/gdnative/include/gdnative/node_path.h b/modules/gdnative/include/gdnative/node_path.h
index 0cd0c3cb9c..052e4469a2 100644
--- a/modules/gdnative/include/gdnative/node_path.h
+++ b/modules/gdnative/include/gdnative/node_path.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/packed_arrays.h b/modules/gdnative/include/gdnative/packed_arrays.h
new file mode 100644
index 0000000000..f5b95eadd3
--- /dev/null
+++ b/modules/gdnative/include/gdnative/packed_arrays.h
@@ -0,0 +1,530 @@
+/*************************************************************************/
+/* packed_arrays.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GODOT_PACKED_ARRAYS_H
+#define GODOT_PACKED_ARRAYS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+/////// PackedByteArray
+
+#define GODOT_PACKED_BYTE_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_BYTE_ARRAY_SIZE];
+} godot_packed_byte_array;
+#endif
+
+/////// PackedInt32Array
+
+#define GODOT_PACKED_INT32_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_INT32_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_INT32_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_INT32_ARRAY_SIZE];
+} godot_packed_int32_array;
+#endif
+
+/////// PackedInt64Array
+
+#define GODOT_PACKED_INT64_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_INT64_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_INT64_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_INT64_ARRAY_SIZE];
+} godot_packed_int64_array;
+#endif
+
+/////// PackedFloat32Array
+
+#define GODOT_PACKED_FLOAT32_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_FLOAT32_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_FLOAT32_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_FLOAT32_ARRAY_SIZE];
+} godot_packed_float32_array;
+#endif
+
+/////// PackedFloat64Array
+
+#define GODOT_PACKED_FLOAT64_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_FLOAT64_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_FLOAT64_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_FLOAT64_ARRAY_SIZE];
+} godot_packed_float64_array;
+#endif
+
+/////// PackedStringArray
+
+#define GODOT_PACKED_STRING_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_STRING_ARRAY_SIZE];
+} godot_packed_string_array;
+#endif
+
+/////// PackedVector2Array
+
+#define GODOT_PACKED_VECTOR2_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2_ARRAY_SIZE];
+} godot_packed_vector2_array;
+#endif
+
+/////// PackedVector2iArray
+
+#define GODOT_PACKED_VECTOR2I_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_VECTOR2I_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2I_ARRAY_SIZE];
+} godot_packed_vector2i_array;
+#endif
+
+/////// PackedVector3Array
+
+#define GODOT_PACKED_VECTOR3_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_VECTOR3_ARRAY_SIZE];
+} godot_packed_vector3_array;
+#endif
+
+/////// PackedColorArray
+
+#define GODOT_PACKED_COLOR_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_COLOR_ARRAY_SIZE];
+} godot_packed_color_array;
+#endif
+
+// reduce extern "C" nesting for VS2013
+#ifdef __cplusplus
+}
+#endif
+
+#include <gdnative/array.h>
+#include <gdnative/color.h>
+#include <gdnative/vector2.h>
+#include <gdnative/vector3.h>
+
+#include <gdnative/gdnative.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// byte
+
+void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *r_dest);
+void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src);
+void GDAPI godot_packed_byte_array_new_with_array(godot_packed_byte_array *r_dest, const godot_array *p_a);
+
+const uint8_t GDAPI *godot_packed_byte_array_ptr(const godot_packed_byte_array *p_self);
+uint8_t GDAPI *godot_packed_byte_array_ptrw(godot_packed_byte_array *p_self);
+
+void GDAPI godot_packed_byte_array_append(godot_packed_byte_array *p_self, const uint8_t p_data);
+
+void GDAPI godot_packed_byte_array_append_array(godot_packed_byte_array *p_self, const godot_packed_byte_array *p_array);
+
+godot_error GDAPI godot_packed_byte_array_insert(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data);
+
+godot_bool GDAPI godot_packed_byte_array_has(godot_packed_byte_array *p_self, const uint8_t p_value);
+
+void GDAPI godot_packed_byte_array_sort(godot_packed_byte_array *p_self);
+
+void GDAPI godot_packed_byte_array_invert(godot_packed_byte_array *p_self);
+
+void GDAPI godot_packed_byte_array_push_back(godot_packed_byte_array *p_self, const uint8_t p_data);
+
+void GDAPI godot_packed_byte_array_remove(godot_packed_byte_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_byte_array_resize(godot_packed_byte_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_byte_array_set(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data);
+uint8_t GDAPI godot_packed_byte_array_get(const godot_packed_byte_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_byte_array_size(const godot_packed_byte_array *p_self);
+
+godot_bool GDAPI godot_packed_byte_array_is_empty(const godot_packed_byte_array *p_self);
+
+void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self);
+
+// int32
+
+void GDAPI godot_packed_int32_array_new(godot_packed_int32_array *r_dest);
+void GDAPI godot_packed_int32_array_new_copy(godot_packed_int32_array *r_dest, const godot_packed_int32_array *p_src);
+void GDAPI godot_packed_int32_array_new_with_array(godot_packed_int32_array *r_dest, const godot_array *p_a);
+
+const int32_t GDAPI *godot_packed_int32_array_ptr(const godot_packed_int32_array *p_self);
+int32_t GDAPI *godot_packed_int32_array_ptrw(godot_packed_int32_array *p_self);
+
+void GDAPI godot_packed_int32_array_append(godot_packed_int32_array *p_self, const int32_t p_data);
+
+void GDAPI godot_packed_int32_array_append_array(godot_packed_int32_array *p_self, const godot_packed_int32_array *p_array);
+
+godot_error GDAPI godot_packed_int32_array_insert(godot_packed_int32_array *p_self, const godot_int p_idx, const int32_t p_data);
+
+godot_bool GDAPI godot_packed_int32_array_has(godot_packed_int32_array *p_self, const int32_t p_value);
+
+void GDAPI godot_packed_int32_array_sort(godot_packed_int32_array *p_self);
+
+void GDAPI godot_packed_int32_array_invert(godot_packed_int32_array *p_self);
+
+void GDAPI godot_packed_int32_array_push_back(godot_packed_int32_array *p_self, const int32_t p_data);
+
+void GDAPI godot_packed_int32_array_remove(godot_packed_int32_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_int32_array_resize(godot_packed_int32_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_int32_array_set(godot_packed_int32_array *p_self, const godot_int p_idx, const int32_t p_data);
+int32_t GDAPI godot_packed_int32_array_get(const godot_packed_int32_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_int32_array_size(const godot_packed_int32_array *p_self);
+
+godot_bool GDAPI godot_packed_int32_array_is_empty(const godot_packed_int32_array *p_self);
+
+void GDAPI godot_packed_int32_array_destroy(godot_packed_int32_array *p_self);
+
+// int64
+
+void GDAPI godot_packed_int64_array_new(godot_packed_int64_array *r_dest);
+void GDAPI godot_packed_int64_array_new_copy(godot_packed_int64_array *r_dest, const godot_packed_int64_array *p_src);
+void GDAPI godot_packed_int64_array_new_with_array(godot_packed_int64_array *r_dest, const godot_array *p_a);
+
+const int64_t GDAPI *godot_packed_int64_array_ptr(const godot_packed_int64_array *p_self);
+int64_t GDAPI *godot_packed_int64_array_ptrw(godot_packed_int64_array *p_self);
+
+void GDAPI godot_packed_int64_array_append(godot_packed_int64_array *p_self, const int64_t p_data);
+
+void GDAPI godot_packed_int64_array_append_array(godot_packed_int64_array *p_self, const godot_packed_int64_array *p_array);
+
+godot_error GDAPI godot_packed_int64_array_insert(godot_packed_int64_array *p_self, const godot_int p_idx, const int64_t p_data);
+
+godot_bool GDAPI godot_packed_int64_array_has(godot_packed_int64_array *p_self, const int64_t p_value);
+
+void GDAPI godot_packed_int64_array_sort(godot_packed_int64_array *p_self);
+
+void GDAPI godot_packed_int64_array_invert(godot_packed_int64_array *p_self);
+
+void GDAPI godot_packed_int64_array_push_back(godot_packed_int64_array *p_self, const int64_t p_data);
+
+void GDAPI godot_packed_int64_array_remove(godot_packed_int64_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_int64_array_resize(godot_packed_int64_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_int64_array_set(godot_packed_int64_array *p_self, const godot_int p_idx, const int64_t p_data);
+int64_t GDAPI godot_packed_int64_array_get(const godot_packed_int64_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_int64_array_size(const godot_packed_int64_array *p_self);
+
+godot_bool GDAPI godot_packed_int64_array_is_empty(const godot_packed_int64_array *p_self);
+
+void GDAPI godot_packed_int64_array_destroy(godot_packed_int64_array *p_self);
+
+// float32
+
+void GDAPI godot_packed_float32_array_new(godot_packed_float32_array *r_dest);
+void GDAPI godot_packed_float32_array_new_copy(godot_packed_float32_array *r_dest, const godot_packed_float32_array *p_src);
+void GDAPI godot_packed_float32_array_new_with_array(godot_packed_float32_array *r_dest, const godot_array *p_a);
+
+const float GDAPI *godot_packed_float32_array_ptr(const godot_packed_float32_array *p_self);
+float GDAPI *godot_packed_float32_array_ptrw(godot_packed_float32_array *p_self);
+
+void GDAPI godot_packed_float32_array_append(godot_packed_float32_array *p_self, const float p_data);
+
+void GDAPI godot_packed_float32_array_append_array(godot_packed_float32_array *p_self, const godot_packed_float32_array *p_array);
+
+godot_error GDAPI godot_packed_float32_array_insert(godot_packed_float32_array *p_self, const godot_int p_idx, const float p_data);
+
+godot_bool GDAPI godot_packed_float32_array_has(godot_packed_float32_array *p_self, const float p_value);
+
+void GDAPI godot_packed_float32_array_sort(godot_packed_float32_array *p_self);
+
+void GDAPI godot_packed_float32_array_invert(godot_packed_float32_array *p_self);
+
+void GDAPI godot_packed_float32_array_push_back(godot_packed_float32_array *p_self, const float p_data);
+
+void GDAPI godot_packed_float32_array_remove(godot_packed_float32_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_float32_array_resize(godot_packed_float32_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_float32_array_set(godot_packed_float32_array *p_self, const godot_int p_idx, const float p_data);
+float GDAPI godot_packed_float32_array_get(const godot_packed_float32_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_float32_array_size(const godot_packed_float32_array *p_self);
+
+godot_bool GDAPI godot_packed_float32_array_is_empty(const godot_packed_float32_array *p_self);
+
+void GDAPI godot_packed_float32_array_destroy(godot_packed_float32_array *p_self);
+
+// float64
+
+void GDAPI godot_packed_float64_array_new(godot_packed_float64_array *r_dest);
+void GDAPI godot_packed_float64_array_new_copy(godot_packed_float64_array *r_dest, const godot_packed_float64_array *p_src);
+void GDAPI godot_packed_float64_array_new_with_array(godot_packed_float64_array *r_dest, const godot_array *p_a);
+
+const double GDAPI *godot_packed_float64_array_ptr(const godot_packed_float64_array *p_self);
+double GDAPI *godot_packed_float64_array_ptrw(godot_packed_float64_array *p_self);
+
+void GDAPI godot_packed_float64_array_append(godot_packed_float64_array *p_self, const double p_data);
+
+void GDAPI godot_packed_float64_array_append_array(godot_packed_float64_array *p_self, const godot_packed_float64_array *p_array);
+
+godot_error GDAPI godot_packed_float64_array_insert(godot_packed_float64_array *p_self, const godot_int p_idx, const double p_data);
+
+godot_bool GDAPI godot_packed_float64_array_has(godot_packed_float64_array *p_self, const double p_value);
+
+void GDAPI godot_packed_float64_array_sort(godot_packed_float64_array *p_self);
+
+void GDAPI godot_packed_float64_array_invert(godot_packed_float64_array *p_self);
+
+void GDAPI godot_packed_float64_array_push_back(godot_packed_float64_array *p_self, const double p_data);
+
+void GDAPI godot_packed_float64_array_remove(godot_packed_float64_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_float64_array_resize(godot_packed_float64_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_float64_array_set(godot_packed_float64_array *p_self, const godot_int p_idx, const double p_data);
+double GDAPI godot_packed_float64_array_get(const godot_packed_float64_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_float64_array_size(const godot_packed_float64_array *p_self);
+
+godot_bool GDAPI godot_packed_float64_array_is_empty(const godot_packed_float64_array *p_self);
+
+void GDAPI godot_packed_float64_array_destroy(godot_packed_float64_array *p_self);
+
+// string
+
+void GDAPI godot_packed_string_array_new(godot_packed_string_array *r_dest);
+void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src);
+void GDAPI godot_packed_string_array_new_with_array(godot_packed_string_array *r_dest, const godot_array *p_a);
+
+const godot_string GDAPI *godot_packed_string_array_ptr(const godot_packed_string_array *p_self);
+godot_string GDAPI *godot_packed_string_array_ptrw(godot_packed_string_array *p_self);
+
+void GDAPI godot_packed_string_array_append(godot_packed_string_array *p_self, const godot_string *p_data);
+
+void GDAPI godot_packed_string_array_append_array(godot_packed_string_array *p_self, const godot_packed_string_array *p_array);
+
+godot_error GDAPI godot_packed_string_array_insert(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data);
+
+godot_bool GDAPI godot_packed_string_array_has(godot_packed_string_array *p_self, const godot_string *p_value);
+
+void GDAPI godot_packed_string_array_sort(godot_packed_string_array *p_self);
+
+void GDAPI godot_packed_string_array_invert(godot_packed_string_array *p_self);
+
+void GDAPI godot_packed_string_array_push_back(godot_packed_string_array *p_self, const godot_string *p_data);
+
+void GDAPI godot_packed_string_array_remove(godot_packed_string_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_string_array_resize(godot_packed_string_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_string_array_set(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data);
+godot_string GDAPI godot_packed_string_array_get(const godot_packed_string_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_string_array_size(const godot_packed_string_array *p_self);
+
+godot_bool GDAPI godot_packed_string_array_is_empty(const godot_packed_string_array *p_self);
+
+void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self);
+
+// vector2
+
+void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *r_dest);
+void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src);
+void GDAPI godot_packed_vector2_array_new_with_array(godot_packed_vector2_array *r_dest, const godot_array *p_a);
+
+const godot_vector2 GDAPI *godot_packed_vector2_array_ptr(const godot_packed_vector2_array *p_self);
+godot_vector2 GDAPI *godot_packed_vector2_array_ptrw(godot_packed_vector2_array *p_self);
+
+void GDAPI godot_packed_vector2_array_append(godot_packed_vector2_array *p_self, const godot_vector2 *p_data);
+
+void GDAPI godot_packed_vector2_array_append_array(godot_packed_vector2_array *p_self, const godot_packed_vector2_array *p_array);
+
+godot_error GDAPI godot_packed_vector2_array_insert(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data);
+
+godot_bool GDAPI godot_packed_vector2_array_has(godot_packed_vector2_array *p_self, const godot_vector2 *p_value);
+
+void GDAPI godot_packed_vector2_array_sort(godot_packed_vector2_array *p_self);
+
+void GDAPI godot_packed_vector2_array_invert(godot_packed_vector2_array *p_self);
+
+void GDAPI godot_packed_vector2_array_push_back(godot_packed_vector2_array *p_self, const godot_vector2 *p_data);
+
+void GDAPI godot_packed_vector2_array_remove(godot_packed_vector2_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_vector2_array_resize(godot_packed_vector2_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_vector2_array_set(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data);
+godot_vector2 GDAPI godot_packed_vector2_array_get(const godot_packed_vector2_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_vector2_array_size(const godot_packed_vector2_array *p_self);
+
+godot_bool GDAPI godot_packed_vector2_array_is_empty(const godot_packed_vector2_array *p_self);
+
+void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self);
+
+// vector2i
+
+void GDAPI godot_packed_vector2i_array_new(godot_packed_vector2i_array *r_dest);
+void GDAPI godot_packed_vector2i_array_new_copy(godot_packed_vector2i_array *r_dest, const godot_packed_vector2i_array *p_src);
+void GDAPI godot_packed_vector2i_array_new_with_array(godot_packed_vector2i_array *r_dest, const godot_array *p_a);
+
+const godot_vector2i GDAPI *godot_packed_vector2i_array_ptr(const godot_packed_vector2i_array *p_self);
+godot_vector2i GDAPI *godot_packed_vector2i_array_ptrw(godot_packed_vector2i_array *p_self);
+
+void GDAPI godot_packed_vector2i_array_append(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data);
+
+void GDAPI godot_packed_vector2i_array_append_array(godot_packed_vector2i_array *p_self, const godot_packed_vector2i_array *p_array);
+
+godot_error GDAPI godot_packed_vector2i_array_insert(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data);
+
+godot_bool GDAPI godot_packed_vector2i_array_has(godot_packed_vector2i_array *p_self, const godot_vector2i *p_value);
+
+void GDAPI godot_packed_vector2i_array_sort(godot_packed_vector2i_array *p_self);
+
+void GDAPI godot_packed_vector2i_array_invert(godot_packed_vector2i_array *p_self);
+
+void GDAPI godot_packed_vector2i_array_push_back(godot_packed_vector2i_array *p_self, const godot_vector2i *p_data);
+
+void GDAPI godot_packed_vector2i_array_remove(godot_packed_vector2i_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_vector2i_array_resize(godot_packed_vector2i_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_vector2i_array_set(godot_packed_vector2i_array *p_self, const godot_int p_idx, const godot_vector2i *p_data);
+godot_vector2i GDAPI godot_packed_vector2i_array_get(const godot_packed_vector2i_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_vector2i_array_size(const godot_packed_vector2i_array *p_self);
+
+godot_bool GDAPI godot_packed_vector2i_array_is_empty(const godot_packed_vector2i_array *p_self);
+
+void GDAPI godot_packed_vector2i_array_destroy(godot_packed_vector2i_array *p_self);
+
+// vector3
+
+void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest);
+void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src);
+void GDAPI godot_packed_vector3_array_new_with_array(godot_packed_vector3_array *r_dest, const godot_array *p_a);
+
+const godot_vector3 GDAPI *godot_packed_vector3_array_ptr(const godot_packed_vector3_array *p_self);
+godot_vector3 GDAPI *godot_packed_vector3_array_ptrw(godot_packed_vector3_array *p_self);
+
+void GDAPI godot_packed_vector3_array_append(godot_packed_vector3_array *p_self, const godot_vector3 *p_data);
+
+void GDAPI godot_packed_vector3_array_append_array(godot_packed_vector3_array *p_self, const godot_packed_vector3_array *p_array);
+
+godot_error GDAPI godot_packed_vector3_array_insert(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data);
+
+godot_bool GDAPI godot_packed_vector3_array_has(godot_packed_vector3_array *p_self, const godot_vector3 *p_value);
+
+void GDAPI godot_packed_vector3_array_sort(godot_packed_vector3_array *p_self);
+
+void GDAPI godot_packed_vector3_array_invert(godot_packed_vector3_array *p_self);
+
+void GDAPI godot_packed_vector3_array_push_back(godot_packed_vector3_array *p_self, const godot_vector3 *p_data);
+
+void GDAPI godot_packed_vector3_array_remove(godot_packed_vector3_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_vector3_array_resize(godot_packed_vector3_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_vector3_array_set(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data);
+godot_vector3 GDAPI godot_packed_vector3_array_get(const godot_packed_vector3_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_vector3_array_size(const godot_packed_vector3_array *p_self);
+
+godot_bool GDAPI godot_packed_vector3_array_is_empty(const godot_packed_vector3_array *p_self);
+
+void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self);
+
+// color
+
+void GDAPI godot_packed_color_array_new(godot_packed_color_array *r_dest);
+void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src);
+void GDAPI godot_packed_color_array_new_with_array(godot_packed_color_array *r_dest, const godot_array *p_a);
+
+const godot_color GDAPI *godot_packed_color_array_ptr(const godot_packed_color_array *p_self);
+godot_color GDAPI *godot_packed_color_array_ptrw(godot_packed_color_array *p_self);
+
+void GDAPI godot_packed_color_array_append(godot_packed_color_array *p_self, const godot_color *p_data);
+
+void GDAPI godot_packed_color_array_append_array(godot_packed_color_array *p_self, const godot_packed_color_array *p_array);
+
+godot_error GDAPI godot_packed_color_array_insert(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data);
+
+godot_bool GDAPI godot_packed_color_array_has(godot_packed_color_array *p_self, const godot_color *p_value);
+
+void GDAPI godot_packed_color_array_sort(godot_packed_color_array *p_self);
+
+void GDAPI godot_packed_color_array_invert(godot_packed_color_array *p_self);
+
+void GDAPI godot_packed_color_array_push_back(godot_packed_color_array *p_self, const godot_color *p_data);
+
+void GDAPI godot_packed_color_array_remove(godot_packed_color_array *p_self, const godot_int p_idx);
+
+void GDAPI godot_packed_color_array_resize(godot_packed_color_array *p_self, const godot_int p_size);
+
+void GDAPI godot_packed_color_array_set(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data);
+godot_color GDAPI godot_packed_color_array_get(const godot_packed_color_array *p_self, const godot_int p_idx);
+
+godot_int GDAPI godot_packed_color_array_size(const godot_packed_color_array *p_self);
+
+godot_bool GDAPI godot_packed_color_array_is_empty(const godot_packed_color_array *p_self);
+
+void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // GODOT_POOL_ARRAYS_H
diff --git a/modules/gdnative/include/gdnative/plane.h b/modules/gdnative/include/gdnative/plane.h
index b759a8cc1a..a8625d4cd6 100644
--- a/modules/gdnative/include/gdnative/plane.h
+++ b/modules/gdnative/include/gdnative/plane.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -68,8 +68,6 @@ godot_plane GDAPI godot_plane_normalized(const godot_plane *p_self);
godot_vector3 GDAPI godot_plane_center(const godot_plane *p_self);
-godot_vector3 GDAPI godot_plane_get_any_point(const godot_plane *p_self);
-
godot_bool GDAPI godot_plane_is_point_over(const godot_plane *p_self, const godot_vector3 *p_point);
godot_real GDAPI godot_plane_distance_to(const godot_plane *p_self, const godot_vector3 *p_point);
diff --git a/modules/gdnative/include/gdnative/pool_arrays.h b/modules/gdnative/include/gdnative/pool_arrays.h
deleted file mode 100644
index c610377f54..0000000000
--- a/modules/gdnative/include/gdnative/pool_arrays.h
+++ /dev/null
@@ -1,340 +0,0 @@
-/*************************************************************************/
-/* pool_arrays.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 GODOT_POOL_ARRAYS_H
-#define GODOT_POOL_ARRAYS_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdint.h>
-
-/////// PackedByteArray
-
-#define GODOT_PACKED_BYTE_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_BYTE_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_BYTE_ARRAY_SIZE];
-} godot_packed_byte_array;
-#endif
-
-/////// PackedInt32Array
-
-#define GODOT_PACKED_INT_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_INT_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_INT_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_INT_ARRAY_SIZE];
-} godot_packed_int_array;
-#endif
-
-/////// PackedFloat32Array
-
-#define GODOT_PACKED_REAL_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_REAL_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_REAL_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_REAL_ARRAY_SIZE];
-} godot_packed_real_array;
-#endif
-
-/////// PackedStringArray
-
-#define GODOT_PACKED_STRING_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_STRING_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_STRING_ARRAY_SIZE];
-} godot_packed_string_array;
-#endif
-
-/////// PackedVector2Array
-
-#define GODOT_PACKED_VECTOR2_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_VECTOR2_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_VECTOR2_ARRAY_SIZE];
-} godot_packed_vector2_array;
-#endif
-
-/////// PackedVector3Array
-
-#define GODOT_PACKED_VECTOR3_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_VECTOR3_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_VECTOR3_ARRAY_SIZE];
-} godot_packed_vector3_array;
-#endif
-
-/////// PackedColorArray
-
-#define GODOT_PACKED_COLOR_ARRAY_SIZE sizeof(void *)
-
-#ifndef GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED
-#define GODOT_CORE_API_GODOT_PACKED_COLOR_ARRAY_TYPE_DEFINED
-typedef struct {
- uint8_t _dont_touch_that[GODOT_PACKED_COLOR_ARRAY_SIZE];
-} godot_packed_color_array;
-#endif
-
-// reduce extern "C" nesting for VS2013
-#ifdef __cplusplus
-}
-#endif
-
-#include <gdnative/array.h>
-#include <gdnative/color.h>
-#include <gdnative/vector2.h>
-#include <gdnative/vector3.h>
-
-#include <gdnative/gdnative.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// byte
-
-void GDAPI godot_packed_byte_array_new(godot_packed_byte_array *r_dest);
-void GDAPI godot_packed_byte_array_new_copy(godot_packed_byte_array *r_dest, const godot_packed_byte_array *p_src);
-void GDAPI godot_packed_byte_array_new_with_array(godot_packed_byte_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_byte_array_append(godot_packed_byte_array *p_self, const uint8_t p_data);
-
-void GDAPI godot_packed_byte_array_append_array(godot_packed_byte_array *p_self, const godot_packed_byte_array *p_array);
-
-godot_error GDAPI godot_packed_byte_array_insert(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data);
-
-void GDAPI godot_packed_byte_array_invert(godot_packed_byte_array *p_self);
-
-void GDAPI godot_packed_byte_array_push_back(godot_packed_byte_array *p_self, const uint8_t p_data);
-
-void GDAPI godot_packed_byte_array_remove(godot_packed_byte_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_byte_array_resize(godot_packed_byte_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_byte_array_set(godot_packed_byte_array *p_self, const godot_int p_idx, const uint8_t p_data);
-uint8_t GDAPI godot_packed_byte_array_get(const godot_packed_byte_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_byte_array_size(const godot_packed_byte_array *p_self);
-
-godot_bool GDAPI godot_packed_byte_array_empty(const godot_packed_byte_array *p_self);
-
-void GDAPI godot_packed_byte_array_destroy(godot_packed_byte_array *p_self);
-
-// int
-
-void GDAPI godot_packed_int_array_new(godot_packed_int_array *r_dest);
-void GDAPI godot_packed_int_array_new_copy(godot_packed_int_array *r_dest, const godot_packed_int_array *p_src);
-void GDAPI godot_packed_int_array_new_with_array(godot_packed_int_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_int_array_append(godot_packed_int_array *p_self, const godot_int p_data);
-
-void GDAPI godot_packed_int_array_append_array(godot_packed_int_array *p_self, const godot_packed_int_array *p_array);
-
-godot_error GDAPI godot_packed_int_array_insert(godot_packed_int_array *p_self, const godot_int p_idx, const godot_int p_data);
-
-void GDAPI godot_packed_int_array_invert(godot_packed_int_array *p_self);
-
-void GDAPI godot_packed_int_array_push_back(godot_packed_int_array *p_self, const godot_int p_data);
-
-void GDAPI godot_packed_int_array_remove(godot_packed_int_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_int_array_resize(godot_packed_int_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_int_array_set(godot_packed_int_array *p_self, const godot_int p_idx, const godot_int p_data);
-godot_int GDAPI godot_packed_int_array_get(const godot_packed_int_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_int_array_size(const godot_packed_int_array *p_self);
-
-godot_bool GDAPI godot_packed_int_array_empty(const godot_packed_int_array *p_self);
-
-void GDAPI godot_packed_int_array_destroy(godot_packed_int_array *p_self);
-
-// real
-
-void GDAPI godot_packed_real_array_new(godot_packed_real_array *r_dest);
-void GDAPI godot_packed_real_array_new_copy(godot_packed_real_array *r_dest, const godot_packed_real_array *p_src);
-void GDAPI godot_packed_real_array_new_with_array(godot_packed_real_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_real_array_append(godot_packed_real_array *p_self, const godot_real p_data);
-
-void GDAPI godot_packed_real_array_append_array(godot_packed_real_array *p_self, const godot_packed_real_array *p_array);
-
-godot_error GDAPI godot_packed_real_array_insert(godot_packed_real_array *p_self, const godot_int p_idx, const godot_real p_data);
-
-void GDAPI godot_packed_real_array_invert(godot_packed_real_array *p_self);
-
-void GDAPI godot_packed_real_array_push_back(godot_packed_real_array *p_self, const godot_real p_data);
-
-void GDAPI godot_packed_real_array_remove(godot_packed_real_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_real_array_resize(godot_packed_real_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_real_array_set(godot_packed_real_array *p_self, const godot_int p_idx, const godot_real p_data);
-godot_real GDAPI godot_packed_real_array_get(const godot_packed_real_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_real_array_size(const godot_packed_real_array *p_self);
-
-godot_bool GDAPI godot_packed_real_array_empty(const godot_packed_real_array *p_self);
-
-void GDAPI godot_packed_real_array_destroy(godot_packed_real_array *p_self);
-
-// string
-
-void GDAPI godot_packed_string_array_new(godot_packed_string_array *r_dest);
-void GDAPI godot_packed_string_array_new_copy(godot_packed_string_array *r_dest, const godot_packed_string_array *p_src);
-void GDAPI godot_packed_string_array_new_with_array(godot_packed_string_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_string_array_append(godot_packed_string_array *p_self, const godot_string *p_data);
-
-void GDAPI godot_packed_string_array_append_array(godot_packed_string_array *p_self, const godot_packed_string_array *p_array);
-
-godot_error GDAPI godot_packed_string_array_insert(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data);
-
-void GDAPI godot_packed_string_array_invert(godot_packed_string_array *p_self);
-
-void GDAPI godot_packed_string_array_push_back(godot_packed_string_array *p_self, const godot_string *p_data);
-
-void GDAPI godot_packed_string_array_remove(godot_packed_string_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_string_array_resize(godot_packed_string_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_string_array_set(godot_packed_string_array *p_self, const godot_int p_idx, const godot_string *p_data);
-godot_string GDAPI godot_packed_string_array_get(const godot_packed_string_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_string_array_size(const godot_packed_string_array *p_self);
-
-godot_bool GDAPI godot_packed_string_array_empty(const godot_packed_string_array *p_self);
-
-void GDAPI godot_packed_string_array_destroy(godot_packed_string_array *p_self);
-
-// vector2
-
-void GDAPI godot_packed_vector2_array_new(godot_packed_vector2_array *r_dest);
-void GDAPI godot_packed_vector2_array_new_copy(godot_packed_vector2_array *r_dest, const godot_packed_vector2_array *p_src);
-void GDAPI godot_packed_vector2_array_new_with_array(godot_packed_vector2_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_vector2_array_append(godot_packed_vector2_array *p_self, const godot_vector2 *p_data);
-
-void GDAPI godot_packed_vector2_array_append_array(godot_packed_vector2_array *p_self, const godot_packed_vector2_array *p_array);
-
-godot_error GDAPI godot_packed_vector2_array_insert(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data);
-
-void GDAPI godot_packed_vector2_array_invert(godot_packed_vector2_array *p_self);
-
-void GDAPI godot_packed_vector2_array_push_back(godot_packed_vector2_array *p_self, const godot_vector2 *p_data);
-
-void GDAPI godot_packed_vector2_array_remove(godot_packed_vector2_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_vector2_array_resize(godot_packed_vector2_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_vector2_array_set(godot_packed_vector2_array *p_self, const godot_int p_idx, const godot_vector2 *p_data);
-godot_vector2 GDAPI godot_packed_vector2_array_get(const godot_packed_vector2_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_vector2_array_size(const godot_packed_vector2_array *p_self);
-
-godot_bool GDAPI godot_packed_vector2_array_empty(const godot_packed_vector2_array *p_self);
-
-void GDAPI godot_packed_vector2_array_destroy(godot_packed_vector2_array *p_self);
-
-// vector3
-
-void GDAPI godot_packed_vector3_array_new(godot_packed_vector3_array *r_dest);
-void GDAPI godot_packed_vector3_array_new_copy(godot_packed_vector3_array *r_dest, const godot_packed_vector3_array *p_src);
-void GDAPI godot_packed_vector3_array_new_with_array(godot_packed_vector3_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_vector3_array_append(godot_packed_vector3_array *p_self, const godot_vector3 *p_data);
-
-void GDAPI godot_packed_vector3_array_append_array(godot_packed_vector3_array *p_self, const godot_packed_vector3_array *p_array);
-
-godot_error GDAPI godot_packed_vector3_array_insert(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data);
-
-void GDAPI godot_packed_vector3_array_invert(godot_packed_vector3_array *p_self);
-
-void GDAPI godot_packed_vector3_array_push_back(godot_packed_vector3_array *p_self, const godot_vector3 *p_data);
-
-void GDAPI godot_packed_vector3_array_remove(godot_packed_vector3_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_vector3_array_resize(godot_packed_vector3_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_vector3_array_set(godot_packed_vector3_array *p_self, const godot_int p_idx, const godot_vector3 *p_data);
-godot_vector3 GDAPI godot_packed_vector3_array_get(const godot_packed_vector3_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_vector3_array_size(const godot_packed_vector3_array *p_self);
-
-godot_bool GDAPI godot_packed_vector3_array_empty(const godot_packed_vector3_array *p_self);
-
-void GDAPI godot_packed_vector3_array_destroy(godot_packed_vector3_array *p_self);
-
-// color
-
-void GDAPI godot_packed_color_array_new(godot_packed_color_array *r_dest);
-void GDAPI godot_packed_color_array_new_copy(godot_packed_color_array *r_dest, const godot_packed_color_array *p_src);
-void GDAPI godot_packed_color_array_new_with_array(godot_packed_color_array *r_dest, const godot_array *p_a);
-
-void GDAPI godot_packed_color_array_append(godot_packed_color_array *p_self, const godot_color *p_data);
-
-void GDAPI godot_packed_color_array_append_array(godot_packed_color_array *p_self, const godot_packed_color_array *p_array);
-
-godot_error GDAPI godot_packed_color_array_insert(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data);
-
-void GDAPI godot_packed_color_array_invert(godot_packed_color_array *p_self);
-
-void GDAPI godot_packed_color_array_push_back(godot_packed_color_array *p_self, const godot_color *p_data);
-
-void GDAPI godot_packed_color_array_remove(godot_packed_color_array *p_self, const godot_int p_idx);
-
-void GDAPI godot_packed_color_array_resize(godot_packed_color_array *p_self, const godot_int p_size);
-
-void GDAPI godot_packed_color_array_set(godot_packed_color_array *p_self, const godot_int p_idx, const godot_color *p_data);
-godot_color GDAPI godot_packed_color_array_get(const godot_packed_color_array *p_self, const godot_int p_idx);
-
-godot_int GDAPI godot_packed_color_array_size(const godot_packed_color_array *p_self);
-
-godot_bool GDAPI godot_packed_color_array_empty(const godot_packed_color_array *p_self);
-
-void GDAPI godot_packed_color_array_destroy(godot_packed_color_array *p_self);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // GODOT_POOL_ARRAYS_H
diff --git a/modules/gdnative/include/gdnative/quat.h b/modules/gdnative/include/gdnative/quat.h
index d315b2d754..68ca1765dd 100644
--- a/modules/gdnative/include/gdnative/quat.h
+++ b/modules/gdnative/include/gdnative/quat.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/rect2.h b/modules/gdnative/include/gdnative/rect2.h
index 0ecf072471..d3cb276e14 100644
--- a/modules/gdnative/include/gdnative/rect2.h
+++ b/modules/gdnative/include/gdnative/rect2.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -44,6 +44,13 @@ typedef struct godot_rect2 {
} godot_rect2;
#endif
+#ifndef GODOT_CORE_API_GODOT_RECT2I_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_RECT2I_TYPE_DEFINED
+typedef struct godot_rect2i {
+ uint8_t _dont_touch_that[16];
+} godot_rect2i;
+#endif
+
// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
@@ -56,11 +63,15 @@ typedef struct godot_rect2 {
extern "C" {
#endif
+// Rect2
+
void GDAPI godot_rect2_new_with_position_and_size(godot_rect2 *r_dest, const godot_vector2 *p_pos, const godot_vector2 *p_size);
void GDAPI godot_rect2_new(godot_rect2 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_width, const godot_real p_height);
godot_string GDAPI godot_rect2_as_string(const godot_rect2 *p_self);
+godot_rect2i GDAPI godot_rect2_as_rect2i(const godot_rect2 *p_self);
+
godot_real GDAPI godot_rect2_get_area(const godot_rect2 *p_self);
godot_bool GDAPI godot_rect2_intersects(const godot_rect2 *p_self, const godot_rect2 *p_b);
@@ -69,7 +80,7 @@ godot_bool GDAPI godot_rect2_encloses(const godot_rect2 *p_self, const godot_rec
godot_bool GDAPI godot_rect2_has_no_area(const godot_rect2 *p_self);
-godot_rect2 GDAPI godot_rect2_clip(const godot_rect2 *p_self, const godot_rect2 *p_b);
+godot_rect2 GDAPI godot_rect2_intersection(const godot_rect2 *p_self, const godot_rect2 *p_b);
godot_rect2 GDAPI godot_rect2_merge(const godot_rect2 *p_self, const godot_rect2 *p_b);
@@ -79,7 +90,7 @@ godot_rect2 GDAPI godot_rect2_grow(const godot_rect2 *p_self, const godot_real p
godot_rect2 GDAPI godot_rect2_grow_individual(const godot_rect2 *p_self, const godot_real p_left, const godot_real p_top, const godot_real p_right, const godot_real p_bottom);
-godot_rect2 GDAPI godot_rect2_grow_margin(const godot_rect2 *p_self, const godot_int p_margin, const godot_real p_by);
+godot_rect2 GDAPI godot_rect2_grow_side(const godot_rect2 *p_self, const godot_int p_margin, const godot_real p_by);
godot_rect2 GDAPI godot_rect2_abs(const godot_rect2 *p_self);
@@ -95,6 +106,49 @@ void GDAPI godot_rect2_set_position(godot_rect2 *p_self, const godot_vector2 *p_
void GDAPI godot_rect2_set_size(godot_rect2 *p_self, const godot_vector2 *p_size);
+// Rect2I
+
+void GDAPI godot_rect2i_new_with_position_and_size(godot_rect2i *r_dest, const godot_vector2i *p_pos, const godot_vector2i *p_size);
+void GDAPI godot_rect2i_new(godot_rect2i *r_dest, const godot_int p_x, const godot_int p_y, const godot_int p_width, const godot_int p_height);
+
+godot_string GDAPI godot_rect2i_as_string(const godot_rect2i *p_self);
+
+godot_rect2 GDAPI godot_rect2i_as_rect2(const godot_rect2i *p_self);
+
+godot_int GDAPI godot_rect2i_get_area(const godot_rect2i *p_self);
+
+godot_bool GDAPI godot_rect2i_intersects(const godot_rect2i *p_self, const godot_rect2i *p_b);
+
+godot_bool GDAPI godot_rect2i_encloses(const godot_rect2i *p_self, const godot_rect2i *p_b);
+
+godot_bool GDAPI godot_rect2i_has_no_area(const godot_rect2i *p_self);
+
+godot_rect2i GDAPI godot_rect2i_intersection(const godot_rect2i *p_self, const godot_rect2i *p_b);
+
+godot_rect2i GDAPI godot_rect2i_merge(const godot_rect2i *p_self, const godot_rect2i *p_b);
+
+godot_bool GDAPI godot_rect2i_has_point(const godot_rect2i *p_self, const godot_vector2i *p_point);
+
+godot_rect2i GDAPI godot_rect2i_grow(const godot_rect2i *p_self, const godot_int p_by);
+
+godot_rect2i GDAPI godot_rect2i_grow_individual(const godot_rect2i *p_self, const godot_int p_left, const godot_int p_top, const godot_int p_right, const godot_int p_bottom);
+
+godot_rect2i GDAPI godot_rect2i_grow_side(const godot_rect2i *p_self, const godot_int p_margin, const godot_int p_by);
+
+godot_rect2i GDAPI godot_rect2i_abs(const godot_rect2i *p_self);
+
+godot_rect2i GDAPI godot_rect2i_expand(const godot_rect2i *p_self, const godot_vector2i *p_to);
+
+godot_bool GDAPI godot_rect2i_operator_equal(const godot_rect2i *p_self, const godot_rect2i *p_b);
+
+godot_vector2i GDAPI godot_rect2i_get_position(const godot_rect2i *p_self);
+
+godot_vector2i GDAPI godot_rect2i_get_size(const godot_rect2i *p_self);
+
+void GDAPI godot_rect2i_set_position(godot_rect2i *p_self, const godot_vector2i *p_pos);
+
+void GDAPI godot_rect2i_set_size(godot_rect2i *p_self, const godot_vector2i *p_size);
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/include/gdnative/rid.h b/modules/gdnative/include/gdnative/rid.h
index 04661cedc8..cbf066d47f 100644
--- a/modules/gdnative/include/gdnative/rid.h
+++ b/modules/gdnative/include/gdnative/rid.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,7 +37,7 @@ extern "C" {
#include <stdint.h>
-#define GODOT_RID_SIZE sizeof(void *)
+#define GODOT_RID_SIZE sizeof(uint64_t)
#ifndef GODOT_CORE_API_GODOT_RID_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_RID_TYPE_DEFINED
diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h
index 608978db76..e58be18b21 100644
--- a/modules/gdnative/include/gdnative/string.h
+++ b/modules/gdnative/include/gdnative/string.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,13 +35,19 @@
extern "C" {
#endif
+#include <stddef.h>
#include <stdint.h>
-#include <wchar.h>
-typedef wchar_t godot_char_type;
+#ifndef __cplusplus
+typedef uint32_t char32_t;
+typedef uint16_t char16_t;
+#endif
+
+typedef char32_t godot_char_type;
#define GODOT_STRING_SIZE sizeof(void *)
#define GODOT_CHAR_STRING_SIZE sizeof(void *)
+#define GODOT_CHAR16_STRING_SIZE sizeof(void *)
#ifndef GODOT_CORE_API_GODOT_STRING_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_STRING_TYPE_DEFINED
@@ -58,6 +64,13 @@ typedef struct {
} godot_char_string;
#endif
+#ifndef GODOT_CORE_API_GODOT_CHAR16_STRING_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_CHAR16_STRING_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_CHAR16_STRING_SIZE];
+} godot_char16_string;
+#endif
+
// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
@@ -75,13 +88,28 @@ godot_int GDAPI godot_char_string_length(const godot_char_string *p_cs);
const char GDAPI *godot_char_string_get_data(const godot_char_string *p_cs);
void GDAPI godot_char_string_destroy(godot_char_string *p_cs);
+godot_int GDAPI godot_char16_string_length(const godot_char16_string *p_cs);
+const char16_t GDAPI *godot_char16_string_get_data(const godot_char16_string *p_cs);
+void GDAPI godot_char16_string_destroy(godot_char16_string *p_cs);
+
void GDAPI godot_string_new(godot_string *r_dest);
void GDAPI godot_string_new_copy(godot_string *r_dest, const godot_string *p_src);
-void GDAPI godot_string_new_with_wide_string(godot_string *r_dest, const wchar_t *p_contents, const int p_size);
-const wchar_t GDAPI *godot_string_operator_index(godot_string *p_self, const godot_int p_idx);
-wchar_t GDAPI godot_string_operator_index_const(const godot_string *p_self, const godot_int p_idx);
-const wchar_t GDAPI *godot_string_wide_str(const godot_string *p_self);
+void GDAPI godot_string_new_with_latin1_chars(godot_string *r_dest, const char *p_contents);
+void GDAPI godot_string_new_with_utf8_chars(godot_string *r_dest, const char *p_contents);
+void GDAPI godot_string_new_with_utf16_chars(godot_string *r_dest, const char16_t *p_contents);
+void GDAPI godot_string_new_with_utf32_chars(godot_string *r_dest, const char32_t *p_contents);
+void GDAPI godot_string_new_with_wide_chars(godot_string *r_dest, const wchar_t *p_contents);
+
+void GDAPI godot_string_new_with_latin1_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size);
+void GDAPI godot_string_new_with_utf8_chars_and_len(godot_string *r_dest, const char *p_contents, const int p_size);
+void GDAPI godot_string_new_with_utf16_chars_and_len(godot_string *r_dest, const char16_t *p_contents, const int p_size);
+void GDAPI godot_string_new_with_utf32_chars_and_len(godot_string *r_dest, const char32_t *p_contents, const int p_size);
+void GDAPI godot_string_new_with_wide_chars_and_len(godot_string *r_dest, const wchar_t *p_contents, const int p_size);
+
+const godot_char_type GDAPI *godot_string_operator_index(godot_string *p_self, const godot_int p_idx);
+godot_char_type GDAPI godot_string_operator_index_const(const godot_string *p_self, const godot_int p_idx);
+const godot_char_type GDAPI *godot_string_get_data(const godot_string *p_self);
godot_bool GDAPI godot_string_operator_equal(const godot_string *p_self, const godot_string *p_b);
godot_bool GDAPI godot_string_operator_less(const godot_string *p_self, const godot_string *p_b);
@@ -89,7 +117,7 @@ godot_string GDAPI godot_string_operator_plus(const godot_string *p_self, const
/* Standard size stuff */
-godot_int GDAPI godot_string_length(const godot_string *p_self);
+/*+++*/ godot_int GDAPI godot_string_length(const godot_string *p_self);
/* Helpers */
@@ -99,25 +127,25 @@ signed char GDAPI godot_string_naturalnocasecmp_to(const godot_string *p_self, c
godot_bool GDAPI godot_string_begins_with(const godot_string *p_self, const godot_string *p_string);
godot_bool GDAPI godot_string_begins_with_char_array(const godot_string *p_self, const char *p_char_array);
-godot_array GDAPI godot_string_bigrams(const godot_string *p_self);
-godot_string GDAPI godot_string_chr(wchar_t p_character);
+godot_packed_string_array GDAPI godot_string_bigrams(const godot_string *p_self);
+godot_string GDAPI godot_string_chr(godot_char_type p_character);
godot_bool GDAPI godot_string_ends_with(const godot_string *p_self, const godot_string *p_string);
-godot_int GDAPI godot_string_count(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to);
-godot_int GDAPI godot_string_countn(const godot_string *p_self, godot_string p_what, godot_int p_from, godot_int p_to);
-godot_int GDAPI godot_string_find(const godot_string *p_self, godot_string p_what);
-godot_int GDAPI godot_string_find_from(const godot_string *p_self, godot_string p_what, godot_int p_from);
-godot_int GDAPI godot_string_findmk(const godot_string *p_self, const godot_array *p_keys);
-godot_int GDAPI godot_string_findmk_from(const godot_string *p_self, const godot_array *p_keys, godot_int p_from);
-godot_int GDAPI godot_string_findmk_from_in_place(const godot_string *p_self, const godot_array *p_keys, godot_int p_from, godot_int *r_key);
-godot_int GDAPI godot_string_findn(const godot_string *p_self, godot_string p_what);
-godot_int GDAPI godot_string_findn_from(const godot_string *p_self, godot_string p_what, godot_int p_from);
-godot_int GDAPI godot_string_find_last(const godot_string *p_self, godot_string p_what);
+godot_bool GDAPI godot_string_ends_with_char_array(const godot_string *p_self, const char *p_char_array);
+godot_int GDAPI godot_string_count(const godot_string *p_self, const godot_string *p_what, godot_int p_from, godot_int p_to);
+godot_int GDAPI godot_string_countn(const godot_string *p_self, const godot_string *p_what, godot_int p_from, godot_int p_to);
+godot_int GDAPI godot_string_find(const godot_string *p_self, const godot_string *p_what);
+godot_int GDAPI godot_string_find_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from);
+godot_int GDAPI godot_string_findmk(const godot_string *p_self, const godot_packed_string_array *p_keys);
+godot_int GDAPI godot_string_findmk_from(const godot_string *p_self, const godot_packed_string_array *p_keys, godot_int p_from);
+godot_int GDAPI godot_string_findmk_from_in_place(const godot_string *p_self, const godot_packed_string_array *p_keys, godot_int p_from, godot_int *r_key);
+godot_int GDAPI godot_string_findn(const godot_string *p_self, const godot_string *p_what);
+godot_int GDAPI godot_string_findn_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from);
godot_string GDAPI godot_string_format(const godot_string *p_self, const godot_variant *p_values);
godot_string GDAPI godot_string_format_with_custom_placeholder(const godot_string *p_self, const godot_variant *p_values, const char *p_placeholder);
godot_string GDAPI godot_string_hex_encode_buffer(const uint8_t *p_buffer, godot_int p_len);
godot_int GDAPI godot_string_hex_to_int(const godot_string *p_self);
-godot_int GDAPI godot_string_hex_to_int_without_prefix(const godot_string *p_self);
-godot_string GDAPI godot_string_insert(const godot_string *p_self, godot_int p_at_pos, godot_string p_string);
+godot_int GDAPI godot_string_hex_to_int_with_prefix(const godot_string *p_self);
+godot_string GDAPI godot_string_insert(const godot_string *p_self, godot_int p_at_pos, const godot_string *p_string);
godot_bool GDAPI godot_string_is_numeric(const godot_string *p_self);
godot_bool GDAPI godot_string_is_subsequence_of(const godot_string *p_self, const godot_string *p_string);
godot_bool GDAPI godot_string_is_subsequence_ofi(const godot_string *p_self, const godot_string *p_string);
@@ -134,92 +162,106 @@ godot_string GDAPI godot_string_num_scientific(double p_num);
godot_string GDAPI godot_string_num_with_decimals(double p_num, godot_int p_decimals);
godot_string GDAPI godot_string_pad_decimals(const godot_string *p_self, godot_int p_digits);
godot_string GDAPI godot_string_pad_zeros(const godot_string *p_self, godot_int p_digits);
-godot_string GDAPI godot_string_replace_first(const godot_string *p_self, godot_string p_key, godot_string p_with);
-godot_string GDAPI godot_string_replace(const godot_string *p_self, godot_string p_key, godot_string p_with);
-godot_string GDAPI godot_string_replacen(const godot_string *p_self, godot_string p_key, godot_string p_with);
-godot_int GDAPI godot_string_rfind(const godot_string *p_self, godot_string p_what);
-godot_int GDAPI godot_string_rfindn(const godot_string *p_self, godot_string p_what);
-godot_int GDAPI godot_string_rfind_from(const godot_string *p_self, godot_string p_what, godot_int p_from);
-godot_int GDAPI godot_string_rfindn_from(const godot_string *p_self, godot_string p_what, godot_int p_from);
+godot_string GDAPI godot_string_replace_first(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with);
+godot_string GDAPI godot_string_replace(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with);
+godot_string GDAPI godot_string_replacen(const godot_string *p_self, const godot_string *p_key, const godot_string *p_with);
+godot_int GDAPI godot_string_rfind(const godot_string *p_self, const godot_string *p_what);
+godot_int GDAPI godot_string_rfindn(const godot_string *p_self, const godot_string *p_what);
+godot_int GDAPI godot_string_rfind_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from);
+godot_int GDAPI godot_string_rfindn_from(const godot_string *p_self, const godot_string *p_what, godot_int p_from);
godot_string GDAPI godot_string_rpad(const godot_string *p_self, godot_int p_min_length);
godot_string GDAPI godot_string_rpad_with_custom_character(const godot_string *p_self, godot_int p_min_length, const godot_string *p_character);
godot_real GDAPI godot_string_similarity(const godot_string *p_self, const godot_string *p_string);
godot_string GDAPI godot_string_sprintf(const godot_string *p_self, const godot_array *p_values, godot_bool *p_error);
godot_string GDAPI godot_string_substr(const godot_string *p_self, godot_int p_from, godot_int p_chars);
-double GDAPI godot_string_to_double(const godot_string *p_self);
-godot_real GDAPI godot_string_to_float(const godot_string *p_self);
+double GDAPI godot_string_to_float(const godot_string *p_self);
godot_int GDAPI godot_string_to_int(const godot_string *p_self);
godot_string GDAPI godot_string_camelcase_to_underscore(const godot_string *p_self);
godot_string GDAPI godot_string_camelcase_to_underscore_lowercased(const godot_string *p_self);
godot_string GDAPI godot_string_capitalize(const godot_string *p_self);
-double GDAPI godot_string_char_to_double(const char *p_what);
+
+double GDAPI godot_string_char_to_float(const char *p_what);
+double GDAPI godot_string_wchar_to_float(const wchar_t *p_str, const wchar_t **r_end);
+
godot_int GDAPI godot_string_char_to_int(const char *p_what);
-int64_t GDAPI godot_string_wchar_to_int(const wchar_t *p_str);
+godot_int GDAPI godot_string_wchar_to_int(const wchar_t *p_str);
+
godot_int GDAPI godot_string_char_to_int_with_len(const char *p_what, godot_int p_len);
-int64_t GDAPI godot_string_char_to_int64_with_len(const wchar_t *p_str, int p_len);
-int64_t GDAPI godot_string_hex_to_int64(const godot_string *p_self);
-int64_t GDAPI godot_string_hex_to_int64_with_prefix(const godot_string *p_self);
-int64_t GDAPI godot_string_to_int64(const godot_string *p_self);
-double GDAPI godot_string_unicode_char_to_double(const wchar_t *p_str, const wchar_t **r_end);
-
-godot_int GDAPI godot_string_get_slice_count(const godot_string *p_self, godot_string p_splitter);
-godot_string GDAPI godot_string_get_slice(const godot_string *p_self, godot_string p_splitter, godot_int p_slice);
-godot_string GDAPI godot_string_get_slicec(const godot_string *p_self, wchar_t p_splitter, godot_int p_slice);
-
-godot_array GDAPI godot_string_split(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_allow_empty(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_floats(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_floats_allows_empty(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_floats_mk(const godot_string *p_self, const godot_array *p_splitters);
-godot_array GDAPI godot_string_split_floats_mk_allows_empty(const godot_string *p_self, const godot_array *p_splitters);
-godot_array GDAPI godot_string_split_ints(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_ints_allows_empty(const godot_string *p_self, const godot_string *p_splitter);
-godot_array GDAPI godot_string_split_ints_mk(const godot_string *p_self, const godot_array *p_splitters);
-godot_array GDAPI godot_string_split_ints_mk_allows_empty(const godot_string *p_self, const godot_array *p_splitters);
-godot_array GDAPI godot_string_split_spaces(const godot_string *p_self);
-
-wchar_t GDAPI godot_string_char_lowercase(wchar_t p_char);
-wchar_t GDAPI godot_string_char_uppercase(wchar_t p_char);
+godot_int GDAPI godot_string_wchar_to_int_with_len(const wchar_t *p_str, int p_len);
+
+godot_int GDAPI godot_string_get_slice_count(const godot_string *p_self, const godot_string *p_splitter);
+godot_string GDAPI godot_string_get_slice(const godot_string *p_self, const godot_string *p_splitter, godot_int p_slice);
+godot_string GDAPI godot_string_get_slicec(const godot_string *p_self, godot_char_type p_splitter, godot_int p_slice);
+
+godot_packed_string_array GDAPI godot_string_split(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_string_array GDAPI godot_string_split_allow_empty(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_string_array GDAPI godot_string_split_with_maxsplit(const godot_string *p_self, const godot_string *p_splitter, const godot_bool p_allow_empty, const godot_int p_maxsplit);
+
+godot_packed_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_string_array GDAPI godot_string_rsplit_allow_empty(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_string_array GDAPI godot_string_rsplit_with_maxsplit(const godot_string *p_self, const godot_string *p_splitter, const godot_bool p_allow_empty, const godot_int p_maxsplit);
+
+godot_packed_float32_array GDAPI godot_string_split_floats(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_float32_array GDAPI godot_string_split_floats_allow_empty(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_float32_array GDAPI godot_string_split_floats_mk(const godot_string *p_self, const godot_packed_string_array *p_splitters);
+godot_packed_float32_array GDAPI godot_string_split_floats_mk_allow_empty(const godot_string *p_self, const godot_packed_string_array *p_splitters);
+godot_packed_int32_array GDAPI godot_string_split_ints(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_int32_array GDAPI godot_string_split_ints_allow_empty(const godot_string *p_self, const godot_string *p_splitter);
+godot_packed_int32_array GDAPI godot_string_split_ints_mk(const godot_string *p_self, const godot_packed_string_array *p_splitters);
+godot_packed_int32_array GDAPI godot_string_split_ints_mk_allow_empty(const godot_string *p_self, const godot_packed_string_array *p_splitters);
+
+godot_packed_string_array GDAPI godot_string_split_spaces(const godot_string *p_self);
+
+godot_char_type GDAPI godot_string_char_lowercase(godot_char_type p_char);
+godot_char_type GDAPI godot_string_char_uppercase(godot_char_type p_char);
godot_string GDAPI godot_string_to_lower(const godot_string *p_self);
godot_string GDAPI godot_string_to_upper(const godot_string *p_self);
godot_string GDAPI godot_string_get_basename(const godot_string *p_self);
godot_string GDAPI godot_string_get_extension(const godot_string *p_self);
godot_string GDAPI godot_string_left(const godot_string *p_self, godot_int p_pos);
-wchar_t GDAPI godot_string_ord_at(const godot_string *p_self, godot_int p_idx);
+godot_char_type GDAPI godot_string_ord_at(const godot_string *p_self, godot_int p_idx);
godot_string GDAPI godot_string_plus_file(const godot_string *p_self, const godot_string *p_file);
godot_string GDAPI godot_string_right(const godot_string *p_self, godot_int p_pos);
+godot_string GDAPI godot_string_repeat(const godot_string *p_self, godot_int p_count);
godot_string GDAPI godot_string_strip_edges(const godot_string *p_self, godot_bool p_left, godot_bool p_right);
godot_string GDAPI godot_string_strip_escapes(const godot_string *p_self);
void GDAPI godot_string_erase(godot_string *p_self, godot_int p_pos, godot_int p_chars);
godot_char_string GDAPI godot_string_ascii(const godot_string *p_self);
-godot_char_string GDAPI godot_string_ascii_extended(const godot_string *p_self);
+godot_char_string GDAPI godot_string_latin1(const godot_string *p_self);
+
godot_char_string GDAPI godot_string_utf8(const godot_string *p_self);
godot_bool GDAPI godot_string_parse_utf8(godot_string *p_self, const char *p_utf8);
godot_bool GDAPI godot_string_parse_utf8_with_len(godot_string *p_self, const char *p_utf8, godot_int p_len);
-godot_string GDAPI godot_string_chars_to_utf8(const char *p_utf8);
-godot_string GDAPI godot_string_chars_to_utf8_with_len(const char *p_utf8, godot_int p_len);
+
+godot_char16_string GDAPI godot_string_utf16(const godot_string *p_self);
+godot_bool GDAPI godot_string_parse_utf16(godot_string *p_self, const char16_t *p_utf16);
+godot_bool GDAPI godot_string_parse_utf16_with_len(godot_string *p_self, const char16_t *p_utf16, godot_int p_len);
uint32_t GDAPI godot_string_hash(const godot_string *p_self);
uint64_t GDAPI godot_string_hash64(const godot_string *p_self);
+
uint32_t GDAPI godot_string_hash_chars(const char *p_cstr);
uint32_t GDAPI godot_string_hash_chars_with_len(const char *p_cstr, godot_int p_len);
-uint32_t GDAPI godot_string_hash_utf8_chars(const wchar_t *p_str);
-uint32_t GDAPI godot_string_hash_utf8_chars_with_len(const wchar_t *p_str, godot_int p_len);
+uint32_t GDAPI godot_string_hash_wide_chars(const wchar_t *p_str);
+uint32_t GDAPI godot_string_hash_wide_chars_with_len(const wchar_t *p_str, godot_int p_len);
+
godot_packed_byte_array GDAPI godot_string_md5_buffer(const godot_string *p_self);
godot_string GDAPI godot_string_md5_text(const godot_string *p_self);
+godot_packed_byte_array GDAPI godot_string_sha1_buffer(const godot_string *p_self);
+godot_string GDAPI godot_string_sha1_text(const godot_string *p_self);
godot_packed_byte_array GDAPI godot_string_sha256_buffer(const godot_string *p_self);
godot_string GDAPI godot_string_sha256_text(const godot_string *p_self);
-godot_bool godot_string_empty(const godot_string *p_self);
+godot_bool godot_string_is_empty(const godot_string *p_self);
// path functions
godot_string GDAPI godot_string_get_base_dir(const godot_string *p_self);
godot_string GDAPI godot_string_get_file(const godot_string *p_self);
-godot_string GDAPI godot_string_humanize_size(size_t p_size);
+godot_string GDAPI godot_string_humanize_size(uint64_t p_size);
godot_bool GDAPI godot_string_is_abs_path(const godot_string *p_self);
godot_bool GDAPI godot_string_is_rel_path(const godot_string *p_self);
godot_bool GDAPI godot_string_is_resource_file(const godot_string *p_self);
@@ -233,14 +275,15 @@ godot_string GDAPI godot_string_c_unescape(const godot_string *p_self);
godot_string GDAPI godot_string_http_escape(const godot_string *p_self);
godot_string GDAPI godot_string_http_unescape(const godot_string *p_self);
godot_string GDAPI godot_string_json_escape(const godot_string *p_self);
-godot_string GDAPI godot_string_word_wrap(const godot_string *p_self, godot_int p_chars_per_line);
godot_string GDAPI godot_string_xml_escape(const godot_string *p_self);
godot_string GDAPI godot_string_xml_escape_with_quotes(const godot_string *p_self);
godot_string GDAPI godot_string_xml_unescape(const godot_string *p_self);
godot_string GDAPI godot_string_percent_decode(const godot_string *p_self);
godot_string GDAPI godot_string_percent_encode(const godot_string *p_self);
+godot_string GDAPI godot_string_join(const godot_string *p_self, const godot_packed_string_array *p_parts);
+godot_bool GDAPI godot_string_is_valid_filename(const godot_string *p_self);
godot_bool GDAPI godot_string_is_valid_float(const godot_string *p_self);
godot_bool GDAPI godot_string_is_valid_hex_number(const godot_string *p_self, godot_bool p_with_prefix);
godot_bool GDAPI godot_string_is_valid_html_color(const godot_string *p_self);
@@ -251,8 +294,8 @@ godot_bool GDAPI godot_string_is_valid_ip_address(const godot_string *p_self);
godot_string GDAPI godot_string_dedent(const godot_string *p_self);
godot_string GDAPI godot_string_trim_prefix(const godot_string *p_self, const godot_string *p_prefix);
godot_string GDAPI godot_string_trim_suffix(const godot_string *p_self, const godot_string *p_suffix);
+godot_string GDAPI godot_string_lstrip(const godot_string *p_self, const godot_string *p_chars);
godot_string GDAPI godot_string_rstrip(const godot_string *p_self, const godot_string *p_chars);
-godot_packed_string_array GDAPI godot_string_rsplit(const godot_string *p_self, const godot_string *p_divisor, const godot_bool p_allow_empty, const godot_int p_maxsplit);
void GDAPI godot_string_destroy(godot_string *p_self);
diff --git a/modules/gdnative/include/gdnative/string_name.h b/modules/gdnative/include/gdnative/string_name.h
index f2555ab98f..b468f716e1 100644
--- a/modules/gdnative/include/gdnative/string_name.h
+++ b/modules/gdnative/include/gdnative/string_name.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/transform.h b/modules/gdnative/include/gdnative/transform.h
index bc51438b17..948cb2ecfd 100644
--- a/modules/gdnative/include/gdnative/transform.h
+++ b/modules/gdnative/include/gdnative/transform.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/transform2d.h b/modules/gdnative/include/gdnative/transform2d.h
index 6b414ca7b2..51c5306c7d 100644
--- a/modules/gdnative/include/gdnative/transform2d.h
+++ b/modules/gdnative/include/gdnative/transform2d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/gdnative/variant.h b/modules/gdnative/include/gdnative/variant.h
index 934e856fbf..a50947cb72 100644
--- a/modules/gdnative/include/gdnative/variant.h
+++ b/modules/gdnative/include/gdnative/variant.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,7 +37,7 @@ extern "C" {
#include <stdint.h>
-#define GODOT_VARIANT_SIZE (16 + sizeof(void *))
+#define GODOT_VARIANT_SIZE (16 + sizeof(int64_t))
#ifndef GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED
@@ -52,7 +52,7 @@ typedef enum godot_variant_type {
// atomic types
GODOT_VARIANT_TYPE_BOOL,
GODOT_VARIANT_TYPE_INT,
- GODOT_VARIANT_TYPE_REAL,
+ GODOT_VARIANT_TYPE_FLOAT,
GODOT_VARIANT_TYPE_STRING,
// math types
@@ -71,16 +71,21 @@ typedef enum godot_variant_type {
// misc types
GODOT_VARIANT_TYPE_COLOR,
+ GODOT_VARIANT_TYPE_STRING_NAME,
GODOT_VARIANT_TYPE_NODE_PATH,
GODOT_VARIANT_TYPE_RID,
GODOT_VARIANT_TYPE_OBJECT,
+ GODOT_VARIANT_TYPE_CALLABLE,
+ GODOT_VARIANT_TYPE_SIGNAL,
GODOT_VARIANT_TYPE_DICTIONARY,
GODOT_VARIANT_TYPE_ARRAY,
// arrays
GODOT_VARIANT_TYPE_PACKED_BYTE_ARRAY,
- GODOT_VARIANT_TYPE_PACKED_INT_ARRAY,
- GODOT_VARIANT_TYPE_PACKED_REAL_ARRAY,
+ GODOT_VARIANT_TYPE_PACKED_INT32_ARRAY,
+ GODOT_VARIANT_TYPE_PACKED_INT64_ARRAY,
+ GODOT_VARIANT_TYPE_PACKED_FLOAT32_ARRAY,
+ GODOT_VARIANT_TYPE_PACKED_FLOAT64_ARRAY,
GODOT_VARIANT_TYPE_PACKED_STRING_ARRAY,
GODOT_VARIANT_TYPE_PACKED_VECTOR2_ARRAY,
GODOT_VARIANT_TYPE_PACKED_VECTOR3_ARRAY,
@@ -149,15 +154,17 @@ typedef enum godot_variant_operator {
#include <gdnative/aabb.h>
#include <gdnative/array.h>
#include <gdnative/basis.h>
+#include <gdnative/callable.h>
#include <gdnative/color.h>
#include <gdnative/dictionary.h>
#include <gdnative/node_path.h>
+#include <gdnative/packed_arrays.h>
#include <gdnative/plane.h>
-#include <gdnative/pool_arrays.h>
#include <gdnative/quat.h>
#include <gdnative/rect2.h>
#include <gdnative/rid.h>
#include <gdnative/string.h>
+#include <gdnative/string_name.h>
#include <gdnative/transform.h>
#include <gdnative/transform2d.h>
#include <gdnative/variant.h>
@@ -181,9 +188,13 @@ void GDAPI godot_variant_new_uint(godot_variant *r_dest, const uint64_t p_i);
void GDAPI godot_variant_new_int(godot_variant *r_dest, const int64_t p_i);
void GDAPI godot_variant_new_real(godot_variant *r_dest, const double p_r);
void GDAPI godot_variant_new_string(godot_variant *r_dest, const godot_string *p_s);
+void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s);
void GDAPI godot_variant_new_vector2(godot_variant *r_dest, const godot_vector2 *p_v2);
+void GDAPI godot_variant_new_vector2i(godot_variant *r_dest, const godot_vector2i *p_v2);
void GDAPI godot_variant_new_rect2(godot_variant *r_dest, const godot_rect2 *p_rect2);
+void GDAPI godot_variant_new_rect2i(godot_variant *r_dest, const godot_rect2i *p_rect2);
void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 *p_v3);
+void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3);
void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d);
void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_plane);
void GDAPI godot_variant_new_quat(godot_variant *r_dest, const godot_quat *p_quat);
@@ -193,12 +204,16 @@ void GDAPI godot_variant_new_transform(godot_variant *r_dest, const godot_transf
void GDAPI godot_variant_new_color(godot_variant *r_dest, const godot_color *p_color);
void GDAPI godot_variant_new_node_path(godot_variant *r_dest, const godot_node_path *p_np);
void GDAPI godot_variant_new_rid(godot_variant *r_dest, const godot_rid *p_rid);
+void GDAPI godot_variant_new_callable(godot_variant *r_dest, const godot_callable *p_callable);
+void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p_signal);
void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj);
void GDAPI godot_variant_new_dictionary(godot_variant *r_dest, const godot_dictionary *p_dict);
void GDAPI godot_variant_new_array(godot_variant *r_dest, const godot_array *p_arr);
void GDAPI godot_variant_new_packed_byte_array(godot_variant *r_dest, const godot_packed_byte_array *p_pba);
-void GDAPI godot_variant_new_packed_int_array(godot_variant *r_dest, const godot_packed_int_array *p_pia);
-void GDAPI godot_variant_new_packed_real_array(godot_variant *r_dest, const godot_packed_real_array *p_pra);
+void GDAPI godot_variant_new_packed_int32_array(godot_variant *r_dest, const godot_packed_int32_array *p_pia);
+void GDAPI godot_variant_new_packed_int64_array(godot_variant *r_dest, const godot_packed_int64_array *p_pia);
+void GDAPI godot_variant_new_packed_float32_array(godot_variant *r_dest, const godot_packed_float32_array *p_pra);
+void GDAPI godot_variant_new_packed_float64_array(godot_variant *r_dest, const godot_packed_float64_array *p_pra);
void GDAPI godot_variant_new_packed_string_array(godot_variant *r_dest, const godot_packed_string_array *p_psa);
void GDAPI godot_variant_new_packed_vector2_array(godot_variant *r_dest, const godot_packed_vector2_array *p_pv2a);
void GDAPI godot_variant_new_packed_vector3_array(godot_variant *r_dest, const godot_packed_vector3_array *p_pv3a);
@@ -209,9 +224,13 @@ uint64_t GDAPI godot_variant_as_uint(const godot_variant *p_self);
int64_t GDAPI godot_variant_as_int(const godot_variant *p_self);
double GDAPI godot_variant_as_real(const godot_variant *p_self);
godot_string GDAPI godot_variant_as_string(const godot_variant *p_self);
+godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self);
godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self);
+godot_vector2i GDAPI godot_variant_as_vector2i(const godot_variant *p_self);
godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self);
+godot_rect2i GDAPI godot_variant_as_rect2i(const godot_variant *p_self);
godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self);
+godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self);
godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self);
godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self);
godot_quat GDAPI godot_variant_as_quat(const godot_variant *p_self);
@@ -221,12 +240,16 @@ godot_transform GDAPI godot_variant_as_transform(const godot_variant *p_self);
godot_color GDAPI godot_variant_as_color(const godot_variant *p_self);
godot_node_path GDAPI godot_variant_as_node_path(const godot_variant *p_self);
godot_rid GDAPI godot_variant_as_rid(const godot_variant *p_self);
+godot_callable GDAPI godot_variant_as_callable(const godot_variant *p_self);
+godot_signal GDAPI godot_variant_as_signal(const godot_variant *p_self);
godot_object GDAPI *godot_variant_as_object(const godot_variant *p_self);
godot_dictionary GDAPI godot_variant_as_dictionary(const godot_variant *p_self);
godot_array GDAPI godot_variant_as_array(const godot_variant *p_self);
godot_packed_byte_array GDAPI godot_variant_as_packed_byte_array(const godot_variant *p_self);
-godot_packed_int_array GDAPI godot_variant_as_packed_int_array(const godot_variant *p_self);
-godot_packed_real_array GDAPI godot_variant_as_packed_real_array(const godot_variant *p_self);
+godot_packed_int32_array GDAPI godot_variant_as_packed_int32_array(const godot_variant *p_self);
+godot_packed_int64_array GDAPI godot_variant_as_packed_int64_array(const godot_variant *p_self);
+godot_packed_float32_array GDAPI godot_variant_as_packed_float32_array(const godot_variant *p_self);
+godot_packed_float64_array GDAPI godot_variant_as_packed_float64_array(const godot_variant *p_self);
godot_packed_string_array GDAPI godot_variant_as_packed_string_array(const godot_variant *p_self);
godot_packed_vector2_array GDAPI godot_variant_as_packed_vector2_array(const godot_variant *p_self);
godot_packed_vector3_array GDAPI godot_variant_as_packed_vector3_array(const godot_variant *p_self);
@@ -239,6 +262,7 @@ godot_bool GDAPI godot_variant_has_method(const godot_variant *p_self, const god
godot_bool GDAPI godot_variant_operator_equal(const godot_variant *p_self, const godot_variant *p_other);
godot_bool GDAPI godot_variant_operator_less(const godot_variant *p_self, const godot_variant *p_other);
+uint32_t GDAPI godot_variant_hash(const godot_variant *p_self);
godot_bool GDAPI godot_variant_hash_compare(const godot_variant *p_self, const godot_variant *p_other);
godot_bool GDAPI godot_variant_booleanize(const godot_variant *p_self);
diff --git a/modules/gdnative/include/gdnative/vector2.h b/modules/gdnative/include/gdnative/vector2.h
index c11e23a586..eb146a9232 100644
--- a/modules/gdnative/include/gdnative/vector2.h
+++ b/modules/gdnative/include/gdnative/vector2.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,6 +46,15 @@ typedef struct {
} godot_vector2;
#endif
+#define GODOT_VECTOR2I_SIZE 8
+
+#ifndef GODOT_CORE_API_GODOT_VECTOR2I_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_VECTOR2I_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR2I_SIZE];
+} godot_vector2i;
+#endif
+
// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
@@ -57,10 +66,14 @@ typedef struct {
extern "C" {
#endif
+// Vector2
+
void GDAPI godot_vector2_new(godot_vector2 *r_dest, const godot_real p_x, const godot_real p_y);
godot_string GDAPI godot_vector2_as_string(const godot_vector2 *p_self);
+godot_vector2i GDAPI godot_vector2_as_vector2i(const godot_vector2 *p_self);
+
godot_vector2 GDAPI godot_vector2_normalized(const godot_vector2 *p_self);
godot_real GDAPI godot_vector2_length(const godot_vector2 *p_self);
@@ -89,10 +102,12 @@ godot_vector2 GDAPI godot_vector2_move_toward(const godot_vector2 *p_self, const
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);
+godot_vector2 GDAPI godot_vector2_orthogonal(const godot_vector2 *p_self);
godot_vector2 GDAPI godot_vector2_floor(const godot_vector2 *p_self);
+godot_vector2 GDAPI godot_vector2_sign(const godot_vector2 *p_self);
+
godot_vector2 GDAPI godot_vector2_snapped(const godot_vector2 *p_self, const godot_vector2 *p_by);
godot_real GDAPI godot_vector2_aspect(const godot_vector2 *p_self);
@@ -135,6 +150,46 @@ godot_real GDAPI godot_vector2_get_x(const godot_vector2 *p_self);
godot_real GDAPI godot_vector2_get_y(const godot_vector2 *p_self);
+// Vector2i
+
+void GDAPI godot_vector2i_new(godot_vector2i *r_dest, const godot_int p_x, const godot_int p_y);
+
+godot_string GDAPI godot_vector2i_as_string(const godot_vector2i *p_self);
+
+godot_vector2 GDAPI godot_vector2i_as_vector2(const godot_vector2i *p_self);
+
+godot_real GDAPI godot_vector2i_aspect(const godot_vector2i *p_self);
+
+godot_vector2i GDAPI godot_vector2i_abs(const godot_vector2i *p_self);
+
+godot_vector2i GDAPI godot_vector2i_sign(const godot_vector2i *p_self);
+
+godot_vector2i GDAPI godot_vector2i_operator_add(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_subtract(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_multiply_vector(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_multiply_scalar(const godot_vector2i *p_self, const godot_int p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_divide_vector(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_divide_scalar(const godot_vector2i *p_self, const godot_int p_b);
+
+godot_bool GDAPI godot_vector2i_operator_equal(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_bool GDAPI godot_vector2i_operator_less(const godot_vector2i *p_self, const godot_vector2i *p_b);
+
+godot_vector2i GDAPI godot_vector2i_operator_neg(const godot_vector2i *p_self);
+
+void GDAPI godot_vector2i_set_x(godot_vector2i *p_self, const godot_int p_x);
+
+void GDAPI godot_vector2i_set_y(godot_vector2i *p_self, const godot_int p_y);
+
+godot_int GDAPI godot_vector2i_get_x(const godot_vector2i *p_self);
+
+godot_int GDAPI godot_vector2i_get_y(const godot_vector2i *p_self);
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/include/gdnative/vector3.h b/modules/gdnative/include/gdnative/vector3.h
index 8ebf15b724..e0205c2fc7 100644
--- a/modules/gdnative/include/gdnative/vector3.h
+++ b/modules/gdnative/include/gdnative/vector3.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,6 +46,15 @@ typedef struct {
} godot_vector3;
#endif
+#define GODOT_VECTOR3I_SIZE 12
+
+#ifndef GODOT_CORE_API_GODOT_VECTOR3I_TYPE_DEFINED
+#define GODOT_CORE_API_GODOT_VECTOR3I_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_VECTOR3I_SIZE];
+} godot_vector3i;
+#endif
+
// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
@@ -64,10 +73,14 @@ typedef enum {
GODOT_VECTOR3_AXIS_Z,
} godot_vector3_axis;
+// Vector3
+
void GDAPI godot_vector3_new(godot_vector3 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z);
godot_string GDAPI godot_vector3_as_string(const godot_vector3 *p_self);
+godot_vector3i GDAPI godot_vector3_as_vector3i(const godot_vector3 *p_self);
+
godot_int GDAPI godot_vector3_min_axis(const godot_vector3 *p_self);
godot_int GDAPI godot_vector3_max_axis(const godot_vector3 *p_self);
@@ -102,6 +115,8 @@ godot_basis GDAPI godot_vector3_to_diagonal_matrix(const godot_vector3 *p_self);
godot_vector3 GDAPI godot_vector3_abs(const godot_vector3 *p_self);
+godot_vector3 GDAPI godot_vector3_sign(const godot_vector3 *p_self);
+
godot_vector3 GDAPI godot_vector3_floor(const godot_vector3 *p_self);
godot_vector3 GDAPI godot_vector3_ceil(const godot_vector3 *p_self);
@@ -142,6 +157,44 @@ void GDAPI godot_vector3_set_axis(godot_vector3 *p_self, const godot_vector3_axi
godot_real GDAPI godot_vector3_get_axis(const godot_vector3 *p_self, const godot_vector3_axis p_axis);
+// Vector3i
+
+void GDAPI godot_vector3i_new(godot_vector3i *r_dest, const godot_int p_x, const godot_int p_y, const godot_int p_z);
+
+godot_string GDAPI godot_vector3i_as_string(const godot_vector3i *p_self);
+
+godot_vector3 GDAPI godot_vector3i_as_vector3(const godot_vector3i *p_self);
+
+godot_int GDAPI godot_vector3i_min_axis(const godot_vector3i *p_self);
+
+godot_int GDAPI godot_vector3i_max_axis(const godot_vector3i *p_self);
+
+godot_vector3i GDAPI godot_vector3i_abs(const godot_vector3i *p_self);
+
+godot_vector3i GDAPI godot_vector3i_sign(const godot_vector3i *p_self);
+
+godot_vector3i GDAPI godot_vector3i_operator_add(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_subtract(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_multiply_vector(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_multiply_scalar(const godot_vector3i *p_self, const godot_int p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_divide_vector(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_divide_scalar(const godot_vector3i *p_self, const godot_int p_b);
+
+godot_bool GDAPI godot_vector3i_operator_equal(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_bool GDAPI godot_vector3i_operator_less(const godot_vector3i *p_self, const godot_vector3i *p_b);
+
+godot_vector3i GDAPI godot_vector3i_operator_neg(const godot_vector3i *p_self);
+
+void GDAPI godot_vector3i_set_axis(godot_vector3i *p_self, const godot_vector3_axis p_axis, const godot_int p_val);
+
+godot_int GDAPI godot_vector3i_get_axis(const godot_vector3i *p_self, const godot_vector3_axis p_axis);
+
#ifdef __cplusplus
}
#endif
diff --git a/modules/gdnative/include/nativescript/godot_nativescript.h b/modules/gdnative/include/nativescript/godot_nativescript.h
index 0fb5180103..73b1738b03 100644
--- a/modules/gdnative/include/nativescript/godot_nativescript.h
+++ b/modules/gdnative/include/nativescript/godot_nativescript.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,7 +45,7 @@ typedef enum {
GODOT_METHOD_RPC_MODE_REMOTESYNC,
GODOT_METHOD_RPC_MODE_MASTERSYNC,
GODOT_METHOD_RPC_MODE_PUPPETSYNC,
-} godot_method_rpc_mode;
+} godot_nativescript_method_rpc_mode;
typedef enum {
GODOT_PROPERTY_HINT_NONE, ///< no hint provided.
@@ -82,10 +82,9 @@ typedef enum {
GODOT_PROPERTY_HINT_PROPERTY_OF_INSTANCE, ///< a property of an instance
GODOT_PROPERTY_HINT_PROPERTY_OF_SCRIPT, ///< a property of a script & base
GODOT_PROPERTY_HINT_MAX,
-} godot_property_hint;
+} godot_nativescript_property_hint;
typedef enum {
-
GODOT_PROPERTY_USAGE_STORAGE = 1,
GODOT_PROPERTY_USAGE_EDITOR = 2,
GODOT_PROPERTY_USAGE_NETWORK = 4,
@@ -106,106 +105,95 @@ typedef enum {
GODOT_PROPERTY_USAGE_DEFAULT = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK,
GODOT_PROPERTY_USAGE_DEFAULT_INTL = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK | GODOT_PROPERTY_USAGE_INTERNATIONALIZED,
GODOT_PROPERTY_USAGE_NOEDITOR = GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_NETWORK,
-} godot_property_usage_flags;
+} godot_nativescript_property_usage_flags;
typedef struct {
- godot_method_rpc_mode rset_type;
+ godot_nativescript_method_rpc_mode rset_type;
godot_int type;
- godot_property_hint hint;
+ godot_nativescript_property_hint hint;
godot_string hint_string;
- godot_property_usage_flags usage;
+ godot_nativescript_property_usage_flags usage;
godot_variant default_value;
-} godot_property_attributes;
+} godot_nativescript_property_attributes;
typedef struct {
// instance pointer, method_data - return user data
GDCALLINGCONV void *(*create_func)(godot_object *, void *);
void *method_data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_instance_create_func;
+} godot_nativescript_instance_create_func;
typedef struct {
// instance pointer, method data, user data
GDCALLINGCONV void (*destroy_func)(godot_object *, void *, void *);
void *method_data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_instance_destroy_func;
+} godot_nativescript_instance_destroy_func;
+
+void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func);
-void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_instance_create_func p_create_func, godot_instance_destroy_func p_destroy_func);
+void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func);
-void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_instance_create_func p_create_func, godot_instance_destroy_func p_destroy_func);
+typedef struct {
+ godot_nativescript_method_rpc_mode rpc_type;
+} godot_nativescript_method_attributes;
typedef struct {
- godot_method_rpc_mode rpc_type;
-} godot_method_attributes;
+ godot_string name;
+
+ godot_variant_type type;
+ godot_nativescript_property_hint hint;
+ godot_string hint_string;
+} godot_nativescript_method_argument;
typedef struct {
// instance pointer, method data, user data, num args, args - return result as varaint
GDCALLINGCONV godot_variant (*method)(godot_object *, void *, void *, int, godot_variant **);
void *method_data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_instance_method;
+} godot_nativescript_instance_method;
-void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_method_attributes p_attr, godot_instance_method p_method);
+void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_nativescript_method_attributes p_attr, godot_nativescript_instance_method p_method);
+void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_nativescript_method_argument *p_args);
typedef struct {
// instance pointer, method data, user data, value
GDCALLINGCONV void (*set_func)(godot_object *, void *, void *, godot_variant *);
void *method_data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_property_set_func;
+} godot_nativescript_property_set_func;
typedef struct {
// instance pointer, method data, user data, value
GDCALLINGCONV godot_variant (*get_func)(godot_object *, void *, void *);
void *method_data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_property_get_func;
+} godot_nativescript_property_get_func;
-void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_property_attributes *p_attr, godot_property_set_func p_set_func, godot_property_get_func p_get_func);
+void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_nativescript_property_attributes *p_attr, godot_nativescript_property_set_func p_set_func, godot_nativescript_property_get_func p_get_func);
typedef struct {
godot_string name;
godot_int type;
- godot_property_hint hint;
+ godot_nativescript_property_hint hint;
godot_string hint_string;
- godot_property_usage_flags usage;
+ godot_nativescript_property_usage_flags usage;
godot_variant default_value;
-} godot_signal_argument;
+} godot_nativescript_signal_argument;
typedef struct {
godot_string name;
int num_args;
- godot_signal_argument *args;
+ godot_nativescript_signal_argument *args;
int num_default_args;
godot_variant *default_args;
-} godot_signal;
+} godot_nativescript_signal;
-void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_signal *p_signal);
+void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_nativescript_signal *p_signal);
void GDAPI *godot_nativescript_get_userdata(godot_object *p_instance);
-/*
- *
- *
- * NativeScript 1.1
- *
- *
- */
-
-// method registering with argument names
-
-typedef struct {
- godot_string name;
-
- godot_variant_type type;
- godot_property_hint hint;
- godot_string hint_string;
-} godot_method_arg;
-
-void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_method_arg *p_args);
-
// documentation
void GDAPI godot_nativescript_set_class_documentation(void *p_gdnative_handle, const char *p_name, godot_string p_documentation);
@@ -230,9 +218,9 @@ typedef struct {
GDCALLINGCONV bool (*refcount_decremented_instance_binding)(void *, godot_object *);
void *data;
GDCALLINGCONV void (*free_func)(void *);
-} godot_instance_binding_functions;
+} godot_nativescript_instance_binding_functions;
-int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_instance_binding_functions p_binding_functions);
+int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_nativescript_instance_binding_functions p_binding_functions);
void GDAPI godot_nativescript_unregister_instance_binding_data_functions(int p_idx);
void GDAPI *godot_nativescript_get_instance_binding_data(int p_idx, godot_object *p_object);
diff --git a/modules/gdnative/include/net/godot_net.h b/modules/gdnative/include/net/godot_net.h
index d245f3b965..2fa576a5bf 100644
--- a/modules/gdnative/include/net/godot_net.h
+++ b/modules/gdnative/include/net/godot_net.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,7 +45,6 @@ extern "C" {
#define GODOT_NET_API_MINOR 1
typedef struct {
-
godot_gdnative_api_version version; /* version of our API */
godot_object *data; /* User reference */
diff --git a/modules/gdnative/include/net/godot_webrtc.h b/modules/gdnative/include/net/godot_webrtc.h
index 15e2df85cc..25aa72dae1 100644
--- a/modules/gdnative/include/net/godot_webrtc.h
+++ b/modules/gdnative/include/net/godot_webrtc.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h
index 406c3ba663..cbd65e3772 100644
--- a/modules/gdnative/include/pluginscript/godot_pluginscript.h
+++ b/modules/gdnative/include/pluginscript/godot_pluginscript.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -72,6 +72,7 @@ typedef struct {
godot_string_name name;
godot_bool is_tool;
godot_string_name base;
+ godot_string icon_path;
// Member lines format: {<string>: <int>}
godot_dictionary member_lines;
@@ -127,6 +128,7 @@ typedef struct {
const char **string_delimiters; // nullptr terminated array
godot_bool has_named_classes;
godot_bool supports_builtin_mode;
+ godot_bool can_inherit_from_file;
godot_string (*get_template_source_code)(godot_pluginscript_language_data *p_data, const godot_string *p_class_name, const godot_string *p_base_class_name);
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_packed_string_array *r_functions);
diff --git a/modules/gdnative/include/text/godot_text.h b/modules/gdnative/include/text/godot_text.h
new file mode 100644
index 0000000000..9de47edf87
--- /dev/null
+++ b/modules/gdnative/include/text/godot_text.h
@@ -0,0 +1,231 @@
+/*************************************************************************/
+/* godot_text.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GODOT_NATIVETEXT_H
+#define GODOT_NATIVETEXT_H
+
+#include <gdnative/gdnative.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define GODOT_TEXT_API_MAJOR 1
+#define GODOT_TEXT_API_MINOR 0
+
+#define GODOT_GLYPH_SIZE 40
+
+#ifndef GODOT_TEXT_API_GODOT_GLYPH_TYPE_DEFINED
+#define GODOT_TEXT_API_GODOT_GLYPH_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_GLYPH_SIZE];
+} godot_glyph;
+#endif
+
+#define GODOT_PACKED_GLYPH_ARRAY_SIZE (2 * sizeof(void *))
+
+#ifndef GODOT_TEXT_API_GODOT_PACKED_GLYPH_ARRAY_TYPE_DEFINED
+#define GODOT_TEXT_API_GODOT_PACKED_GLYPH_ARRAY_TYPE_DEFINED
+typedef struct {
+ uint8_t _dont_touch_that[GODOT_PACKED_GLYPH_ARRAY_SIZE];
+} godot_packed_glyph_array;
+#endif
+
+typedef struct {
+ godot_gdnative_api_version version;
+ void *(*constructor)(godot_object *);
+ void (*destructor)(void *);
+ godot_string (*get_name)(const void *);
+ godot_bool (*has_feature)(const void *, godot_int);
+ bool (*load_support_data)(void *, const godot_string *);
+ godot_string (*get_support_data_filename)(const void *);
+ godot_string (*get_support_data_info)(const void *);
+ bool (*save_support_data)(void *, const godot_string *);
+ bool (*is_locale_right_to_left)(void *, const godot_string *);
+ void (*free)(void *, godot_rid *);
+ bool (*has)(void *, godot_rid *);
+ godot_rid (*create_font_system)(void *, const godot_string *, int);
+ godot_rid (*create_font_resource)(void *, const godot_string *, int);
+ godot_rid (*create_font_memory)(void *, const uint8_t *, size_t, godot_string *, int);
+ float (*font_get_height)(void *, godot_rid *, int);
+ float (*font_get_ascent)(void *, godot_rid *, int);
+ float (*font_get_descent)(void *, godot_rid *, int);
+ float (*font_get_underline_position)(void *, godot_rid *, int);
+ float (*font_get_underline_thickness)(void *, godot_rid *, int);
+ void (*font_set_antialiased)(void *, godot_rid *, bool);
+ bool (*font_get_antialiased)(void *, godot_rid *);
+ godot_dictionary (*font_get_feature_list)(void *, godot_rid *);
+ godot_dictionary (*font_get_variation_list)(void *, godot_rid *);
+ void (*font_set_variation)(void *, godot_rid *, const godot_string *, double);
+ double (*font_get_variation)(void *, godot_rid *, const godot_string *);
+ void (*font_set_distance_field_hint)(void *, godot_rid *, bool);
+ bool (*font_get_distance_field_hint)(void *, godot_rid *);
+ void (*font_set_hinting)(void *, godot_rid *, godot_int);
+ godot_int (*font_get_hinting)(void *, godot_rid *);
+ void (*font_set_force_autohinter)(void *, godot_rid *, bool);
+ bool (*font_get_force_autohinter)(void *, godot_rid *);
+ bool (*font_has_char)(void *, godot_rid *, char32_t);
+ godot_string (*font_get_supported_chars)(void *, godot_rid *);
+ bool (*font_has_outline)(void *, godot_rid *);
+ int (*font_get_base_size)(void *, godot_rid *);
+ bool (*font_is_language_supported)(void *, godot_rid *, const godot_string *);
+ void (*font_set_language_support_override)(void *, godot_rid *, const godot_string *, bool);
+ bool (*font_get_language_support_override)(void *, godot_rid *, const godot_string *);
+ void (*font_remove_language_support_override)(void *, godot_rid *, const godot_string *);
+ godot_packed_string_array (*font_get_language_support_overrides)(void *, godot_rid *);
+ bool (*font_is_script_supported)(void *, godot_rid *, const godot_string *);
+ void (*font_set_script_support_override)(void *, godot_rid *, const godot_string *, bool);
+ bool (*font_get_script_support_override)(void *, godot_rid *, const godot_string *);
+ void (*font_remove_script_support_override)(void *, godot_rid *, const godot_string *);
+ godot_packed_string_array (*font_get_script_support_overrides)(void *, godot_rid *);
+ uint32_t (*font_get_glyph_index)(void *, godot_rid *, char32_t, char32_t);
+ godot_vector2 (*font_get_glyph_advance)(void *, godot_rid *, uint32_t, int);
+ godot_vector2 (*font_get_glyph_kerning)(void *, godot_rid *, uint32_t, uint32_t, int);
+ godot_vector2 (*font_draw_glyph)(void *, godot_rid *, godot_rid *, int, const godot_vector2 *, uint32_t, const godot_color *);
+ godot_vector2 (*font_draw_glyph_outline)(void *, godot_rid *, godot_rid *, int, int, const godot_vector2 *, uint32_t, const godot_color *);
+ float (*font_get_oversampling)(void *);
+ void (*font_set_oversampling)(void *, float);
+ godot_packed_string_array (*get_system_fonts)(void *);
+ godot_rid (*create_shaped_text)(void *, godot_int, godot_int);
+ void (*shaped_text_clear)(void *, godot_rid *);
+ void (*shaped_text_set_direction)(void *, godot_rid *, godot_int);
+ godot_int (*shaped_text_get_direction)(void *, godot_rid *);
+ void (*shaped_text_set_bidi_override)(void *, godot_rid *, const godot_packed_vector2i_array *);
+ void (*shaped_text_set_orientation)(void *, godot_rid *, godot_int);
+ godot_int (*shaped_text_get_orientation)(void *, godot_rid *);
+ void (*shaped_text_set_preserve_invalid)(void *, godot_rid *, bool);
+ bool (*shaped_text_get_preserve_invalid)(void *, godot_rid *);
+ void (*shaped_text_set_preserve_control)(void *, godot_rid *, bool);
+ bool (*shaped_text_get_preserve_control)(void *, godot_rid *);
+ bool (*shaped_text_add_string)(void *, godot_rid *, const godot_string *, const godot_rid **, int, const godot_dictionary *, const godot_string *);
+ bool (*shaped_text_add_object)(void *, godot_rid *, const godot_variant *, const godot_vector2 *, godot_int, godot_int);
+ bool (*shaped_text_resize_object)(void *, godot_rid *, const godot_variant *, const godot_vector2 *, godot_int);
+ godot_rid (*shaped_text_substr)(void *, godot_rid *, godot_int, godot_int);
+ godot_rid (*shaped_text_get_parent)(void *, godot_rid *);
+ float (*shaped_text_fit_to_width)(void *, godot_rid *, float, uint8_t);
+ float (*shaped_text_tab_align)(void *, godot_rid *, godot_packed_float32_array *);
+ bool (*shaped_text_shape)(void *, godot_rid *);
+ bool (*shaped_text_update_breaks)(void *, godot_rid *);
+ bool (*shaped_text_update_justification_ops)(void *, godot_rid *);
+ bool (*shaped_text_is_ready)(void *, godot_rid *);
+ godot_packed_glyph_array (*shaped_text_get_glyphs)(void *, godot_rid *);
+ godot_vector2i (*shaped_text_get_range)(void *, godot_rid *);
+ godot_packed_glyph_array (*shaped_text_sort_logical)(void *, godot_rid *);
+ godot_packed_vector2i_array (*shaped_text_get_line_breaks_adv)(void *, godot_rid *, godot_packed_float32_array *, int, bool, uint8_t);
+ godot_packed_vector2i_array (*shaped_text_get_line_breaks)(void *, godot_rid *, float, int, uint8_t);
+ godot_packed_vector2i_array (*shaped_text_get_word_breaks)(void *, godot_rid *);
+ godot_array (*shaped_text_get_objects)(void *, godot_rid *);
+ godot_rect2 (*shaped_text_get_object_rect)(void *, godot_rid *, const godot_variant *);
+ godot_vector2 (*shaped_text_get_size)(void *, godot_rid *);
+ float (*shaped_text_get_ascent)(void *, godot_rid *);
+ float (*shaped_text_get_descent)(void *, godot_rid *);
+ float (*shaped_text_get_width)(void *, godot_rid *);
+ float (*shaped_text_get_underline_position)(void *, godot_rid *);
+ float (*shaped_text_get_underline_thickness)(void *, godot_rid *);
+ godot_string (*format_number)(void *, const godot_string *, const godot_string *);
+ godot_string (*parse_number)(void *, const godot_string *, const godot_string *);
+ godot_string (*percent_sign)(void *, const godot_string *);
+} godot_text_interface_gdnative;
+
+void GDAPI godot_text_register_interface(const godot_text_interface_gdnative *p_interface, const godot_string *p_name, uint32_t p_features);
+
+// Glyph
+
+void GDAPI godot_glyph_new(godot_glyph *r_dest);
+
+godot_vector2i GDAPI godot_glyph_get_range(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_range(godot_glyph *p_self, const godot_vector2i *p_range);
+
+godot_int GDAPI godot_glyph_get_count(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_count(godot_glyph *p_self, godot_int p_count);
+
+godot_int GDAPI godot_glyph_get_repeat(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_repeat(godot_glyph *p_self, godot_int p_repeat);
+
+godot_int GDAPI godot_glyph_get_flags(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_flags(godot_glyph *p_self, godot_int p_flags);
+
+godot_vector2 GDAPI godot_glyph_get_offset(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_offset(godot_glyph *p_self, const godot_vector2 *p_offset);
+
+godot_real GDAPI godot_glyph_get_advance(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_advance(godot_glyph *p_self, godot_real p_advance);
+
+godot_rid GDAPI godot_glyph_get_font(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_font(godot_glyph *p_self, godot_rid *p_font);
+
+godot_int GDAPI godot_glyph_get_font_size(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_font_size(godot_glyph *p_self, godot_int p_size);
+
+godot_int GDAPI godot_glyph_get_index(const godot_glyph *p_self);
+void GDAPI godot_glyph_set_index(godot_glyph *p_self, godot_int p_index);
+
+// GlyphArray
+
+void GDAPI godot_packed_glyph_array_new(godot_packed_glyph_array *r_dest);
+void GDAPI godot_packed_glyph_array_new_copy(godot_packed_glyph_array *r_dest, const godot_packed_glyph_array *p_src);
+
+const godot_glyph GDAPI *godot_packed_glyph_array_ptr(const godot_packed_glyph_array *p_self);
+godot_glyph GDAPI *godot_packed_glyph_array_ptrw(godot_packed_glyph_array *p_self);
+
+void GDAPI godot_packed_glyph_array_append(godot_packed_glyph_array *p_self, const godot_glyph *p_data);
+
+void GDAPI godot_packed_glyph_array_append_array(godot_packed_glyph_array *p_self, const godot_packed_glyph_array *p_array);
+
+godot_error GDAPI godot_packed_glyph_array_insert(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data);
+
+godot_bool GDAPI godot_packed_glyph_array_has(godot_packed_glyph_array *p_self, const godot_glyph *p_value);
+
+void GDAPI godot_packed_glyph_array_sort(godot_packed_glyph_array *p_self);
+
+void GDAPI godot_packed_glyph_array_invert(godot_packed_glyph_array *p_self);
+
+void GDAPI godot_packed_glyph_array_push_back(godot_packed_glyph_array *p_self, const godot_glyph *p_data);
+
+void GDAPI godot_packed_glyph_array_remove(godot_packed_glyph_array *p_self, godot_int p_idx);
+
+void GDAPI godot_packed_glyph_array_resize(godot_packed_glyph_array *p_self, godot_int p_size);
+
+void GDAPI godot_packed_glyph_array_set(godot_packed_glyph_array *p_self, godot_int p_idx, const godot_glyph *p_data);
+godot_glyph GDAPI godot_packed_glyph_array_get(const godot_packed_glyph_array *p_self, godot_int p_idx);
+
+godot_int GDAPI godot_packed_glyph_array_size(const godot_packed_glyph_array *p_self);
+
+godot_bool GDAPI godot_packed_glyph_array_is_empty(const godot_packed_glyph_array *p_self);
+
+void GDAPI godot_packed_glyph_array_destroy(godot_packed_glyph_array *p_self);
+
+// Grapheme
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !GODOT_NATIVETEXT_H */
diff --git a/modules/gdnative/include/videodecoder/godot_videodecoder.h b/modules/gdnative/include/videodecoder/godot_videodecoder.h
index 3e91a2e9ac..e5a2657997 100644
--- a/modules/gdnative/include/videodecoder/godot_videodecoder.h
+++ b/modules/gdnative/include/videodecoder/godot_videodecoder.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,7 +46,7 @@ typedef struct
void *next;
void *(*constructor)(godot_object *);
void (*destructor)(void *);
- const char *(*get_plugin_name)(void);
+ const char *(*get_plugin_name)();
const char **(*get_supported_extensions)(int *count);
godot_bool (*open_file)(void *, void *); // data struct, and a FileAccess pointer
godot_real (*get_length)(const void *);
diff --git a/modules/gdnative/include/xr/godot_xr.h b/modules/gdnative/include/xr/godot_xr.h
index 22f7f021c4..235242bc84 100644
--- a/modules/gdnative/include/xr/godot_xr.h
+++ b/modules/gdnative/include/xr/godot_xr.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/nativescript/api_generator.cpp b/modules/gdnative/nativescript/api_generator.cpp
index 3c0cfd0484..6b46c9418a 100644
--- a/modules/gdnative/nativescript/api_generator.cpp
+++ b/modules/gdnative/nativescript/api_generator.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,16 +32,15 @@
#ifdef TOOLS_ENABLED
-#include "core/class_db.h"
-#include "core/engine.h"
-#include "core/global_constants.h"
+#include "core/config/engine.h"
+#include "core/core_constants.h"
+#include "core/object/class_db.h"
#include "core/os/file_access.h"
-#include "core/pair.h"
+#include "core/templates/pair.h"
// helper stuff
static Error save_file(const String &p_path, const List<String> &p_content) {
-
FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE);
ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE);
@@ -140,13 +139,12 @@ static String get_type_name(const PropertyInfo &info) {
}
/*
- * Some comparison helper functions we need
+ * Some comparison helper functions we need
*/
struct MethodInfoComparator {
StringName::AlphCompare compare;
bool operator()(const MethodInfo &p_a, const MethodInfo &p_b) const {
-
return compare(p_a.name, p_b.name);
}
};
@@ -154,7 +152,6 @@ struct MethodInfoComparator {
struct PropertyInfoComparator {
StringName::AlphCompare compare;
bool operator()(const PropertyInfo &p_a, const PropertyInfo &p_b) const {
-
return compare(p_a.name, p_b.name);
}
};
@@ -162,7 +159,6 @@ struct PropertyInfoComparator {
struct ConstantAPIComparator {
NoCaseComparator compare;
bool operator()(const ConstantAPI &p_a, const ConstantAPI &p_b) const {
-
return compare(p_a.constant_name, p_b.constant_name);
}
};
@@ -171,26 +167,25 @@ struct ConstantAPIComparator {
* Reads the entire Godot API to a list
*/
List<ClassAPI> generate_c_api_classes() {
-
List<ClassAPI> api;
List<StringName> classes;
ClassDB::get_class_list(&classes);
classes.sort_custom<StringName::AlphCompare>();
- // Register global constants as a fake GlobalConstants singleton class
+ // Register global constants as a fake CoreConstants singleton class
{
ClassAPI global_constants_api;
- global_constants_api.class_name = L"GlobalConstants";
+ global_constants_api.class_name = "CoreConstants";
global_constants_api.api_type = ClassDB::API_CORE;
global_constants_api.is_singleton = true;
- global_constants_api.singleton_name = L"GlobalConstants";
+ global_constants_api.singleton_name = "CoreConstants";
global_constants_api.is_instanciable = false;
- const int constants_count = GlobalConstants::get_global_constant_count();
+ const int constants_count = CoreConstants::get_global_constant_count();
for (int i = 0; i < constants_count; ++i) {
ConstantAPI constant_api;
- constant_api.constant_name = GlobalConstants::get_global_constant_name(i);
- constant_api.constant_value = GlobalConstants::get_global_constant_value(i);
+ constant_api.constant_name = CoreConstants::get_global_constant_name(i);
+ constant_api.constant_value = CoreConstants::get_global_constant_value(i);
global_constants_api.constants.push_back(constant_api);
}
global_constants_api.constants.sort_custom<ConstantAPIComparator>();
@@ -219,7 +214,7 @@ List<ClassAPI> generate_c_api_classes() {
{
List<StringName> inheriters;
ClassDB::get_inheriters_from_class("Reference", &inheriters);
- bool is_reference = !!inheriters.find(class_name);
+ bool is_reference = !!inheriters.find(class_name) || class_name == "Reference";
// @Unclear
class_api.is_reference = !class_api.is_singleton && is_reference;
}
@@ -300,7 +295,7 @@ List<ClassAPI> generate_c_api_classes() {
property_api.index = ClassDB::get_property_index(class_name, p->get().name);
- if (!property_api.setter.empty() || !property_api.getter.empty()) {
+ if (!property_api.setter.is_empty() || !property_api.getter.is_empty()) {
class_api.properties.push_back(property_api);
}
}
@@ -410,7 +405,6 @@ List<ClassAPI> generate_c_api_classes() {
* Generates the JSON source from the API in p_api
*/
static List<String> generate_c_api_json(const List<ClassAPI> &p_api) {
-
// I'm sorry for the \t mess
List<String> source;
@@ -458,6 +452,7 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) {
source.push_back("\t\t\t\t\t{\n");
source.push_back("\t\t\t\t\t\t\"name\": \"" + e->get().argument_names[i] + "\",\n");
source.push_back("\t\t\t\t\t\t\"type\": \"" + e->get().argument_types[i] + "\",\n");
+ source.push_back(String("\t\t\t\t\t\t\"has_default_value\": ") + (e->get().default_arguments.has(i) ? "true" : "false") + ",\n");
source.push_back("\t\t\t\t\t\t\"default_value\": \"" + (e->get().default_arguments.has(i) ? (String)e->get().default_arguments[i] : "") + "\"\n");
source.push_back(String("\t\t\t\t\t}") + ((i < e->get().argument_names.size() - 1) ? "," : "") + "\n");
}
@@ -520,7 +515,6 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) {
* p_path
*/
Error generate_c_api(const String &p_path) {
-
#ifndef TOOLS_ENABLED
return ERR_BUG;
#else
diff --git a/modules/gdnative/nativescript/api_generator.h b/modules/gdnative/nativescript/api_generator.h
index edbb1d1f23..a324ded4a9 100644
--- a/modules/gdnative/nativescript/api_generator.h
+++ b/modules/gdnative/nativescript/api_generator.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef API_GENERATOR_H
#define API_GENERATOR_H
+#include "core/string/ustring.h"
#include "core/typedefs.h"
-#include "core/ustring.h"
Error generate_c_api(const String &p_path);
diff --git a/modules/gdnative/nativescript/godot_nativescript.cpp b/modules/gdnative/nativescript/godot_nativescript.cpp
index 0502458b4f..b2abf8b8ae 100644
--- a/modules/gdnative/nativescript/godot_nativescript.cpp
+++ b/modules/gdnative/nativescript/godot_nativescript.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,11 +30,11 @@
#include "nativescript/godot_nativescript.h"
-#include "core/class_db.h"
-#include "core/error_macros.h"
-#include "core/global_constants.h"
-#include "core/project_settings.h"
-#include "core/variant.h"
+#include "core/config/project_settings.h"
+#include "core/core_constants.h"
+#include "core/error/error_macros.h"
+#include "core/object/class_db.h"
+#include "core/variant/variant.h"
#include "gdnative/gdnative.h"
#include <stdint.h>
@@ -51,8 +51,7 @@ extern "C" void _native_script_hook() {
// Script API
-void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_instance_create_func p_create_func, godot_instance_destroy_func p_destroy_func) {
-
+void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc> *classes = &NSL->library_classes[*s];
@@ -84,8 +83,7 @@ void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char
classes->insert(p_name, desc);
}
-void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_instance_create_func p_create_func, godot_instance_destroy_func p_destroy_func) {
-
+void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const char *p_name, const char *p_base, godot_nativescript_instance_create_func p_create_func, godot_nativescript_instance_destroy_func p_destroy_func) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc> *classes = &NSL->library_classes[*s];
@@ -118,8 +116,7 @@ void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const
classes->insert(p_name, desc);
}
-void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_method_attributes p_attr, godot_instance_method p_method) {
-
+void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const char *p_name, const char *p_function_name, godot_nativescript_method_attributes p_attr, godot_nativescript_instance_method p_method) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name);
@@ -138,8 +135,7 @@ void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const cha
E->get().methods.insert(p_function_name, method);
}
-void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_property_attributes *p_attr, godot_property_set_func p_set_func, godot_property_get_func p_get_func) {
-
+void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_nativescript_property_attributes *p_attr, godot_nativescript_property_set_func p_set_func, godot_nativescript_property_get_func p_get_func) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name);
@@ -163,8 +159,7 @@ void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const c
E->get().properties.insert(p_path, property);
}
-void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_signal *p_signal) {
-
+void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const char *p_name, const godot_nativescript_signal *p_signal) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name);
@@ -176,7 +171,7 @@ void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const cha
for (int i = 0; i < p_signal->num_args; i++) {
PropertyInfo info;
- godot_signal_argument arg = p_signal->args[i];
+ godot_nativescript_signal_argument arg = p_signal->args[i];
info.hint = (PropertyHint)arg.hint;
info.hint_string = *(String *)&arg.hint_string;
@@ -189,7 +184,7 @@ void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const cha
for (int i = 0; i < p_signal->num_default_args; i++) {
Variant *v;
- godot_signal_argument attrib = p_signal->args[i];
+ godot_nativescript_signal_argument attrib = p_signal->args[i];
v = (Variant *)&attrib.default_value;
@@ -209,8 +204,9 @@ void GDAPI godot_nativescript_register_signal(void *p_gdnative_handle, const cha
void GDAPI *godot_nativescript_get_userdata(godot_object *p_instance) {
Object *instance = (Object *)p_instance;
- if (!instance)
+ if (!instance) {
return nullptr;
+ }
if (instance->get_script_instance() && instance->get_script_instance()->get_language() == NativeScriptLanguage::get_singleton()) {
return ((NativeScriptInstance *)instance->get_script_instance())->userdata;
}
@@ -225,7 +221,7 @@ void GDAPI *godot_nativescript_get_userdata(godot_object *p_instance) {
*
*/
-void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_method_arg *p_args) {
+void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_handle, const char *p_name, const char *p_function_name, int p_num_args, const godot_nativescript_method_argument *p_args) {
String *s = (String *)p_gdnative_handle;
Map<StringName, NativeScriptDesc>::Element *E = NSL->library_classes[*s].find(p_name);
@@ -239,7 +235,7 @@ void GDAPI godot_nativescript_set_method_argument_information(void *p_gdnative_h
List<PropertyInfo> args;
for (int i = 0; i < p_num_args; i++) {
- godot_method_arg arg = p_args[i];
+ godot_nativescript_method_argument arg = p_args[i];
String name = *(String *)&arg.name;
String hint_string = *(String *)&arg.hint_string;
@@ -315,7 +311,6 @@ void GDAPI godot_nativescript_set_type_tag(void *p_gdnative_handle, const char *
}
const void GDAPI *godot_nativescript_get_type_tag(const godot_object *p_object) {
-
const Object *o = (Object *)p_object;
if (!o->get_script_instance()) {
@@ -326,14 +321,15 @@ const void GDAPI *godot_nativescript_get_type_tag(const godot_object *p_object)
return nullptr;
}
- if (script->get_script_desc())
+ if (script->get_script_desc()) {
return script->get_script_desc()->type_tag;
+ }
}
return nullptr;
}
-int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_instance_binding_functions p_binding_functions) {
+int GDAPI godot_nativescript_register_instance_binding_data_functions(godot_nativescript_instance_binding_functions p_binding_functions) {
return NativeScriptLanguage::get_singleton()->register_binding_functions(p_binding_functions);
}
diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp
index ed3ec44bf7..e08961564d 100644
--- a/modules/gdnative/nativescript/nativescript.cpp
+++ b/modules/gdnative/nativescript/nativescript.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,12 +34,12 @@
#include "gdnative/gdnative.h"
+#include "core/config/project_settings.h"
+#include "core/core_constants.h"
#include "core/core_string_names.h"
-#include "core/global_constants.h"
#include "core/io/file_access_encrypted.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "scene/main/scene_tree.h"
#include "scene/resources/resource_format_text.h"
@@ -169,7 +169,6 @@ String NativeScript::get_script_class_icon_path() const {
}
bool NativeScript::can_instance() const {
-
NativeScriptDesc *script_data = get_script_desc();
#ifdef TOOLS_ENABLED
@@ -185,8 +184,9 @@ bool NativeScript::can_instance() const {
Ref<Script> NativeScript::get_base_script() const {
NativeScriptDesc *script_data = get_script_desc();
- if (!script_data)
+ if (!script_data) {
return Ref<Script>();
+ }
NativeScript *script = (NativeScript *)NSL->create_script();
Ref<NativeScript> ns = Ref<NativeScript>(script);
@@ -200,14 +200,14 @@ Ref<Script> NativeScript::get_base_script() const {
StringName NativeScript::get_instance_base_type() const {
NativeScriptDesc *script_data = get_script_desc();
- if (!script_data)
+ if (!script_data) {
return "";
+ }
return script_data->base_native_type;
}
ScriptInstance *NativeScript::instance_create(Object *p_this) {
-
NativeScriptDesc *script_data = get_script_desc();
if (!script_data) {
@@ -274,8 +274,9 @@ bool NativeScript::has_method(const StringName &p_method) const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
- if (script_data->methods.has(p_method))
+ if (script_data->methods.has(p_method)) {
return true;
+ }
script_data = script_data->base_data;
}
@@ -285,14 +286,16 @@ bool NativeScript::has_method(const StringName &p_method) const {
MethodInfo NativeScript::get_method_info(const StringName &p_method) const {
NativeScriptDesc *script_data = get_script_desc();
- if (!script_data)
+ if (!script_data) {
return MethodInfo();
+ }
while (script_data) {
Map<StringName, NativeScriptDesc::Method>::Element *M = script_data->methods.find(p_method);
- if (M)
+ if (M) {
return M->get().info;
+ }
script_data = script_data->base_data;
}
@@ -306,8 +309,9 @@ bool NativeScript::is_valid() const {
bool NativeScript::is_tool() const {
NativeScriptDesc *script_data = get_script_desc();
- if (script_data)
+ if (script_data) {
return script_data->is_tool;
+ }
return false;
}
@@ -320,8 +324,9 @@ bool NativeScript::has_script_signal(const StringName &p_signal) const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
- if (script_data->signals_.has(p_signal))
+ if (script_data->signals_.has(p_signal)) {
return true;
+ }
script_data = script_data->base_data;
}
return false;
@@ -330,13 +335,13 @@ bool NativeScript::has_script_signal(const StringName &p_signal) const {
void NativeScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
NativeScriptDesc *script_data = get_script_desc();
- if (!script_data)
+ if (!script_data) {
return;
+ }
Set<MethodInfo> signals_;
while (script_data) {
-
for (Map<StringName, NativeScriptDesc::Signal>::Element *S = script_data->signals_.front(); S; S = S->next()) {
signals_.insert(S->get().signal);
}
@@ -357,8 +362,9 @@ bool NativeScript::get_property_default_value(const StringName &p_property, Vari
P = script_data->properties.find(p_property);
script_data = script_data->base_data;
}
- if (!P)
+ if (!P) {
return false;
+ }
r_value = P.get().default_value;
return true;
@@ -370,13 +376,13 @@ void NativeScript::update_exports() {
void NativeScript::get_script_method_list(List<MethodInfo> *p_list) const {
NativeScriptDesc *script_data = get_script_desc();
- if (!script_data)
+ if (!script_data) {
return;
+ }
Set<MethodInfo> methods;
while (script_data) {
-
for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) {
methods.insert(E->get().info);
}
@@ -408,13 +414,11 @@ void NativeScript::get_script_property_list(List<PropertyInfo> *p_list) const {
}
Vector<ScriptNetData> NativeScript::get_rpc_methods() const {
-
Vector<ScriptNetData> v;
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) {
if (E->get().rpc_mode != GODOT_METHOD_RPC_MODE_DISABLED) {
ScriptNetData nd;
@@ -434,7 +438,6 @@ uint16_t NativeScript::get_rpc_method_id(const StringName &p_method) const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method);
if (E) {
return E->get().rpc_method_id;
@@ -452,7 +455,6 @@ StringName NativeScript::get_rpc_method(uint16_t p_id) const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) {
if (E->get().rpc_method_id == p_id) {
return E->key();
@@ -466,13 +468,11 @@ StringName NativeScript::get_rpc_method(uint16_t p_id) const {
}
MultiplayerAPI::RPCMode NativeScript::get_rpc_mode_by_id(uint16_t p_id) const {
-
ERR_FAIL_COND_V(p_id == UINT16_MAX, MultiplayerAPI::RPC_MODE_DISABLED);
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) {
if (E->get().rpc_method_id == p_id) {
switch (E->get().rpc_mode) {
@@ -503,11 +503,9 @@ MultiplayerAPI::RPCMode NativeScript::get_rpc_mode_by_id(uint16_t p_id) const {
}
MultiplayerAPI::RPCMode NativeScript::get_rpc_mode(const StringName &p_method) const {
-
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method);
if (E) {
switch (E->get().rpc_mode) {
@@ -542,7 +540,6 @@ Vector<ScriptNetData> NativeScript::get_rset_properties() const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) {
if (E.get().rset_mode != GODOT_METHOD_RPC_MODE_DISABLED) {
ScriptNetData nd;
@@ -561,7 +558,6 @@ uint16_t NativeScript::get_rset_property_id(const StringName &p_variable) const
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.find(p_variable);
if (E) {
return E.get().rset_property_id;
@@ -579,7 +575,6 @@ StringName NativeScript::get_rset_property(uint16_t p_id) const {
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) {
if (E.get().rset_property_id == p_id) {
return E.key();
@@ -593,13 +588,11 @@ StringName NativeScript::get_rset_property(uint16_t p_id) const {
}
MultiplayerAPI::RPCMode NativeScript::get_rset_mode_by_id(uint16_t p_id) const {
-
ERR_FAIL_COND_V(p_id == UINT16_MAX, MultiplayerAPI::RPC_MODE_DISABLED);
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) {
if (E.get().rset_property_id == p_id) {
switch (E.get().rset_mode) {
@@ -630,11 +623,9 @@ MultiplayerAPI::RPCMode NativeScript::get_rset_mode_by_id(uint16_t p_id) const {
}
MultiplayerAPI::RPCMode NativeScript::get_rset_mode(const StringName &p_variable) const {
-
NativeScriptDesc *script_data = get_script_desc();
while (script_data) {
-
OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.find(p_variable);
if (E) {
switch (E.get().rset_mode) {
@@ -677,7 +668,6 @@ String NativeScript::get_method_documentation(const StringName &p_method) const
ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get method documentation on invalid NativeScript.");
while (script_data) {
-
Map<StringName, NativeScriptDesc::Method>::Element *method = script_data->methods.find(p_method);
if (method) {
@@ -696,7 +686,6 @@ String NativeScript::get_signal_documentation(const StringName &p_signal_name) c
ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get signal documentation on invalid NativeScript.");
while (script_data) {
-
Map<StringName, NativeScriptDesc::Signal>::Element *signal = script_data->signals_.find(p_signal_name);
if (signal) {
@@ -715,7 +704,6 @@ String NativeScript::get_property_documentation(const StringName &p_path) const
ERR_FAIL_COND_V_MSG(!script_data, "", "Attempt to get property documentation on invalid NativeScript.");
while (script_data) {
-
OrderedHashMap<StringName, NativeScriptDesc::Property>::Element property = script_data->properties.find(p_path);
if (property) {
@@ -729,8 +717,7 @@ String NativeScript::get_property_documentation(const StringName &p_path) const
}
Variant NativeScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
- if (lib_path.empty() || class_name.empty() || library.is_null()) {
+ if (lib_path.is_empty() || class_name.is_empty() || library.is_null()) {
r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
return Variant();
}
@@ -840,6 +827,7 @@ bool NativeScriptInstance::set(const StringName &p_name, const Variant &p_value)
}
return false;
}
+
bool NativeScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
NativeScriptDesc *script_data = GET_SCRIPT_DESC();
@@ -884,10 +872,8 @@ void NativeScriptInstance::get_property_list(List<PropertyInfo> *p_properties) c
NativeScriptDesc *script_data = GET_SCRIPT_DESC();
while (script_data) {
-
Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find("_get_property_list");
if (E) {
-
godot_variant result;
result = E->get().method.method((godot_object *)owner,
E->get().method.method_data,
@@ -936,11 +922,9 @@ void NativeScriptInstance::get_property_list(List<PropertyInfo> *p_properties) c
}
Variant::Type NativeScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
-
NativeScriptDesc *script_data = GET_SCRIPT_DESC();
while (script_data) {
-
OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = script_data->properties.find(p_name);
if (P) {
*r_is_valid = true;
@@ -961,7 +945,6 @@ bool NativeScriptInstance::has_method(const StringName &p_method) const {
}
Variant NativeScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
NativeScriptDesc *script_data = GET_SCRIPT_DESC();
while (script_data) {
@@ -1008,7 +991,8 @@ void NativeScriptInstance::notification(int p_notification) {
Variant value = p_notification;
const Variant *args[1] = { &value };
- call_multilevel("_notification", args, 1);
+ Callable::CallError error;
+ call("_notification", args, 1, error);
}
String NativeScriptInstance::to_string(bool *r_valid) {
@@ -1017,17 +1001,20 @@ String NativeScriptInstance::to_string(bool *r_valid) {
Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce);
if (ce.error == Callable::CallError::CALL_OK) {
if (ret.get_type() != Variant::STRING) {
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String.");
}
- if (r_valid)
+ if (r_valid) {
*r_valid = true;
+ }
return ret.operator String();
}
}
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
@@ -1101,37 +1088,12 @@ ScriptLanguage *NativeScriptInstance::get_language() {
return NativeScriptLanguage::get_singleton();
}
-void NativeScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
- NativeScriptDesc *script_data = GET_SCRIPT_DESC();
-
- while (script_data) {
- Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method);
- if (E) {
- godot_variant res = E->get().method.method((godot_object *)owner,
- E->get().method.method_data,
- userdata,
- p_argcount,
- (godot_variant **)p_args);
- godot_variant_destroy(&res);
- }
- script_data = script_data->base_data;
- }
-}
-
-void NativeScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
- NativeScriptDesc *script_data = GET_SCRIPT_DESC();
-
- if (script_data) {
- _ml_call_reversed(script_data, p_method, p_args, p_argcount);
- }
-}
-
NativeScriptInstance::~NativeScriptInstance() {
-
NativeScriptDesc *script_data = GET_SCRIPT_DESC();
- if (!script_data)
+ if (!script_data) {
return;
+ }
script_data->destroy_func.destroy_func((godot_object *)owner, script_data->destroy_func.method_data, userdata);
@@ -1145,16 +1107,13 @@ NativeScriptInstance::~NativeScriptInstance() {
NativeScriptLanguage *NativeScriptLanguage::singleton;
void NativeScriptLanguage::_unload_stuff(bool p_reload) {
-
Map<String, Ref<GDNative>> erase_and_unload;
for (Map<String, Map<StringName, NativeScriptDesc>>::Element *L = library_classes.front(); L; L = L->next()) {
-
String lib_path = L->key();
Map<StringName, NativeScriptDesc> classes = L->get();
if (p_reload) {
-
Map<String, Ref<GDNative>>::Element *E = library_gdnatives.find(lib_path);
Ref<GDNative> gdn;
@@ -1184,28 +1143,32 @@ void NativeScriptLanguage::_unload_stuff(bool p_reload) {
}
for (Map<StringName, NativeScriptDesc>::Element *C = classes.front(); C; C = C->next()) {
-
// free property stuff first
for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element P = C->get().properties.front(); P; P = P.next()) {
- if (P.get().getter.free_func)
+ if (P.get().getter.free_func) {
P.get().getter.free_func(P.get().getter.method_data);
+ }
- if (P.get().setter.free_func)
+ if (P.get().setter.free_func) {
P.get().setter.free_func(P.get().setter.method_data);
+ }
}
// free method stuff
for (Map<StringName, NativeScriptDesc::Method>::Element *M = C->get().methods.front(); M; M = M->next()) {
- if (M->get().method.free_func)
+ if (M->get().method.free_func) {
M->get().method.free_func(M->get().method.method_data);
+ }
}
// free constructor/destructor
- if (C->get().create_func.free_func)
+ if (C->get().create_func.free_func) {
C->get().create_func.free_func(C->get().create_func.method_data);
+ }
- if (C->get().destroy_func.free_func)
+ if (C->get().destroy_func.free_func) {
C->get().destroy_func.free_func(C->get().destroy_func.method_data);
+ }
}
erase_and_unload.insert(lib_path, gdn);
@@ -1253,13 +1216,10 @@ NativeScriptLanguage::NativeScriptLanguage() {
}
NativeScriptLanguage::~NativeScriptLanguage() {
-
for (Map<String, Ref<GDNative>>::Element *L = NSL->library_gdnatives.front(); L; L = L->next()) {
-
Ref<GDNative> lib = L->get();
// only shut down valid libs, duh!
if (lib.is_valid()) {
-
// If it's a singleton-library then the gdnative module
// manages the destruction at engine shutdown, not NativeScript.
if (!lib->get_library()->is_singleton()) {
@@ -1285,7 +1245,6 @@ void _add_reload_node() {
}
void NativeScriptLanguage::init() {
-
#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
List<String> args = OS::get_singleton()->get_cmdline_args();
@@ -1304,22 +1263,29 @@ void NativeScriptLanguage::init() {
EditorNode::add_init_callback(&_add_reload_node);
#endif
}
+
String NativeScriptLanguage::get_type() const {
return "NativeScript";
}
+
String NativeScriptLanguage::get_extension() const {
return "gdns";
}
+
Error NativeScriptLanguage::execute_file(const String &p_path) {
return OK; // Qué?
}
+
void NativeScriptLanguage::finish() {
_unload_stuff();
}
+
void NativeScriptLanguage::get_reserved_words(List<String> *p_words) const {
}
+
void NativeScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
}
+
void NativeScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
}
@@ -1328,6 +1294,7 @@ Ref<Script> NativeScriptLanguage::get_template(const String &p_class_name, const
s->set_class_name(p_class_name);
return Ref<NativeScript>(s);
}
+
bool NativeScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
return true;
}
@@ -1336,20 +1303,26 @@ Script *NativeScriptLanguage::create_script() const {
NativeScript *script = memnew(NativeScript);
return script;
}
+
bool NativeScriptLanguage::has_named_classes() const {
return true;
}
+
bool NativeScriptLanguage::supports_builtin_mode() const {
return true;
}
+
int NativeScriptLanguage::find_function(const String &p_function, const String &p_code) const {
return -1;
}
+
String NativeScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
return "";
}
+
void NativeScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
}
+
void NativeScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
}
@@ -1357,27 +1330,36 @@ void NativeScriptLanguage::add_global_constant(const StringName &p_variable, con
String NativeScriptLanguage::debug_get_error() const {
return "";
}
+
int NativeScriptLanguage::debug_get_stack_level_count() const {
return -1;
}
+
int NativeScriptLanguage::debug_get_stack_level_line(int p_level) const {
return -1;
}
+
String NativeScriptLanguage::debug_get_stack_level_function(int p_level) const {
return "";
}
+
String NativeScriptLanguage::debug_get_stack_level_source(int p_level) const {
return "";
}
+
void NativeScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
}
+
void NativeScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
}
+
void NativeScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
}
+
String NativeScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
return "";
}
+
// Debugging stuff end.
void NativeScriptLanguage::reload_all_scripts() {
@@ -1385,6 +1367,7 @@ void NativeScriptLanguage::reload_all_scripts() {
void NativeScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
}
+
void NativeScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("gdns");
}
@@ -1419,8 +1402,9 @@ int NativeScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_a
int current = 0;
for (Map<StringName, ProfileData>::Element *d = profile_data.front(); d; d = d->next()) {
- if (current >= p_info_max)
+ if (current >= p_info_max) {
break;
+ }
p_info_arr[current].call_count = d->get().call_count;
p_info_arr[current].self_time = d->get().self_time;
@@ -1442,8 +1426,9 @@ int NativeScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, in
int current = 0;
for (Map<StringName, ProfileData>::Element *d = profile_data.front(); d; d = d->next()) {
- if (current >= p_info_max)
+ if (current >= p_info_max) {
break;
+ }
if (d->get().last_frame_call_count) {
p_info_arr[current].call_count = d->get().last_frame_call_count;
@@ -1489,8 +1474,7 @@ void NativeScriptLanguage::profiling_add_data(StringName p_signature, uint64_t p
#endif
}
-int NativeScriptLanguage::register_binding_functions(godot_instance_binding_functions p_binding_functions) {
-
+int NativeScriptLanguage::register_binding_functions(godot_nativescript_instance_binding_functions p_binding_functions) {
// find index
int idx = -1;
@@ -1521,14 +1505,16 @@ void NativeScriptLanguage::unregister_binding_functions(int p_idx) {
for (Set<Vector<void *> *>::Element *E = binding_instances.front(); E; E = E->next()) {
Vector<void *> &binding_data = *E->get();
- if (p_idx < binding_data.size() && binding_data[p_idx] && binding_functions[p_idx].second.free_instance_binding_data)
+ if (p_idx < binding_data.size() && binding_data[p_idx] && binding_functions[p_idx].second.free_instance_binding_data) {
binding_functions[p_idx].second.free_instance_binding_data(binding_functions[p_idx].second.data, binding_data[p_idx]);
+ }
}
binding_functions.write[p_idx].first = false;
- if (binding_functions[p_idx].second.free_func)
+ if (binding_functions[p_idx].second.free_func) {
binding_functions[p_idx].second.free_func(binding_functions[p_idx].second.data);
+ }
}
void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_object) {
@@ -1538,8 +1524,9 @@ void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_objec
Vector<void *> *binding_data = (Vector<void *> *)p_object->get_script_instance_binding(lang_idx);
- if (!binding_data)
+ if (!binding_data) {
return nullptr; // should never happen.
+ }
if (binding_data->size() <= p_idx) {
// okay, add new elements here.
@@ -1553,7 +1540,6 @@ void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_objec
}
if (!(*binding_data)[p_idx]) {
-
const void *global_type_tag = get_global_type_tag(p_idx, p_object->get_class_name());
// no binding data yet, soooooo alloc new one \o/
@@ -1564,7 +1550,6 @@ void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_objec
}
void *NativeScriptLanguage::alloc_instance_binding_data(Object *p_object) {
-
Vector<void *> *binding_data = new Vector<void *>;
binding_data->resize(binding_functions.size());
@@ -1579,15 +1564,16 @@ void *NativeScriptLanguage::alloc_instance_binding_data(Object *p_object) {
}
void NativeScriptLanguage::free_instance_binding_data(void *p_data) {
-
- if (!p_data)
+ if (!p_data) {
return;
+ }
Vector<void *> &binding_data = *(Vector<void *> *)p_data;
for (int i = 0; i < binding_data.size(); i++) {
- if (!binding_data[i])
+ if (!binding_data[i]) {
continue;
+ }
if (binding_functions[i].first && binding_functions[i].second.free_instance_binding_data) {
binding_functions[i].second.free_instance_binding_data(binding_functions[i].second.data, binding_data[i]);
@@ -1600,20 +1586,22 @@ void NativeScriptLanguage::free_instance_binding_data(void *p_data) {
}
void NativeScriptLanguage::refcount_incremented_instance_binding(Object *p_object) {
-
void *data = p_object->get_script_instance_binding(lang_idx);
- if (!data)
+ if (!data) {
return;
+ }
Vector<void *> &binding_data = *(Vector<void *> *)data;
for (int i = 0; i < binding_data.size(); i++) {
- if (!binding_data[i])
+ if (!binding_data[i]) {
continue;
+ }
- if (!binding_functions[i].first)
+ if (!binding_functions[i].first) {
continue;
+ }
if (binding_functions[i].second.refcount_incremented_instance_binding) {
binding_functions[i].second.refcount_incremented_instance_binding(binding_data[i], p_object);
@@ -1622,22 +1610,24 @@ void NativeScriptLanguage::refcount_incremented_instance_binding(Object *p_objec
}
bool NativeScriptLanguage::refcount_decremented_instance_binding(Object *p_object) {
-
void *data = p_object->get_script_instance_binding(lang_idx);
- if (!data)
+ if (!data) {
return true;
+ }
Vector<void *> &binding_data = *(Vector<void *> *)data;
bool can_die = true;
for (int i = 0; i < binding_data.size(); i++) {
- if (!binding_data[i])
+ if (!binding_data[i]) {
continue;
+ }
- if (!binding_functions[i].first)
+ if (!binding_functions[i].first) {
continue;
+ }
if (binding_functions[i].second.refcount_decremented_instance_binding) {
can_die = can_die && binding_functions[i].second.refcount_decremented_instance_binding(binding_data[i], p_object);
@@ -1658,13 +1648,15 @@ void NativeScriptLanguage::set_global_type_tag(int p_idx, StringName p_class_nam
}
const void *NativeScriptLanguage::get_global_type_tag(int p_idx, StringName p_class_name) const {
- if (!global_type_tags.has(p_idx))
+ if (!global_type_tags.has(p_idx)) {
return nullptr;
+ }
const HashMap<StringName, const void *> &tags = global_type_tags[p_idx];
- if (!tags.has(p_class_name))
+ if (!tags.has(p_class_name)) {
return nullptr;
+ }
const void *tag = tags.get(p_class_name);
@@ -1700,8 +1692,9 @@ void NativeScriptLanguage::init_library(const Ref<GDNativeLibrary> &lib) {
library_classes.insert(lib_path, Map<StringName, NativeScriptDesc>());
- if (!library_script_users.has(lib_path))
+ if (!library_script_users.has(lib_path)) {
library_script_users.insert(lib_path, Set<NativeScript *>());
+ }
void *proc_ptr;
@@ -1741,13 +1734,11 @@ void NativeScriptLanguage::unregister_script(NativeScript *script) {
void NativeScriptLanguage::call_libraries_cb(const StringName &name) {
// library_gdnatives is modified only from the main thread, so it's safe not to use mutex here
for (Map<String, Ref<GDNative>>::Element *L = library_gdnatives.front(); L; L = L->next()) {
-
if (L->get().is_null()) {
continue;
}
if (L->get()->is_initialized()) {
-
void *proc_ptr;
Error err = L->get()->get_symbol(L->get()->get_library()->get_symbol_prefix() + name, proc_ptr);
@@ -1809,19 +1800,23 @@ bool NativeScriptLanguage::handles_global_class_type(const String &p_type) const
}
String NativeScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
- if (!p_path.empty()) {
+ if (!p_path.is_empty()) {
Ref<NativeScript> script = ResourceLoader::load(p_path, "NativeScript");
if (script.is_valid()) {
- if (r_base_type)
+ if (r_base_type) {
*r_base_type = script->get_instance_base_type();
- if (r_icon_path)
+ }
+ if (r_icon_path) {
*r_icon_path = script->get_script_class_icon_path();
+ }
return script->get_script_class_name();
}
- if (r_base_type)
+ if (r_base_type) {
*r_base_type = String();
- if (r_icon_path)
+ }
+ if (r_icon_path) {
*r_icon_path = String();
+ }
}
return String();
}
@@ -1834,15 +1829,14 @@ void NativeReloadNode::_notification(int p_what) {
#ifdef TOOLS_ENABLED
switch (p_what) {
- case NOTIFICATION_WM_FOCUS_OUT: {
-
- if (unloaded)
+ case NOTIFICATION_APPLICATION_FOCUS_OUT: {
+ if (unloaded) {
break;
+ }
MutexLock lock(NSL->mutex);
NSL->_unload_stuff(true);
for (Map<String, Ref<GDNative>>::Element *L = NSL->library_gdnatives.front(); L; L = L->next()) {
-
Ref<GDNative> gdn = L->get();
if (gdn.is_null()) {
@@ -1869,15 +1863,14 @@ void NativeReloadNode::_notification(int p_what) {
} break;
- case NOTIFICATION_WM_FOCUS_IN: {
-
- if (!unloaded)
+ case NOTIFICATION_APPLICATION_FOCUS_IN: {
+ if (!unloaded) {
break;
+ }
MutexLock lock(NSL->mutex);
Set<StringName> libs_to_remove;
for (Map<String, Ref<GDNative>>::Element *L = NSL->library_gdnatives.front(); L; L = L->next()) {
-
Ref<GDNative> gdn = L->get();
if (gdn.is_null()) {
@@ -1915,8 +1908,9 @@ void NativeReloadNode::_notification(int p_what) {
for (Set<NativeScript *>::Element *S = U->get().front(); S; S = S->next()) {
NativeScript *script = S->get();
- if (script->placeholders.size() == 0)
+ if (script->placeholders.size() == 0) {
continue;
+ }
for (Set<PlaceHolderScriptInstance *>::Element *P = script->placeholders.front(); P; P = P->next()) {
script->_update_placeholder(P->get());
@@ -1952,8 +1946,9 @@ bool ResourceFormatLoaderNativeScript::handles_type(const String &p_type) const
String ResourceFormatLoaderNativeScript::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
- if (el == "gdns")
+ if (el == "gdns") {
return "NativeScript";
+ }
return "";
}
diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h
index 7e7598e06c..9d72bf39d1 100644
--- a/modules/gdnative/nativescript/nativescript.h
+++ b/modules/gdnative/nativescript/nativescript.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,32 +31,34 @@
#ifndef NATIVE_SCRIPT_H
#define NATIVE_SCRIPT_H
+#include "core/doc_data.h"
+#include "core/io/resource.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
-#include "core/oa_hash_map.h"
-#include "core/ordered_hash_map.h"
+#include "core/object/script_language.h"
#include "core/os/mutex.h"
#include "core/os/thread_safe.h"
-#include "core/resource.h"
-#include "core/script_language.h"
-#include "core/self_list.h"
+#include "core/templates/oa_hash_map.h"
+#include "core/templates/ordered_hash_map.h"
+#include "core/templates/self_list.h"
#include "scene/main/node.h"
#include "modules/gdnative/gdnative.h"
+
#include <nativescript/godot_nativescript.h>
struct NativeScriptDesc {
-
struct Method {
- godot_instance_method method;
+ godot_nativescript_instance_method method;
MethodInfo info;
int rpc_mode;
uint16_t rpc_method_id;
String documentation;
};
+
struct Property {
- godot_property_set_func setter;
- godot_property_get_func getter;
+ godot_nativescript_property_set_func setter;
+ godot_nativescript_property_get_func getter;
PropertyInfo info;
Variant default_value;
int rset_mode;
@@ -69,35 +71,26 @@ struct NativeScriptDesc {
String documentation;
};
- uint16_t rpc_count;
+ uint16_t rpc_count = 0;
Map<StringName, Method> methods;
- uint16_t rset_count;
+ uint16_t rset_count = 0;
OrderedHashMap<StringName, Property> properties;
Map<StringName, Signal> signals_; // QtCreator doesn't like the name signals
StringName base;
StringName base_native_type;
NativeScriptDesc *base_data;
- godot_instance_create_func create_func;
- godot_instance_destroy_func destroy_func;
+ godot_nativescript_instance_create_func create_func;
+ godot_nativescript_instance_destroy_func destroy_func;
String documentation;
- const void *type_tag;
+ const void *type_tag = nullptr;
bool is_tool;
- inline NativeScriptDesc() :
- rpc_count(0),
- methods(),
- rset_count(0),
- properties(),
- signals_(),
- base(),
- base_native_type(),
- documentation(),
- type_tag(nullptr) {
- zeromem(&create_func, sizeof(godot_instance_create_func));
- zeromem(&destroy_func, sizeof(godot_instance_destroy_func));
+ inline NativeScriptDesc() {
+ zeromem(&create_func, sizeof(godot_nativescript_instance_create_func));
+ zeromem(&destroy_func, sizeof(godot_nativescript_instance_destroy_func));
}
};
@@ -107,7 +100,7 @@ class NativeScript : public Script {
#ifdef TOOLS_ENABLED
Set<PlaceHolderScriptInstance *> placeholders;
void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
+ virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
#endif
friend class NativeScriptInstance;
@@ -133,7 +126,7 @@ protected:
public:
inline NativeScriptDesc *get_script_desc() const;
- bool inherits_script(const Ref<Script> &p_script) const;
+ bool inherits_script(const Ref<Script> &p_script) const override;
void set_class_name(String p_class_name);
String get_class_name() const;
@@ -146,48 +139,55 @@ public:
void set_script_class_icon_path(String p_icon_path);
String get_script_class_icon_path() const;
- virtual bool can_instance() const;
+ virtual bool can_instance() const override;
- virtual Ref<Script> get_base_script() const; //for script inheritance
+ virtual Ref<Script> get_base_script() const override; //for script inheritance
- virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so
- virtual ScriptInstance *instance_create(Object *p_this);
- virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this);
- virtual bool instance_has(const Object *p_this) const;
+ virtual StringName get_instance_base_type() const override; // this may not work in all scripts, will return empty if so
+ virtual ScriptInstance *instance_create(Object *p_this) override;
+ virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override;
+ virtual bool instance_has(const Object *p_this) const override;
- virtual bool has_source_code() const;
- virtual String get_source_code() const;
- virtual void set_source_code(const String &p_code);
- virtual Error reload(bool p_keep_state = false);
+ virtual bool has_source_code() const override;
+ virtual String get_source_code() const override;
+ virtual void set_source_code(const String &p_code) override;
+ virtual Error reload(bool p_keep_state = false) override;
- virtual bool has_method(const StringName &p_method) const;
- virtual MethodInfo get_method_info(const StringName &p_method) const;
+#ifdef TOOLS_ENABLED
+ virtual const Vector<DocData::ClassDoc> &get_documentation() const override {
+ static Vector<DocData::ClassDoc> docs;
+ return docs;
+ }
+#endif // TOOLS_ENABLED
- virtual bool is_tool() const;
- virtual bool is_valid() const;
+ virtual bool has_method(const StringName &p_method) const override;
+ virtual MethodInfo get_method_info(const StringName &p_method) const override;
- virtual ScriptLanguage *get_language() const;
+ virtual bool is_tool() const override;
+ virtual bool is_valid() const override;
- virtual bool has_script_signal(const StringName &p_signal) const;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
+ virtual ScriptLanguage *get_language() const override;
- virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const;
+ virtual bool has_script_signal(const StringName &p_signal) const override;
+ virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override;
- virtual void update_exports(); //editor tool
- virtual void get_script_method_list(List<MethodInfo> *p_list) const;
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
+ virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(uint16_t p_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(uint16_t p_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual void update_exports() override; //editor tool
+ virtual void get_script_method_list(List<MethodInfo> *p_list) const override;
+ virtual void get_script_property_list(List<PropertyInfo> *p_list) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_variable) const;
- virtual StringName get_rset_property(uint16_t p_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(uint16_t p_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ virtual Vector<ScriptNetData> get_rpc_methods() const override;
+ virtual uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ virtual StringName get_rpc_method(uint16_t p_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(uint16_t p_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
+
+ virtual Vector<ScriptNetData> get_rset_properties() const override;
+ virtual uint16_t get_rset_property_id(const StringName &p_variable) const override;
+ virtual StringName get_rset_property(uint16_t p_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(uint16_t p_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
String get_class_documentation() const;
String get_method_documentation(const StringName &p_method) const;
@@ -201,7 +201,6 @@ public:
};
class NativeScriptInstance : public ScriptInstance {
-
friend class NativeScript;
Object *owner;
@@ -240,9 +239,6 @@ public:
virtual ScriptLanguage *get_language();
- virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount);
- virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount);
-
virtual void refcount_incremented();
virtual bool refcount_decremented();
@@ -252,7 +248,6 @@ public:
class NativeReloadNode;
class NativeScriptLanguage : public ScriptLanguage {
-
friend class NativeScript;
friend class NativeScriptInstance;
friend class NativeReloadNode;
@@ -277,7 +272,7 @@ private:
void call_libraries_cb(const StringName &name);
- Vector<Pair<bool, godot_instance_binding_functions>> binding_functions;
+ Vector<Pair<bool, godot_nativescript_instance_binding_functions>> binding_functions;
Set<Vector<void *> *> binding_instances;
Map<int, HashMap<StringName, const void *>> global_type_tags;
@@ -370,7 +365,7 @@ public:
virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max);
virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max);
- int register_binding_functions(godot_instance_binding_functions p_binding_functions);
+ int register_binding_functions(godot_nativescript_instance_binding_functions p_binding_functions);
void unregister_binding_functions(int p_idx);
void *get_instance_binding_data(int p_idx, Object *p_object);
@@ -396,14 +391,13 @@ inline NativeScriptDesc *NativeScript::get_script_desc() const {
class NativeReloadNode : public Node {
GDCLASS(NativeReloadNode, Node);
- bool unloaded;
+ bool unloaded = false;
public:
static void _bind_methods();
void _notification(int p_what);
- NativeReloadNode() :
- unloaded(false) {}
+ NativeReloadNode() {}
};
class ResourceFormatLoaderNativeScript : public ResourceFormatLoader {
diff --git a/modules/gdnative/nativescript/register_types.cpp b/modules/gdnative/nativescript/register_types.cpp
index b5e8174e43..0353ab2092 100644
--- a/modules/gdnative/nativescript/register_types.cpp
+++ b/modules/gdnative/nativescript/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -58,7 +58,6 @@ void register_nativescript_types() {
}
void unregister_nativescript_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_gdns);
resource_loader_gdns.unref();
diff --git a/modules/gdnative/nativescript/register_types.h b/modules/gdnative/nativescript/register_types.h
index 088bf38dd5..d12ac9eda3 100644
--- a/modules/gdnative/nativescript/register_types.h
+++ b/modules/gdnative/nativescript/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.cpp b/modules/gdnative/net/multiplayer_peer_gdnative.cpp
index a95697ea65..8b5fc8db5c 100644
--- a/modules/gdnative/net/multiplayer_peer_gdnative.cpp
+++ b/modules/gdnative/net/multiplayer_peer_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -120,7 +120,6 @@ void MultiplayerPeerGDNative::_bind_methods() {
extern "C" {
void GDAPI godot_net_bind_multiplayer_peer(godot_object *p_obj, const godot_net_multiplayer_peer *p_impl) {
-
((MultiplayerPeerGDNative *)p_obj)->set_native_multiplayer_peer(p_impl);
}
}
diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.h b/modules/gdnative/net/multiplayer_peer_gdnative.h
index cfaf14936e..593b2534dd 100644
--- a/modules/gdnative/net/multiplayer_peer_gdnative.h
+++ b/modules/gdnative/net/multiplayer_peer_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -50,28 +50,28 @@ public:
void set_native_multiplayer_peer(const godot_net_multiplayer_peer *p_impl);
/* Specific to PacketPeer */
- 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;
- virtual int get_available_packet_count() const;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
+ virtual int get_max_packet_size() const override;
+ virtual int get_available_packet_count() const override;
/* Specific to NetworkedMultiplayerPeer */
- virtual void set_transfer_mode(TransferMode p_mode);
- virtual TransferMode get_transfer_mode() const;
- virtual void set_target_peer(int p_peer_id);
+ virtual void set_transfer_mode(TransferMode p_mode) override;
+ virtual TransferMode get_transfer_mode() const override;
+ virtual void set_target_peer(int p_peer_id) override;
- virtual int get_packet_peer() const;
+ virtual int get_packet_peer() const override;
- virtual bool is_server() const;
+ virtual bool is_server() const override;
- virtual void poll();
+ virtual void poll() override;
- virtual int get_unique_id() const;
+ virtual int get_unique_id() const override;
- virtual void set_refuse_new_connections(bool p_enable);
- virtual bool is_refusing_new_connections() const;
+ virtual void set_refuse_new_connections(bool p_enable) override;
+ virtual bool is_refusing_new_connections() const override;
- virtual ConnectionStatus get_connection_status() const;
+ virtual ConnectionStatus get_connection_status() const override;
};
#endif // MULTIPLAYER_PEER_GDNATIVE_H
diff --git a/modules/gdnative/net/packet_peer_gdnative.cpp b/modules/gdnative/net/packet_peer_gdnative.cpp
index 28135df3b6..3bcdfed8ff 100644
--- a/modules/gdnative/net/packet_peer_gdnative.cpp
+++ b/modules/gdnative/net/packet_peer_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -67,7 +67,6 @@ int PacketPeerGDNative::get_available_packet_count() const {
extern "C" {
void GDAPI godot_net_bind_packet_peer(godot_object *p_obj, const godot_net_packet_peer *p_impl) {
-
((PacketPeerGDNative *)p_obj)->set_native_packet_peer(p_impl);
}
}
diff --git a/modules/gdnative/net/packet_peer_gdnative.h b/modules/gdnative/net/packet_peer_gdnative.h
index 78d8bb32b6..29013f9367 100644
--- a/modules/gdnative/net/packet_peer_gdnative.h
+++ b/modules/gdnative/net/packet_peer_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -50,10 +50,10 @@ public:
void set_native_packet_peer(const godot_net_packet_peer *p_impl);
/* Specific to PacketPeer */
- 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;
- virtual int get_available_packet_count() const;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
+ virtual int get_max_packet_size() const override;
+ virtual int get_available_packet_count() const override;
};
#endif // PACKET_PEER_GDNATIVE_H
diff --git a/modules/gdnative/net/register_types.cpp b/modules/gdnative/net/register_types.cpp
index 4e48a43210..645c43b7e3 100644
--- a/modules/gdnative/net/register_types.cpp
+++ b/modules/gdnative/net/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/net/register_types.h b/modules/gdnative/net/register_types.h
index 70b266f9b9..c99c6f6fbf 100644
--- a/modules/gdnative/net/register_types.h
+++ b/modules/gdnative/net/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/net/stream_peer_gdnative.cpp b/modules/gdnative/net/stream_peer_gdnative.cpp
index 9dcb184115..72ab72323d 100644
--- a/modules/gdnative/net/stream_peer_gdnative.cpp
+++ b/modules/gdnative/net/stream_peer_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/net/stream_peer_gdnative.h b/modules/gdnative/net/stream_peer_gdnative.h
index f3711e0f0f..dd5abceb83 100644
--- a/modules/gdnative/net/stream_peer_gdnative.h
+++ b/modules/gdnative/net/stream_peer_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,6 @@
#include "modules/gdnative/include/net/godot_net.h"
class StreamPeerGDNative : public StreamPeer {
-
GDCLASS(StreamPeerGDNative, StreamPeer);
protected:
@@ -51,11 +50,11 @@ public:
void set_native_stream_peer(const godot_net_stream_peer *p_interface);
/* Specific to StreamPeer */
- Error put_data(const uint8_t *p_data, int p_bytes);
- Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent);
- Error get_data(uint8_t *p_buffer, int p_bytes);
- Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received);
- int get_available_bytes() const;
+ Error put_data(const uint8_t *p_data, int p_bytes) override;
+ Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) override;
+ Error get_data(uint8_t *p_buffer, int p_bytes) override;
+ Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) override;
+ int get_available_bytes() const override;
};
#endif // STREAM_PEER_GDNATIVE_H
diff --git a/modules/gdnative/net/webrtc_gdnative.cpp b/modules/gdnative/net/webrtc_gdnative.cpp
index a7355e4d12..76ccbad009 100644
--- a/modules/gdnative/net/webrtc_gdnative.cpp
+++ b/modules/gdnative/net/webrtc_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -54,7 +54,7 @@ godot_error GDAPI godot_net_set_webrtc_library(const godot_net_webrtc_library *p
#ifdef WEBRTC_GDNATIVE_ENABLED
return (godot_error)WebRTCPeerConnectionGDNative::set_default_library(p_lib);
#else
- return ERR_UNAVAILABLE;
+ return (godot_error)ERR_UNAVAILABLE;
#endif
}
}
diff --git a/modules/gdnative/pluginscript/pluginscript_instance.cpp b/modules/gdnative/pluginscript/pluginscript_instance.cpp
index 7d17a7d5ab..432aa80325 100644
--- a/modules/gdnative/pluginscript/pluginscript_instance.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_instance.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
// Godot imports
#include "core/os/os.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
// PluginScript imports
#include "pluginscript_language.h"
diff --git a/modules/gdnative/pluginscript/pluginscript_instance.h b/modules/gdnative/pluginscript/pluginscript_instance.h
index 6309b6fde3..865080fddf 100644
--- a/modules/gdnative/pluginscript/pluginscript_instance.h
+++ b/modules/gdnative/pluginscript/pluginscript_instance.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define PLUGINSCRIPT_INSTANCE_H
// Godot imports
-#include "core/script_language.h"
+#include "core/object/script_language.h"
// PluginScript imports
#include <pluginscript/godot_pluginscript.h>
@@ -62,12 +62,6 @@ public:
virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- // Rely on default implementations provided by ScriptInstance for the moment.
- // Note that multilevel call could be removed in 3.0 release, so stay tuned
- // (see https://godotengine.org/qa/9244/can-override-the-_ready-and-_process-functions-child-classes)
- //virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount);
- //virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount);
-
virtual void notification(int p_notification);
virtual Ref<Script> get_script() const;
diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp
index bccbe95033..3ed1dcaca9 100644
--- a/modules/gdnative/pluginscript/pluginscript_language.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_language.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,9 +29,9 @@
/*************************************************************************/
// Godot imports
+#include "core/config/project_settings.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
// PluginScript imports
#include "pluginscript_language.h"
#include "pluginscript_script.h"
@@ -142,6 +142,10 @@ bool PluginScriptLanguage::supports_builtin_mode() const {
return _desc.supports_builtin_mode;
}
+bool PluginScriptLanguage::can_inherit_from_file() const {
+ return _desc.can_inherit_from_file;
+}
+
int PluginScriptLanguage::find_function(const String &p_function, const String &p_code) const {
if (_desc.find_function) {
return _desc.find_function(_data, (godot_string *)&p_function, (godot_string *)&p_code);
@@ -398,6 +402,32 @@ void PluginScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool
#endif
}
+bool PluginScriptLanguage::handles_global_class_type(const String &p_type) const {
+ return p_type == "PluginScript";
+}
+
+String PluginScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
+ if (!p_path.is_empty()) {
+ Ref<PluginScript> script = ResourceLoader::load(p_path, "PluginScript");
+ if (script.is_valid()) {
+ if (r_base_type) {
+ *r_base_type = script->get_instance_base_type();
+ }
+ if (r_icon_path) {
+ *r_icon_path = script->get_script_class_icon_path();
+ }
+ return script->get_script_class_name();
+ }
+ if (r_base_type) {
+ *r_base_type = String();
+ }
+ if (r_icon_path) {
+ *r_icon_path = String();
+ }
+ }
+ return String();
+}
+
void PluginScriptLanguage::lock() {
_lock.lock();
}
diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h
index dd6758713f..226b039265 100644
--- a/modules/gdnative/pluginscript/pluginscript_language.h
+++ b/modules/gdnative/pluginscript/pluginscript_language.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,9 +34,9 @@
// Godot imports
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
-#include "core/map.h"
-#include "core/script_language.h"
-#include "core/self_list.h"
+#include "core/object/script_language.h"
+#include "core/templates/map.h"
+#include "core/templates/self_list.h"
// PluginScript imports
#include "pluginscript_loader.h"
#include <pluginscript/godot_pluginscript.h>
@@ -78,7 +78,7 @@ public:
virtual Script *create_script() const;
virtual bool has_named_classes() const;
virtual bool supports_builtin_mode() const;
- virtual bool can_inherit_from_file() { return true; }
+ virtual bool can_inherit_from_file() const;
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 PackedStringArray &p_args) const;
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);
@@ -122,6 +122,11 @@ public:
virtual void frame();
+ /* GLOBAL CLASSES */
+
+ virtual bool handles_global_class_type(const String &p_type) const;
+ virtual String get_global_class_name(const String &p_path, String *r_base_type = nullptr, String *r_icon_path = nullptr) const;
+
void lock();
void unlock();
diff --git a/modules/gdnative/pluginscript/pluginscript_loader.cpp b/modules/gdnative/pluginscript/pluginscript_loader.cpp
index 64582cc517..cd1879a13e 100644
--- a/modules/gdnative/pluginscript/pluginscript_loader.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_loader.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,8 +40,9 @@ ResourceFormatLoaderPluginScript::ResourceFormatLoaderPluginScript(PluginScriptL
}
RES ResourceFormatLoaderPluginScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CANT_OPEN;
+ }
PluginScript *script = memnew(PluginScript);
script->init(_language);
@@ -55,8 +56,9 @@ RES ResourceFormatLoaderPluginScript::load(const String &p_path, const String &p
script->reload();
- if (r_error)
+ if (r_error) {
*r_error = OK;
+ }
return scriptres;
}
@@ -71,8 +73,9 @@ bool ResourceFormatLoaderPluginScript::handles_type(const String &p_type) const
String ResourceFormatLoaderPluginScript::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
- if (el == _language->get_extension())
+ if (el == _language->get_extension()) {
return _language->get_type();
+ }
return "";
}
@@ -101,13 +104,11 @@ Error ResourceFormatSaverPluginScript::save(const String &p_path, const RES &p_r
}
void ResourceFormatSaverPluginScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
-
if (Object::cast_to<PluginScript>(*p_resource)) {
p_extensions->push_back(_language->get_extension());
}
}
bool ResourceFormatSaverPluginScript::recognize(const RES &p_resource) const {
-
return Object::cast_to<PluginScript>(*p_resource) != nullptr;
}
diff --git a/modules/gdnative/pluginscript/pluginscript_loader.h b/modules/gdnative/pluginscript/pluginscript_loader.h
index e47754490a..7b1a7f5423 100644
--- a/modules/gdnative/pluginscript/pluginscript_loader.h
+++ b/modules/gdnative/pluginscript/pluginscript_loader.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,12 +34,11 @@
// Godot imports
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
-#include "core/script_language.h"
+#include "core/object/script_language.h"
class PluginScriptLanguage;
class ResourceFormatLoaderPluginScript : public ResourceFormatLoader {
-
PluginScriptLanguage *_language;
public:
@@ -51,7 +50,6 @@ public:
};
class ResourceFormatSaverPluginScript : public ResourceFormatSaver {
-
PluginScriptLanguage *_language;
public:
diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp
index 6b303c8716..31e6a81975 100644
--- a/modules/gdnative/pluginscript/pluginscript_script.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_script.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -56,7 +56,6 @@ void PluginScript::_bind_methods() {
}
PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Callable::CallError &r_error) {
-
r_error.error = Callable::CallError::CALL_OK;
// Create instance
@@ -84,7 +83,6 @@ PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int
}
Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
r_error.error = Callable::CallError::CALL_OK;
if (!_valid) {
@@ -156,10 +154,12 @@ Ref<Script> PluginScript::get_base_script() const {
}
StringName PluginScript::get_instance_base_type() const {
- if (_native_parent)
+ if (_native_parent) {
return _native_parent;
- if (_ref_base_parent.is_valid())
+ }
+ if (_ref_base_parent.is_valid()) {
return _ref_base_parent->get_instance_base_type();
+ }
return StringName();
}
@@ -167,7 +167,6 @@ void PluginScript::update_exports() {
#ifdef TOOLS_ENABLED
ASSERT_SCRIPT_VALID();
if (placeholders.size()) {
-
//update placeholders if any
Map<StringName, Variant> propdefvalues;
List<PropertyInfo> propinfos;
@@ -229,8 +228,9 @@ String PluginScript::get_source_code() const {
}
void PluginScript::set_source_code(const String &p_code) {
- if (_source == p_code)
+ if (_source == p_code) {
return;
+ }
_source = p_code;
}
@@ -244,11 +244,13 @@ Error PluginScript::reload(bool p_keep_state) {
_valid = false;
String basedir = _path;
- if (basedir == "")
+ if (basedir == "") {
basedir = get_path();
+ }
- if (basedir != "")
+ if (basedir != "") {
basedir = basedir.get_base_dir();
+ }
if (_data) {
_desc->finish(_data);
@@ -281,7 +283,6 @@ Error PluginScript::reload(bool p_keep_state) {
// ClassDB name (i.e. `Node2D`) or a resource path (i.e. `res://foo/bar.gd`)
StringName *base_name = (StringName *)&manifest.base;
if (*base_name) {
-
if (ClassDB::class_exists(*base_name)) {
_native_parent = *base_name;
} else {
@@ -301,6 +302,7 @@ Error PluginScript::reload(bool p_keep_state) {
_data = manifest.data;
_name = *(StringName *)&manifest.name;
_tool = manifest.is_tool;
+ _icon_path = *(String *)&manifest.icon_path;
Dictionary *members = (Dictionary *)&manifest.member_lines;
for (const Variant *key = members->next(); key != nullptr; key = members->next(key)) {
@@ -434,7 +436,6 @@ ScriptLanguage *PluginScript::get_language() const {
}
Error PluginScript::load_source_code(const String &p_path) {
-
Vector<uint8_t> sourcef;
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
@@ -476,11 +477,11 @@ void PluginScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
int PluginScript::get_member_line(const StringName &p_member) const {
#ifdef TOOLS_ENABLED
- if (_member_lines.has(p_member))
+ if (_member_lines.has(p_member)) {
return _member_lines[p_member];
- else
+ }
#endif
- return -1;
+ return -1;
}
Vector<ScriptNetData> PluginScript::get_rpc_methods() const {
@@ -499,15 +500,17 @@ uint16_t PluginScript::get_rpc_method_id(const StringName &p_method) const {
StringName PluginScript::get_rpc_method(const uint16_t p_rpc_method_id) const {
ASSERT_SCRIPT_VALID_V(StringName());
- if (p_rpc_method_id >= _rpc_methods.size())
+ if (p_rpc_method_id >= _rpc_methods.size()) {
return StringName();
+ }
return _rpc_methods[p_rpc_method_id].name;
}
MultiplayerAPI::RPCMode PluginScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const {
ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
- if (p_rpc_method_id >= _rpc_methods.size())
+ if (p_rpc_method_id >= _rpc_methods.size()) {
return MultiplayerAPI::RPC_MODE_DISABLED;
+ }
return _rpc_methods[p_rpc_method_id].mode;
}
@@ -532,15 +535,17 @@ uint16_t PluginScript::get_rset_property_id(const StringName &p_property) const
StringName PluginScript::get_rset_property(const uint16_t p_rset_property_id) const {
ASSERT_SCRIPT_VALID_V(StringName());
- if (p_rset_property_id >= _rpc_variables.size())
+ if (p_rset_property_id >= _rpc_variables.size()) {
return StringName();
+ }
return _rpc_variables[p_rset_property_id].name;
}
MultiplayerAPI::RPCMode PluginScript::get_rset_mode_by_id(const uint16_t p_rset_property_id) const {
ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
- if (p_rset_property_id >= _rpc_variables.size())
+ if (p_rset_property_id >= _rpc_variables.size()) {
return MultiplayerAPI::RPC_MODE_DISABLED;
+ }
return _rpc_variables[p_rset_property_id].mode;
}
@@ -550,11 +555,6 @@ MultiplayerAPI::RPCMode PluginScript::get_rset_mode(const StringName &p_variable
}
PluginScript::PluginScript() :
- _data(nullptr),
- _desc(nullptr),
- _language(nullptr),
- _tool(false),
- _valid(false),
_script_list(this) {
}
diff --git a/modules/gdnative/pluginscript/pluginscript_script.h b/modules/gdnative/pluginscript/pluginscript_script.h
index 70b9ca980b..1c86f2056d 100644
--- a/modules/gdnative/pluginscript/pluginscript_script.h
+++ b/modules/gdnative/pluginscript/pluginscript_script.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,24 +32,25 @@
#define PLUGINSCRIPT_SCRIPT_H
// Godot imports
-#include "core/script_language.h"
+
+#include "core/doc_data.h"
+#include "core/object/script_language.h"
// PluginScript imports
#include "pluginscript_language.h"
#include <pluginscript/godot_pluginscript.h>
class PluginScript : public Script {
-
GDCLASS(PluginScript, Script);
friend class PluginScriptInstance;
friend class PluginScriptLanguage;
private:
- godot_pluginscript_script_data *_data;
- const godot_pluginscript_script_desc *_desc;
- PluginScriptLanguage *_language;
- bool _tool;
- bool _valid;
+ godot_pluginscript_script_data *_data = nullptr;
+ const godot_pluginscript_script_desc *_desc = nullptr;
+ PluginScriptLanguage *_language = nullptr;
+ bool _tool = false;
+ bool _valid = false;
Ref<Script> _ref_base_parent;
StringName _native_parent;
@@ -68,11 +69,12 @@ private:
String _source;
String _path;
StringName _name;
+ String _icon_path;
protected:
static void _bind_methods();
- bool inherits_script(const Ref<Script> &p_script) const;
+ bool inherits_script(const Ref<Script> &p_script) const override;
PluginScriptInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Callable::CallError &r_error);
Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
@@ -80,57 +82,72 @@ protected:
#ifdef TOOLS_ENABLED
Set<PlaceHolderScriptInstance *> placeholders;
//void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
+ virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
#endif
public:
- virtual bool can_instance() const;
+ String get_script_class_name() const {
+ return _name;
+ }
+
+ String get_script_class_icon_path() const {
+ return _icon_path;
+ }
- virtual Ref<Script> get_base_script() const; //for script inheritance
+ virtual bool can_instance() const override;
- virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so
- virtual ScriptInstance *instance_create(Object *p_this);
- virtual bool instance_has(const Object *p_this) const;
+ virtual Ref<Script> get_base_script() const override; //for script inheritance
- virtual bool has_source_code() const;
- virtual String get_source_code() const;
- virtual void set_source_code(const String &p_code);
- virtual Error reload(bool p_keep_state = false);
+ virtual StringName get_instance_base_type() const override; // this may not work in all scripts, will return empty if so
+ virtual ScriptInstance *instance_create(Object *p_this) override;
+ virtual bool instance_has(const Object *p_this) const override;
+
+ virtual bool has_source_code() const override;
+ virtual String get_source_code() const override;
+ virtual void set_source_code(const String &p_code) override;
+ virtual Error reload(bool p_keep_state = false) override;
// TODO: load_source_code only allow utf-8 file, should handle bytecode as well ?
virtual Error load_source_code(const String &p_path);
- virtual bool has_method(const StringName &p_method) const;
- virtual MethodInfo get_method_info(const StringName &p_method) const;
+#ifdef TOOLS_ENABLED
+ virtual const Vector<DocData::ClassDoc> &get_documentation() const override {
+ static Vector<DocData::ClassDoc> docs;
+ return docs;
+ }
+#endif // TOOLS_ENABLED
+
+ virtual bool has_method(const StringName &p_method) const override;
+ virtual MethodInfo get_method_info(const StringName &p_method) const override;
bool has_property(const StringName &p_method) const;
PropertyInfo get_property_info(const StringName &p_property) const;
- bool is_tool() const { return _tool; }
- bool is_valid() const { return true; }
+ bool is_tool() const override { return _tool; }
+ bool is_valid() const override { return true; }
- virtual ScriptLanguage *get_language() const;
+ virtual ScriptLanguage *get_language() const override;
- virtual bool has_script_signal(const StringName &p_signal) const;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
+ virtual bool has_script_signal(const StringName &p_signal) const override;
+ virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override;
- virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const;
+ virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
- virtual void update_exports();
- virtual void get_script_method_list(List<MethodInfo> *r_methods) const;
- virtual void get_script_property_list(List<PropertyInfo> *r_properties) const;
+ virtual void update_exports() override;
+ virtual void get_script_method_list(List<MethodInfo> *r_methods) const override;
+ virtual void get_script_property_list(List<PropertyInfo> *r_properties) const override;
- virtual int get_member_line(const StringName &p_member) const;
+ virtual int get_member_line(const StringName &p_member) const override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual Vector<ScriptNetData> get_rpc_methods() const override;
+ virtual uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_property) const;
- virtual StringName get_rset_property(const uint16_t p_rset_property_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ virtual Vector<ScriptNetData> get_rset_properties() const override;
+ virtual uint16_t get_rset_property_id(const StringName &p_property) const override;
+ virtual StringName get_rset_property(const uint16_t p_rset_property_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
PluginScript();
void init(PluginScriptLanguage *language);
diff --git a/modules/gdnative/pluginscript/register_types.cpp b/modules/gdnative/pluginscript/register_types.cpp
index 97a48b0e89..b94538b2f7 100644
--- a/modules/gdnative/pluginscript/register_types.cpp
+++ b/modules/gdnative/pluginscript/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,11 +30,11 @@
#include "register_types.h"
+#include "core/config/project_settings.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "scene/main/scene_tree.h"
#include "pluginscript_language.h"
diff --git a/modules/gdnative/pluginscript/register_types.h b/modules/gdnative/pluginscript/register_types.h
index c6a64b4f40..2118f668e9 100644
--- a/modules/gdnative/pluginscript/register_types.h
+++ b/modules/gdnative/pluginscript/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp
index 67a286ee2e..31f4fecb19 100644
--- a/modules/gdnative/register_types.cpp
+++ b/modules/gdnative/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,11 +40,11 @@
#include "videodecoder/register_types.h"
#include "xr/register_types.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
+#include "core/config/project_settings.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_export.h"
@@ -53,7 +53,6 @@
#include "gdnative_library_singleton_editor.h"
class GDNativeExportPlugin : public EditorExportPlugin {
-
protected:
virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features);
};
@@ -77,7 +76,6 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty
Ref<ConfigFile> config = lib->get_config_file();
{
-
List<String> entry_keys;
config->get_section_keys("entry", &entry_keys);
@@ -144,52 +142,89 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty
}
}
+ // Add symbols for staticaly linked libraries on iOS
if (p_features.has("iOS")) {
- // Register symbols in the "fake" dynamic lookup table, because dlsym does not work well on iOS.
- LibrarySymbol expected_symbols[] = {
- { "gdnative_init", true },
- { "gdnative_terminate", false },
- { "nativescript_init", false },
- { "nativescript_frame", false },
- { "nativescript_thread_enter", false },
- { "nativescript_thread_exit", false },
- { "gdnative_singleton", false }
- };
- String declare_pattern = "extern \"C\" void $name(void)$weak;\n";
- String additional_code = "extern void register_dynamic_symbol(char *name, void *address);\n"
- "extern void add_ios_init_callback(void (*cb)());\n";
- String linker_flags = "";
- for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
- String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
- String code = declare_pattern.replace("$name", full_name);
- code = code.replace("$weak", expected_symbols[i].is_required ? "" : " __attribute__((weak))");
- additional_code += code;
-
- if (!expected_symbols[i].is_required) {
- if (linker_flags.length() > 0) {
- linker_flags += " ";
+ bool should_fake_dynamic = false;
+
+ List<String> entry_keys;
+ config->get_section_keys("entry", &entry_keys);
+
+ for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) {
+ String key = E->get();
+
+ Vector<String> tags = key.split(".");
+
+ bool skip = false;
+ for (int i = 0; i < tags.size(); i++) {
+ bool has_feature = p_features.has(tags[i]);
+
+ if (!has_feature) {
+ skip = true;
+ break;
}
- linker_flags += "-Wl,-U,_" + full_name;
}
- }
- additional_code += String("void $prefixinit() {\n").replace("$prefix", lib->get_symbol_prefix());
- String register_pattern = " if (&$name) register_dynamic_symbol((char *)\"$name\", (void *)$name);\n";
- for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
- String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
- additional_code += register_pattern.replace("$name", full_name);
+ if (skip) {
+ continue;
+ }
+
+ String entry_lib_path = config->get_value("entry", key);
+ if (entry_lib_path.begins_with("res://") && entry_lib_path.ends_with(".a")) {
+ // If we find static library that was used for export
+ // we should add a fake lookup table.
+ // In case of dynamic library being used,
+ // this symbols will not cause any issues with library loading.
+ should_fake_dynamic = true;
+ break;
+ }
}
- additional_code += "}\n";
- additional_code += String("struct $prefixstruct {$prefixstruct() {add_ios_init_callback($prefixinit);}};\n").replace("$prefix", lib->get_symbol_prefix());
- additional_code += String("$prefixstruct $prefixstruct_instance;\n").replace("$prefix", lib->get_symbol_prefix());
- add_ios_cpp_code(additional_code);
- add_ios_linker_flags(linker_flags);
+ if (should_fake_dynamic) {
+ // Register symbols in the "fake" dynamic lookup table, because dlsym does not work well on iOS.
+ LibrarySymbol expected_symbols[] = {
+ { "gdnative_init", true },
+ { "gdnative_terminate", false },
+ { "nativescript_init", false },
+ { "nativescript_frame", false },
+ { "nativescript_thread_enter", false },
+ { "nativescript_thread_exit", false },
+ { "gdnative_singleton", false }
+ };
+ String declare_pattern = "extern \"C\" void $name(void)$weak;\n";
+ String additional_code = "extern void register_dynamic_symbol(char *name, void *address);\n"
+ "extern void add_ios_init_callback(void (*cb)());\n";
+ String linker_flags = "";
+ for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
+ String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
+ String code = declare_pattern.replace("$name", full_name);
+ code = code.replace("$weak", expected_symbols[i].is_required ? "" : " __attribute__((weak))");
+ additional_code += code;
+
+ if (!expected_symbols[i].is_required) {
+ if (linker_flags.length() > 0) {
+ linker_flags += " ";
+ }
+ linker_flags += "-Wl,-U,_" + full_name;
+ }
+ }
+
+ additional_code += String("void $prefixinit() {\n").replace("$prefix", lib->get_symbol_prefix());
+ String register_pattern = " if (&$name) register_dynamic_symbol((char *)\"$name\", (void *)$name);\n";
+ for (unsigned long i = 0; i < sizeof(expected_symbols) / sizeof(expected_symbols[0]); ++i) {
+ String full_name = lib->get_symbol_prefix() + expected_symbols[i].name;
+ additional_code += register_pattern.replace("$name", full_name);
+ }
+ additional_code += "}\n";
+ additional_code += String("struct $prefixstruct {$prefixstruct() {add_ios_init_callback($prefixinit);}};\n").replace("$prefix", lib->get_symbol_prefix());
+ additional_code += String("$prefixstruct $prefixstruct_instance;\n").replace("$prefix", lib->get_symbol_prefix());
+
+ add_ios_cpp_code(additional_code);
+ add_ios_linker_flags(linker_flags);
+ }
}
}
static void editor_init_callback() {
-
GDNativeLibrarySingletonEditor *library_editor = memnew(GDNativeLibrarySingletonEditor);
library_editor->set_name(TTR("GDNative"));
ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor);
@@ -205,7 +240,6 @@ static void editor_init_callback() {
#endif
static godot_variant cb_standard_varcall(void *p_procedure_handle, godot_array *p_args) {
-
godot_gdnative_procedure_fn proc;
proc = (godot_gdnative_procedure_fn)p_procedure_handle;
@@ -220,7 +254,6 @@ Ref<GDNativeLibraryResourceLoader> resource_loader_gdnlib;
Ref<GDNativeLibraryResourceSaver> resource_saver_gdnlib;
void register_gdnative_types() {
-
#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(editor_init_callback);
@@ -259,8 +292,9 @@ void register_gdnative_types() {
for (int i = 0; i < singletons.size(); i++) {
String path = singletons[i];
- if (excluded.has(path))
+ if (excluded.has(path)) {
continue;
+ }
Ref<GDNativeLibrary> lib = ResourceLoader::load(path);
Ref<GDNative> singleton;
@@ -287,9 +321,7 @@ void register_gdnative_types() {
}
void unregister_gdnative_types() {
-
for (int i = 0; i < singleton_gdnatives.size(); i++) {
-
if (singleton_gdnatives[i].is_null()) {
continue;
}
diff --git a/modules/gdnative/register_types.h b/modules/gdnative/register_types.h
index b5c182f8b7..662c638442 100644
--- a/modules/gdnative/register_types.h
+++ b/modules/gdnative/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/tests/test_string.h b/modules/gdnative/tests/test_string.h
new file mode 100644
index 0000000000..3e2ba7451b
--- /dev/null
+++ b/modules/gdnative/tests/test_string.h
@@ -0,0 +1,1979 @@
+/*************************************************************************/
+/* test_string.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEST_GDNATIVE_STRING_H
+#define TEST_GDNATIVE_STRING_H
+
+namespace TestGDNativeString {
+
+#include "gdnative/string.h"
+
+#include "tests/test_macros.h"
+
+int u32scmp(const char32_t *l, const char32_t *r) {
+ for (; *l == *r && *l && *r; l++, r++)
+ ;
+ return *l - *r;
+}
+
+TEST_CASE("[GDNative String] Construct from Latin-1 char string") {
+ godot_string s;
+
+ godot_string_new_with_latin1_chars(&s, "Hello");
+ CHECK(u32scmp(godot_string_get_data(&s), U"Hello") == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_latin1_chars_and_len(&s, "Hello", 3);
+ CHECK(u32scmp(godot_string_get_data(&s), U"Hel") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Construct from wchar_t string") {
+ godot_string s;
+
+ godot_string_new_with_wide_chars(&s, L"Give me");
+ CHECK(u32scmp(godot_string_get_data(&s), U"Give me") == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_wide_chars_and_len(&s, L"Give me", 3);
+ CHECK(u32scmp(godot_string_get_data(&s), U"Giv") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Construct from UTF-8 char string") {
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char32_t u32str_short[] = { 0x0045, 0x0020, 0x304A, 0 };
+ static const uint8_t u8str[] = { 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
+
+ godot_string s;
+
+ godot_string_new_with_utf8_chars(&s, (const char *)u8str);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf8_chars_and_len(&s, (const char *)u8str, 5);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str_short) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf32_chars(&s, u32str);
+ godot_char_string cs = godot_string_utf8(&s);
+ godot_string_parse_utf8(&s, godot_char_string_get_data(&cs));
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+ godot_char_string_destroy(&cs);
+
+ godot_string_new_with_utf32_chars(&s, u32str);
+ cs = godot_string_utf8(&s);
+ godot_string_parse_utf8_with_len(&s, godot_char_string_get_data(&cs), godot_char_string_length(&cs));
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+ godot_char_string_destroy(&cs);
+}
+
+TEST_CASE("[GDNative String] Construct from UTF-8 string with BOM") {
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char32_t u32str_short[] = { 0x0045, 0x0020, 0x304A, 0 };
+ static const uint8_t u8str[] = { 0xEF, 0xBB, 0xBF, 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
+
+ godot_string s;
+
+ godot_string_new_with_utf8_chars(&s, (const char *)u8str);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf8_chars_and_len(&s, (const char *)u8str, 8);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str_short) == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Construct from UTF-16 string") {
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x1F3A4, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char32_t u32str_short[] = { 0x0045, 0x0020, 0x1F3A4, 0 };
+ static const char16_t u16str[] = { 0x0045, 0x0020, 0xD83C, 0xDFA4, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
+
+ godot_string s;
+
+ godot_string_new_with_utf16_chars(&s, u16str);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf16_chars_and_len(&s, u16str, 4);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str_short) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf32_chars(&s, u32str);
+ godot_char16_string cs = godot_string_utf16(&s);
+ godot_string_parse_utf16(&s, godot_char16_string_get_data(&cs));
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+ godot_char16_string_destroy(&cs);
+
+ godot_string_new_with_utf32_chars(&s, u32str);
+ cs = godot_string_utf16(&s);
+ godot_string_parse_utf16_with_len(&s, godot_char16_string_get_data(&cs), godot_char16_string_length(&cs));
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+ godot_char16_string_destroy(&cs);
+}
+
+TEST_CASE("[GDNative String] Construct from UTF-16 string with BOM ") {
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x1F3A4, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char32_t u32str_short[] = { 0x0045, 0x0020, 0x1F3A4, 0 };
+ static const char16_t u16str[] = { 0xFEFF, 0x0045, 0x0020, 0xD83C, 0xDFA4, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
+ static const char16_t u16str_swap[] = { 0xFFFE, 0x4500, 0x2000, 0x3CD8, 0xA4DF, 0x0F36, 0x8830, 0x4630, 0x3CD8, 0xA4DF, 0 };
+
+ godot_string s;
+
+ godot_string_new_with_utf16_chars(&s, u16str);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf16_chars(&s, u16str_swap);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf16_chars_and_len(&s, u16str, 5);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str_short) == 0);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_utf16_chars_and_len(&s, u16str_swap, 5);
+ CHECK(u32scmp(godot_string_get_data(&s), u32str_short) == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Construct string copy") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "Hello");
+ godot_string_new_copy(&t, &s);
+ CHECK(u32scmp(godot_string_get_data(&t), U"Hello") == 0);
+ godot_string_destroy(&t);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Construct empty string") {
+ godot_string s;
+
+ godot_string_new(&s);
+ CHECK(u32scmp(godot_string_get_data(&s), U"") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] ASCII/Latin-1") {
+ godot_string s;
+ godot_string_new_with_utf32_chars(&s, U"Primero Leche");
+
+ godot_char_string cs = godot_string_ascii(&s);
+ CHECK(strcmp(godot_char_string_get_data(&cs), "Primero Leche") == 0);
+ godot_char_string_destroy(&cs);
+
+ cs = godot_string_latin1(&s);
+ CHECK(strcmp(godot_char_string_get_data(&cs), "Primero Leche") == 0);
+ godot_char_string_destroy(&cs);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Comparisons (equal)") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "Test Compare");
+ godot_string_new_with_latin1_chars(&t, "Test Compare");
+ CHECK(godot_string_operator_equal(&s, &t));
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] Comparisons (operator <)") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "Bees");
+
+ godot_string_new_with_latin1_chars(&t, "Elephant");
+ CHECK(godot_string_operator_less(&s, &t));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Amber");
+ CHECK(!godot_string_operator_less(&s, &t));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Beatrix");
+ CHECK(!godot_string_operator_less(&s, &t));
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Concatenation (operator +)") {
+ godot_string s, t, x;
+
+ godot_string_new_with_latin1_chars(&s, "Hel");
+ godot_string_new_with_latin1_chars(&t, "lo");
+ x = godot_string_operator_plus(&s, &t);
+ CHECK(u32scmp(godot_string_get_data(&x), U"Hello") == 0);
+ godot_string_destroy(&x);
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] Testing size and length of string") {
+ godot_string s;
+
+ godot_string_new_with_latin1_chars(&s, "Mellon");
+ CHECK(godot_string_length(&s) == 6);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_latin1_chars(&s, "Mellon1");
+ CHECK(godot_string_length(&s) == 7);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Testing for empty string") {
+ godot_string s;
+
+ godot_string_new_with_latin1_chars(&s, "Mellon");
+ CHECK(!godot_string_is_empty(&s));
+ godot_string_destroy(&s);
+
+ godot_string_new_with_latin1_chars(&s, "");
+ CHECK(godot_string_is_empty(&s));
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Test chr") {
+ godot_string s;
+
+ s = godot_string_chr('H');
+ CHECK(u32scmp(godot_string_get_data(&s), U"H") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_chr(0x3012);
+ CHECK(godot_string_operator_index_const(&s, 0) == 0x3012);
+ godot_string_destroy(&s);
+
+ ERR_PRINT_OFF
+ s = godot_string_chr(0xd812);
+ CHECK(godot_string_operator_index_const(&s, 0) == 0xfffd); // Unpaired UTF-16 surrogate
+ godot_string_destroy(&s);
+
+ s = godot_string_chr(0x20d812);
+ CHECK(godot_string_operator_index_const(&s, 0) == 0xfffd); // Outside UTF-32 range
+ godot_string_destroy(&s);
+ ERR_PRINT_ON
+}
+
+TEST_CASE("[GDNative String] Operator []") {
+ godot_string s;
+
+ godot_string_new_with_latin1_chars(&s, "Hello");
+ CHECK(*godot_string_operator_index(&s, 1) == 'e');
+ CHECK(godot_string_operator_index_const(&s, 0) == 'H');
+ CHECK(godot_string_ord_at(&s, 0) == 'H');
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Case function test") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "MoMoNgA");
+
+ t = godot_string_to_upper(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), U"MOMONGA") == 0);
+ godot_string_destroy(&t);
+
+ t = godot_string_to_lower(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), U"momonga") == 0);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Case compare function test") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "MoMoNgA");
+ godot_string_new_with_latin1_chars(&t, "momonga");
+
+ CHECK(godot_string_casecmp_to(&s, &t) != 0);
+ CHECK(godot_string_nocasecmp_to(&s, &t) == 0);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] Natural compare function test") {
+ godot_string s, t;
+
+ godot_string_new_with_latin1_chars(&s, "img2.png");
+ godot_string_new_with_latin1_chars(&t, "img10.png");
+
+ CHECK(godot_string_nocasecmp_to(&s, &t) > 0);
+ CHECK(godot_string_naturalnocasecmp_to(&s, &t) < 0);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] hex_encode_buffer") {
+ static const uint8_t u8str[] = { 0x45, 0xE3, 0x81, 0x8A, 0x8F, 0xE3 };
+ godot_string s = godot_string_hex_encode_buffer(u8str, 6);
+ CHECK(u32scmp(godot_string_get_data(&s), U"45e3818a8fe3") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Substr") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "Killer Baby");
+ t = godot_string_substr(&s, 3, 4);
+ CHECK(u32scmp(godot_string_get_data(&t), U"ler ") == 0);
+ godot_string_destroy(&t);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Find") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "Pretty Woman Woman");
+
+ godot_string_new_with_latin1_chars(&t, "Revenge of the Monster Truck");
+ CHECK(godot_string_find(&s, &t) == -1);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "tty");
+ CHECK(godot_string_find(&s, &t) == 3);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Wo");
+ CHECK(godot_string_find_from(&s, &t, 9) == 13);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "man");
+ CHECK(godot_string_rfind(&s, &t) == 15);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Find no case") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "Pretty Whale Whale");
+
+ godot_string_new_with_latin1_chars(&t, "WHA");
+ CHECK(godot_string_findn(&s, &t) == 7);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "WHA");
+ CHECK(godot_string_findn_from(&s, &t, 9) == 13);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "WHA");
+ CHECK(godot_string_rfindn(&s, &t) == 13);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Revenge of the Monster SawFish");
+ CHECK(godot_string_findn(&s, &t) == -1);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Find MK") {
+ godot_packed_string_array keys;
+ godot_packed_string_array_new(&keys);
+
+#define PUSH_KEY(x) \
+ { \
+ godot_string t; \
+ godot_string_new_with_latin1_chars(&t, x); \
+ godot_packed_string_array_push_back(&keys, &t); \
+ godot_string_destroy(&t); \
+ }
+
+ PUSH_KEY("sty")
+ PUSH_KEY("tty")
+ PUSH_KEY("man")
+
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, "Pretty Woman");
+ godot_int key = 0;
+
+ CHECK(godot_string_findmk(&s, &keys) == 3);
+ CHECK(godot_string_findmk_from_in_place(&s, &keys, 0, &key) == 3);
+ CHECK(key == 1);
+
+ CHECK(godot_string_findmk_from(&s, &keys, 5) == 9);
+ CHECK(godot_string_findmk_from_in_place(&s, &keys, 5, &key) == 9);
+ CHECK(key == 2);
+
+ godot_string_destroy(&s);
+ godot_packed_string_array_destroy(&keys);
+
+#undef PUSH_KEY
+}
+
+TEST_CASE("[GDNative String] Find and replace") {
+ godot_string s, c, w;
+ godot_string_new_with_latin1_chars(&s, "Happy Birthday, Anna!");
+ godot_string_new_with_latin1_chars(&c, "Birthday");
+ godot_string_new_with_latin1_chars(&w, "Halloween");
+ godot_string t = godot_string_replace(&s, &c, &w);
+ CHECK(u32scmp(godot_string_get_data(&t), U"Happy Halloween, Anna!") == 0);
+ godot_string_destroy(&s);
+ godot_string_destroy(&c);
+ godot_string_destroy(&w);
+
+ godot_string_new_with_latin1_chars(&c, "H");
+ godot_string_new_with_latin1_chars(&w, "W");
+ s = godot_string_replace_first(&t, &c, &w);
+ godot_string_destroy(&t);
+ godot_string_destroy(&c);
+ godot_string_destroy(&w);
+
+ CHECK(u32scmp(godot_string_get_data(&s), U"Wappy Halloween, Anna!") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Insertion") {
+ godot_string s, t, r, u;
+ godot_string_new_with_latin1_chars(&s, "Who is Frederic?");
+ godot_string_new_with_latin1_chars(&t, "?");
+ godot_string_new_with_latin1_chars(&r, " Chopin");
+
+ u = godot_string_insert(&s, godot_string_find(&s, &t), &r);
+ CHECK(u32scmp(godot_string_get_data(&u), U"Who is Frederic Chopin?") == 0);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+ godot_string_destroy(&r);
+ godot_string_destroy(&u);
+}
+
+TEST_CASE("[GDNative String] Number to string") {
+ godot_string s;
+ s = godot_string_num(3.141593);
+ CHECK(u32scmp(godot_string_get_data(&s), U"3.141593") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_with_decimals(3.141593, 3);
+ CHECK(u32scmp(godot_string_get_data(&s), U"3.142") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_real(3.141593);
+ CHECK(u32scmp(godot_string_get_data(&s), U"3.141593") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_scientific(30000000);
+ CHECK(u32scmp(godot_string_get_data(&s), U"3e+07") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_int64(3141593, 10);
+ CHECK(u32scmp(godot_string_get_data(&s), U"3141593") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_int64(0xA141593, 16);
+ CHECK(u32scmp(godot_string_get_data(&s), U"a141593") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_num_int64_capitalized(0xA141593, 16, true);
+ CHECK(u32scmp(godot_string_get_data(&s), U"A141593") == 0);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] String to integer") {
+ static const wchar_t *wnums[4] = { L"1237461283", L"- 22", L"0", L" - 1123412" };
+ static const char *nums[4] = { "1237461283", "- 22", "0", " - 1123412" };
+ static const int num[4] = { 1237461283, -22, 0, -1123412 };
+
+ for (int i = 0; i < 4; i++) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, nums[i]);
+ CHECK(godot_string_to_int(&s) == num[i]);
+ godot_string_destroy(&s);
+
+ CHECK(godot_string_char_to_int(nums[i]) == num[i]);
+ CHECK(godot_string_wchar_to_int(wnums[i]) == num[i]);
+ }
+}
+
+TEST_CASE("[GDNative String] Hex to integer") {
+ static const char *nums[4] = { "0xFFAE", "22", "0", "AADDAD" };
+ static const int64_t num[4] = { 0xFFAE, 0x22, 0, 0xAADDAD };
+ static const bool wo_prefix[4] = { false, true, true, true };
+ static const bool w_prefix[4] = { true, false, true, false };
+
+ for (int i = 0; i < 4; i++) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, nums[i]);
+ CHECK((godot_string_hex_to_int_with_prefix(&s) == num[i]) == w_prefix[i]);
+ CHECK((godot_string_hex_to_int(&s) == num[i]) == wo_prefix[i]);
+ godot_string_destroy(&s);
+ }
+}
+
+TEST_CASE("[GDNative String] String to float") {
+ static const wchar_t *wnums[4] = { L"-12348298412.2", L"0.05", L"2.0002", L" -0.0001" };
+ static const char *nums[4] = { "-12348298412.2", "0.05", "2.0002", " -0.0001" };
+ static const double num[4] = { -12348298412.2, 0.05, 2.0002, -0.0001 };
+
+ for (int i = 0; i < 4; i++) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, nums[i]);
+ CHECK(!(ABS(godot_string_to_float(&s) - num[i]) > 0.00001));
+ godot_string_destroy(&s);
+
+ CHECK(!(ABS(godot_string_char_to_float(nums[i]) - num[i]) > 0.00001));
+ CHECK(!(ABS(godot_string_wchar_to_float(wnums[i], nullptr) - num[i]) > 0.00001));
+ }
+}
+
+TEST_CASE("[GDNative String] CamelCase to underscore") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "TestTestStringGD");
+
+ t = godot_string_camelcase_to_underscore(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), U"Test_Test_String_GD") == 0);
+ godot_string_destroy(&t);
+
+ t = godot_string_camelcase_to_underscore_lowercased(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), U"test_test_string_gd") == 0);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Slicing") {
+ godot_string s, c;
+ godot_string_new_with_latin1_chars(&s, "Mars,Jupiter,Saturn,Uranus");
+ godot_string_new_with_latin1_chars(&c, ",");
+
+ const char32_t *slices[4] = { U"Mars", U"Jupiter", U"Saturn", U"Uranus" };
+ for (int i = 0; i < godot_string_get_slice_count(&s, &c); i++) {
+ godot_string t;
+ t = godot_string_get_slice(&s, &c, i);
+ CHECK(u32scmp(godot_string_get_data(&t), slices[i]) == 0);
+ godot_string_destroy(&t);
+
+ t = godot_string_get_slicec(&s, U',', i);
+ CHECK(u32scmp(godot_string_get_data(&t), slices[i]) == 0);
+ godot_string_destroy(&t);
+ }
+
+ godot_string_destroy(&c);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Splitting") {
+ godot_string s, c;
+ godot_string_new_with_latin1_chars(&s, "Mars,Jupiter,Saturn,Uranus");
+ godot_string_new_with_latin1_chars(&c, ",");
+
+ godot_packed_string_array l;
+
+ const char32_t *slices_l[3] = { U"Mars", U"Jupiter", U"Saturn,Uranus" };
+ const char32_t *slices_r[3] = { U"Mars,Jupiter", U"Saturn", U"Uranus" };
+
+ l = godot_string_split_with_maxsplit(&s, &c, true, 2);
+ CHECK(godot_packed_string_array_size(&l) == 3);
+ for (int i = 0; i < godot_packed_string_array_size(&l); i++) {
+ godot_string t = godot_packed_string_array_get(&l, i);
+ CHECK(u32scmp(godot_string_get_data(&t), slices_l[i]) == 0);
+ godot_string_destroy(&t);
+ }
+ godot_packed_string_array_destroy(&l);
+
+ l = godot_string_rsplit_with_maxsplit(&s, &c, true, 2);
+ CHECK(godot_packed_string_array_size(&l) == 3);
+ for (int i = 0; i < godot_packed_string_array_size(&l); i++) {
+ godot_string t = godot_packed_string_array_get(&l, i);
+ CHECK(u32scmp(godot_string_get_data(&t), slices_r[i]) == 0);
+ godot_string_destroy(&t);
+ }
+ godot_packed_string_array_destroy(&l);
+ godot_string_destroy(&s);
+
+ godot_string_new_with_latin1_chars(&s, "Mars Jupiter Saturn Uranus");
+ const char32_t *slices_s[4] = { U"Mars", U"Jupiter", U"Saturn", U"Uranus" };
+ l = godot_string_split_spaces(&s);
+ for (int i = 0; i < godot_packed_string_array_size(&l); i++) {
+ godot_string t = godot_packed_string_array_get(&l, i);
+ CHECK(u32scmp(godot_string_get_data(&t), slices_s[i]) == 0);
+ godot_string_destroy(&t);
+ }
+ godot_packed_string_array_destroy(&l);
+ godot_string_destroy(&s);
+
+ godot_string c1, c2;
+ godot_string_new_with_latin1_chars(&c1, ";");
+ godot_string_new_with_latin1_chars(&c2, " ");
+
+ godot_string_new_with_latin1_chars(&s, "1.2;2.3 4.5");
+ const double slices_d[3] = { 1.2, 2.3, 4.5 };
+
+ godot_packed_float32_array lf = godot_string_split_floats_allow_empty(&s, &c1);
+ CHECK(godot_packed_float32_array_size(&lf) == 2);
+ for (int i = 0; i < godot_packed_float32_array_size(&lf); i++) {
+ CHECK(ABS(godot_packed_float32_array_get(&lf, i) - slices_d[i]) <= 0.00001);
+ }
+ godot_packed_float32_array_destroy(&lf);
+
+ godot_packed_string_array keys;
+ godot_packed_string_array_new(&keys);
+ godot_packed_string_array_push_back(&keys, &c1);
+ godot_packed_string_array_push_back(&keys, &c2);
+
+ lf = godot_string_split_floats_mk_allow_empty(&s, &keys);
+ CHECK(godot_packed_float32_array_size(&lf) == 3);
+ for (int i = 0; i < godot_packed_float32_array_size(&lf); i++) {
+ CHECK(ABS(godot_packed_float32_array_get(&lf, i) - slices_d[i]) <= 0.00001);
+ }
+ godot_packed_float32_array_destroy(&lf);
+
+ godot_string_destroy(&s);
+ godot_string_new_with_latin1_chars(&s, "1;2 4");
+ const int slices_i[3] = { 1, 2, 4 };
+
+ godot_packed_int32_array li = godot_string_split_ints_allow_empty(&s, &c1);
+ CHECK(godot_packed_int32_array_size(&li) == 2);
+ for (int i = 0; i < godot_packed_int32_array_size(&li); i++) {
+ CHECK(godot_packed_int32_array_get(&li, i) == slices_i[i]);
+ }
+ godot_packed_int32_array_destroy(&li);
+
+ li = godot_string_split_ints_mk_allow_empty(&s, &keys);
+ CHECK(godot_packed_int32_array_size(&li) == 3);
+ for (int i = 0; i < godot_packed_int32_array_size(&li); i++) {
+ CHECK(godot_packed_int32_array_get(&li, i) == slices_i[i]);
+ }
+ godot_packed_int32_array_destroy(&li);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&c);
+ godot_string_destroy(&c1);
+ godot_string_destroy(&c2);
+ godot_packed_string_array_destroy(&keys);
+}
+
+TEST_CASE("[GDNative String] Erasing") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "Josephine is such a cute girl!");
+ godot_string_new_with_latin1_chars(&t, "cute ");
+
+ godot_string_erase(&s, godot_string_find(&s, &t), godot_string_length(&t));
+
+ CHECK(u32scmp(godot_string_get_data(&s), U"Josephine is such a girl!") == 0);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+struct test_27_data {
+ char const *data;
+ char const *part;
+ bool expected;
+};
+
+TEST_CASE("[GDNative String] Begins with") {
+ test_27_data tc[] = {
+ { "res://foobar", "res://", true },
+ { "res", "res://", false },
+ { "abc", "abc", true }
+ };
+ size_t count = sizeof(tc) / sizeof(tc[0]);
+ bool state = true;
+ for (size_t i = 0; state && i < count; ++i) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, tc[i].data);
+
+ state = godot_string_begins_with_char_array(&s, tc[i].part) == tc[i].expected;
+ if (state) {
+ godot_string t;
+ godot_string_new_with_latin1_chars(&t, tc[i].part);
+ state = godot_string_begins_with(&s, &t) == tc[i].expected;
+ godot_string_destroy(&t);
+ }
+ godot_string_destroy(&s);
+
+ CHECK(state);
+ if (!state) {
+ break;
+ }
+ };
+ CHECK(state);
+}
+
+TEST_CASE("[GDNative String] Ends with") {
+ test_27_data tc[] = {
+ { "res://foobar", "foobar", true },
+ { "res", "res://", false },
+ { "abc", "abc", true }
+ };
+ size_t count = sizeof(tc) / sizeof(tc[0]);
+ bool state = true;
+ for (size_t i = 0; state && i < count; ++i) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, tc[i].data);
+
+ state = godot_string_ends_with_char_array(&s, tc[i].part) == tc[i].expected;
+ if (state) {
+ godot_string t;
+ godot_string_new_with_latin1_chars(&t, tc[i].part);
+ state = godot_string_ends_with(&s, &t) == tc[i].expected;
+ godot_string_destroy(&t);
+ }
+ godot_string_destroy(&s);
+
+ CHECK(state);
+ if (!state) {
+ break;
+ }
+ };
+ CHECK(state);
+}
+
+TEST_CASE("[GDNative String] format") {
+ godot_string value_format, t;
+ godot_string_new_with_latin1_chars(&value_format, "red=\"$red\" green=\"$green\" blue=\"$blue\" alpha=\"$alpha\"");
+
+ godot_variant key_v, val_v;
+ godot_dictionary value_dictionary;
+ godot_dictionary_new(&value_dictionary);
+
+ godot_string_new_with_latin1_chars(&t, "red");
+ godot_variant_new_string(&key_v, &t);
+ godot_string_destroy(&t);
+ godot_variant_new_int(&val_v, 10);
+ godot_dictionary_set(&value_dictionary, &key_v, &val_v);
+ godot_variant_destroy(&key_v);
+ godot_variant_destroy(&val_v);
+
+ godot_string_new_with_latin1_chars(&t, "green");
+ godot_variant_new_string(&key_v, &t);
+ godot_string_destroy(&t);
+ godot_variant_new_int(&val_v, 20);
+ godot_dictionary_set(&value_dictionary, &key_v, &val_v);
+ godot_variant_destroy(&key_v);
+ godot_variant_destroy(&val_v);
+
+ godot_string_new_with_latin1_chars(&t, "blue");
+ godot_variant_new_string(&key_v, &t);
+ godot_string_destroy(&t);
+ godot_string_new_with_latin1_chars(&t, "bla");
+ godot_variant_new_string(&val_v, &t);
+ godot_string_destroy(&t);
+ godot_dictionary_set(&value_dictionary, &key_v, &val_v);
+ godot_variant_destroy(&key_v);
+ godot_variant_destroy(&val_v);
+
+ godot_string_new_with_latin1_chars(&t, "alpha");
+ godot_variant_new_string(&key_v, &t);
+ godot_string_destroy(&t);
+ godot_variant_new_real(&val_v, 0.4);
+ godot_dictionary_set(&value_dictionary, &key_v, &val_v);
+ godot_variant_destroy(&key_v);
+ godot_variant_destroy(&val_v);
+
+ godot_variant dict_v;
+ godot_variant_new_dictionary(&dict_v, &value_dictionary);
+ godot_string s = godot_string_format_with_custom_placeholder(&value_format, &dict_v, "$_");
+
+ CHECK(u32scmp(godot_string_get_data(&s), U"red=\"10\" green=\"20\" blue=\"bla\" alpha=\"0.4\"") == 0);
+
+ godot_dictionary_destroy(&value_dictionary);
+ godot_string_destroy(&s);
+ godot_variant_destroy(&dict_v);
+ godot_string_destroy(&value_format);
+}
+
+TEST_CASE("[GDNative String] sprintf") {
+ //godot_string GDAPI (const godot_string *p_self, const godot_array *p_values, godot_bool *p_error);
+ godot_string format, output;
+ godot_array args;
+ bool error;
+
+#define ARRAY_PUSH_STRING(x) \
+ { \
+ godot_variant v; \
+ godot_string t; \
+ godot_string_new_with_latin1_chars(&t, x); \
+ godot_variant_new_string(&v, &t); \
+ godot_string_destroy(&t); \
+ godot_array_push_back(&args, &v); \
+ godot_variant_destroy(&v); \
+ }
+
+#define ARRAY_PUSH_INT(x) \
+ { \
+ godot_variant v; \
+ godot_variant_new_int(&v, x); \
+ godot_array_push_back(&args, &v); \
+ godot_variant_destroy(&v); \
+ }
+
+#define ARRAY_PUSH_REAL(x) \
+ { \
+ godot_variant v; \
+ godot_variant_new_real(&v, x); \
+ godot_array_push_back(&args, &v); \
+ godot_variant_destroy(&v); \
+ }
+
+ godot_array_new(&args);
+
+ // %%
+ godot_string_new_with_latin1_chars(&format, "fish %% frog");
+ godot_array_clear(&args);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish % frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+ //////// INTS
+
+ // Int
+ godot_string_new_with_latin1_chars(&format, "fish %d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 5 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Int left padded with zeroes.
+ godot_string_new_with_latin1_chars(&format, "fish %05d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 00005 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Int left padded with spaces.
+ godot_string_new_with_latin1_chars(&format, "fish %5d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 5 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Int right padded with spaces.
+ godot_string_new_with_latin1_chars(&format, "fish %-5d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 5 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Int with sign (positive).
+ godot_string_new_with_latin1_chars(&format, "fish %+d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish +5 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Negative int.
+ godot_string_new_with_latin1_chars(&format, "fish %d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(-5);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish -5 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Hex (lower)
+ godot_string_new_with_latin1_chars(&format, "fish %x frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(45);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 2d frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Hex (upper)
+ godot_string_new_with_latin1_chars(&format, "fish %X frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(45);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 2D frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Octal
+ godot_string_new_with_latin1_chars(&format, "fish %o frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 143 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+ ////// REALS
+
+ // Real
+ godot_string_new_with_latin1_chars(&format, "fish %f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.990000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real left-padded
+ godot_string_new_with_latin1_chars(&format, "fish %11f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.990000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real right-padded
+ godot_string_new_with_latin1_chars(&format, "fish %-11f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.990000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real given int.
+ godot_string_new_with_latin1_chars(&format, "fish %f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.000000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real with sign (positive).
+ godot_string_new_with_latin1_chars(&format, "fish %+f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish +99.990000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real with 1 decimals.
+ godot_string_new_with_latin1_chars(&format, "fish %.1f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 100.0 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real with 12 decimals.
+ godot_string_new_with_latin1_chars(&format, "fish %.12f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.990000000000 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Real with no decimals.
+ godot_string_new_with_latin1_chars(&format, "fish %.f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 100 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ /////// Strings.
+
+ // String
+ godot_string_new_with_latin1_chars(&format, "fish %s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish cheese frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // String left-padded
+ godot_string_new_with_latin1_chars(&format, "fish %10s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish cheese frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // String right-padded
+ godot_string_new_with_latin1_chars(&format, "fish %-10s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish cheese frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ ///// Characters
+
+ // Character as string.
+ godot_string_new_with_latin1_chars(&format, "fish %c frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("A");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish A frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Character as int.
+ godot_string_new_with_latin1_chars(&format, "fish %c frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(65);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish A frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ ///// Dynamic width
+
+ // String dynamic width
+ godot_string_new_with_latin1_chars(&format, "fish %*s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(10);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ REQUIRE(u32scmp(godot_string_get_data(&output), U"fish cheese frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Int dynamic width
+ godot_string_new_with_latin1_chars(&format, "fish %*d frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(10);
+ ARRAY_PUSH_INT(99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ REQUIRE(u32scmp(godot_string_get_data(&output), U"fish 99 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Float dynamic width
+ godot_string_new_with_latin1_chars(&format, "fish %*.*f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_INT(10);
+ ARRAY_PUSH_INT(3);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error == false);
+ CHECK(u32scmp(godot_string_get_data(&output), U"fish 99.990 frog") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ ///// Errors
+
+ // More formats than arguments.
+ godot_string_new_with_latin1_chars(&format, "fish %s %s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"not enough arguments for format string") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // More arguments than formats.
+ godot_string_new_with_latin1_chars(&format, "fish %s frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("hello");
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"not all arguments converted during string formatting") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Incomplete format.
+ godot_string_new_with_latin1_chars(&format, "fish %10");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"incomplete format") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Bad character in format string
+ godot_string_new_with_latin1_chars(&format, "fish %&f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"unsupported format character") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Too many decimals.
+ godot_string_new_with_latin1_chars(&format, "fish %2.2.2f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"too many decimal points in format") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // * not a number
+ godot_string_new_with_latin1_chars(&format, "fish %*f frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("cheese");
+ ARRAY_PUSH_REAL(99.99);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"* wants number") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Character too long.
+ godot_string_new_with_latin1_chars(&format, "fish %c frog");
+ godot_array_clear(&args);
+ ARRAY_PUSH_STRING("sc");
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"%c requires number or single-character string") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ // Character bad type.
+ godot_string_new_with_latin1_chars(&format, "fish %c frog");
+ godot_array_clear(&args);
+ godot_array t;
+ godot_array_new(&t);
+ godot_variant v;
+ godot_variant_new_array(&v, &t);
+ godot_array_destroy(&t);
+ godot_array_push_back(&args, &v);
+ godot_variant_destroy(&v);
+ output = godot_string_sprintf(&format, &args, &error);
+ REQUIRE(error);
+ CHECK(u32scmp(godot_string_get_data(&output), U"%c requires number or single-character string") == 0);
+ godot_string_destroy(&format);
+ godot_string_destroy(&output);
+
+ godot_array_destroy(&args);
+#undef ARRAY_PUSH_INT
+#undef ARRAY_PUSH_REAL
+#undef ARRAY_PUSH_STRING
+}
+
+TEST_CASE("[GDNative String] is_numeric") {
+#define IS_NUM_TEST(x, r) \
+ { \
+ godot_string t; \
+ godot_string_new_with_latin1_chars(&t, x); \
+ CHECK(godot_string_is_numeric(&t) == r); \
+ godot_string_destroy(&t); \
+ }
+
+ IS_NUM_TEST("12", true);
+ IS_NUM_TEST("1.2", true);
+ IS_NUM_TEST("AF", false);
+ IS_NUM_TEST("-12", true);
+ IS_NUM_TEST("-1.2", true);
+
+#undef IS_NUM_TEST
+}
+
+TEST_CASE("[GDNative String] pad") {
+ godot_string s, c;
+ godot_string_new_with_latin1_chars(&s, "test");
+ godot_string_new_with_latin1_chars(&c, "x");
+
+ godot_string l = godot_string_lpad_with_custom_character(&s, 10, &c);
+ CHECK(u32scmp(godot_string_get_data(&l), U"xxxxxxtest") == 0);
+ godot_string_destroy(&l);
+
+ godot_string r = godot_string_rpad_with_custom_character(&s, 10, &c);
+ CHECK(u32scmp(godot_string_get_data(&r), U"testxxxxxx") == 0);
+ godot_string_destroy(&r);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&c);
+
+ godot_string_new_with_latin1_chars(&s, "10.10");
+ c = godot_string_pad_decimals(&s, 4);
+ CHECK(u32scmp(godot_string_get_data(&c), U"10.1000") == 0);
+ godot_string_destroy(&c);
+ c = godot_string_pad_zeros(&s, 4);
+ CHECK(u32scmp(godot_string_get_data(&c), U"0010.10") == 0);
+ godot_string_destroy(&c);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] is_subsequence_of") {
+ godot_string a, t;
+ godot_string_new_with_latin1_chars(&a, "is subsequence of");
+
+ godot_string_new_with_latin1_chars(&t, "sub");
+ CHECK(godot_string_is_subsequence_of(&t, &a));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Sub");
+ CHECK(!godot_string_is_subsequence_of(&t, &a));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Sub");
+ CHECK(godot_string_is_subsequence_ofi(&t, &a));
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&a);
+}
+
+TEST_CASE("[GDNative String] match") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "*.png");
+
+ godot_string_new_with_latin1_chars(&t, "img1.png");
+ CHECK(godot_string_match(&t, &s));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "img1.jpeg");
+ CHECK(!godot_string_match(&t, &s));
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "img1.Png");
+ CHECK(!godot_string_match(&t, &s));
+ CHECK(godot_string_matchn(&t, &s));
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] IPVX address to string") {
+ godot_string ip;
+
+ godot_string_new_with_latin1_chars(&ip, "192.168.0.1");
+ CHECK(godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "192.368.0.1");
+ CHECK(!godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
+ CHECK(godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "2001:0db8:85j3:0000:0000:8a2e:0370:7334");
+ CHECK(!godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "2001:0db8:85f345:0000:0000:8a2e:0370:7334");
+ CHECK(!godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "2001:0db8::0:8a2e:370:7334");
+ CHECK(godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+
+ godot_string_new_with_latin1_chars(&ip, "::ffff:192.168.0.1");
+ CHECK(godot_string_is_valid_ip_address(&ip));
+ godot_string_destroy(&ip);
+}
+
+TEST_CASE("[GDNative String] Capitalize against many strings") {
+#define CAP_TEST(i, o) \
+ godot_string_new_with_latin1_chars(&input, i); \
+ godot_string_new_with_latin1_chars(&output, o); \
+ test = godot_string_capitalize(&input); \
+ CHECK(u32scmp(godot_string_get_data(&output), godot_string_get_data(&test)) == 0); \
+ godot_string_destroy(&input); \
+ godot_string_destroy(&output); \
+ godot_string_destroy(&test);
+
+ godot_string input, output, test;
+
+ CAP_TEST("bytes2var", "Bytes 2 Var");
+ CAP_TEST("linear2db", "Linear 2 Db");
+ CAP_TEST("vector3", "Vector 3");
+ CAP_TEST("sha256", "Sha 256");
+ CAP_TEST("2db", "2 Db");
+ CAP_TEST("PascalCase", "Pascal Case");
+ CAP_TEST("PascalPascalCase", "Pascal Pascal Case");
+ CAP_TEST("snake_case", "Snake Case");
+ CAP_TEST("snake_snake_case", "Snake Snake Case");
+ CAP_TEST("sha256sum", "Sha 256 Sum");
+ CAP_TEST("cat2dog", "Cat 2 Dog");
+ CAP_TEST("function(name)", "Function(name)");
+ CAP_TEST("snake_case_function(snake_case_arg)", "Snake Case Function(snake Case Arg)");
+ CAP_TEST("snake_case_function( snake_case_arg )", "Snake Case Function( Snake Case Arg )");
+
+#undef CAP_TEST
+}
+
+TEST_CASE("[GDNative String] lstrip and rstrip") {
+#define LSTRIP_TEST(x, y, z) \
+ { \
+ godot_string xx, yy, zz, rr; \
+ godot_string_new_with_latin1_chars(&xx, x); \
+ godot_string_new_with_latin1_chars(&yy, y); \
+ godot_string_new_with_latin1_chars(&zz, z); \
+ rr = godot_string_lstrip(&xx, &yy); \
+ state = state && (u32scmp(godot_string_get_data(&rr), godot_string_get_data(&zz)) == 0); \
+ godot_string_destroy(&xx); \
+ godot_string_destroy(&yy); \
+ godot_string_destroy(&zz); \
+ godot_string_destroy(&rr); \
+ }
+
+#define RSTRIP_TEST(x, y, z) \
+ { \
+ godot_string xx, yy, zz, rr; \
+ godot_string_new_with_latin1_chars(&xx, x); \
+ godot_string_new_with_latin1_chars(&yy, y); \
+ godot_string_new_with_latin1_chars(&zz, z); \
+ rr = godot_string_rstrip(&xx, &yy); \
+ state = state && (u32scmp(godot_string_get_data(&rr), godot_string_get_data(&zz)) == 0); \
+ godot_string_destroy(&xx); \
+ godot_string_destroy(&yy); \
+ godot_string_destroy(&zz); \
+ godot_string_destroy(&rr); \
+ }
+
+#define LSTRIP_UTF8_TEST(x, y, z) \
+ { \
+ godot_string xx, yy, zz, rr; \
+ godot_string_new_with_utf8_chars(&xx, x); \
+ godot_string_new_with_utf8_chars(&yy, y); \
+ godot_string_new_with_utf8_chars(&zz, z); \
+ rr = godot_string_lstrip(&xx, &yy); \
+ state = state && (u32scmp(godot_string_get_data(&rr), godot_string_get_data(&zz)) == 0); \
+ godot_string_destroy(&xx); \
+ godot_string_destroy(&yy); \
+ godot_string_destroy(&zz); \
+ godot_string_destroy(&rr); \
+ }
+
+#define RSTRIP_UTF8_TEST(x, y, z) \
+ { \
+ godot_string xx, yy, zz, rr; \
+ godot_string_new_with_utf8_chars(&xx, x); \
+ godot_string_new_with_utf8_chars(&yy, y); \
+ godot_string_new_with_utf8_chars(&zz, z); \
+ rr = godot_string_rstrip(&xx, &yy); \
+ state = state && (u32scmp(godot_string_get_data(&rr), godot_string_get_data(&zz)) == 0); \
+ godot_string_destroy(&xx); \
+ godot_string_destroy(&yy); \
+ godot_string_destroy(&zz); \
+ godot_string_destroy(&rr); \
+ }
+
+ bool state = true;
+
+ // strip none
+ LSTRIP_TEST("abc", "", "abc");
+ RSTRIP_TEST("abc", "", "abc");
+ // strip one
+ LSTRIP_TEST("abc", "a", "bc");
+ RSTRIP_TEST("abc", "c", "ab");
+ // strip lots
+ LSTRIP_TEST("bababbababccc", "ab", "ccc");
+ RSTRIP_TEST("aaabcbcbcbbcbbc", "cb", "aaa");
+ // strip empty string
+ LSTRIP_TEST("", "", "");
+ RSTRIP_TEST("", "", "");
+ // strip to empty string
+ LSTRIP_TEST("abcabcabc", "bca", "");
+ RSTRIP_TEST("abcabcabc", "bca", "");
+ // don't strip wrong end
+ LSTRIP_TEST("abc", "c", "abc");
+ LSTRIP_TEST("abca", "a", "bca");
+ RSTRIP_TEST("abc", "a", "abc");
+ RSTRIP_TEST("abca", "a", "abc");
+ // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
+ // and the same second as "ÿ" (\u00ff)
+ LSTRIP_UTF8_TEST("¿", "µÿ", "¿");
+ RSTRIP_UTF8_TEST("¿", "µÿ", "¿");
+ LSTRIP_UTF8_TEST("µ¿ÿ", "µÿ", "¿ÿ");
+ RSTRIP_UTF8_TEST("µ¿ÿ", "µÿ", "µ¿");
+
+ // the above tests repeated with additional superfluous strip chars
+
+ // strip none
+ LSTRIP_TEST("abc", "qwjkl", "abc");
+ RSTRIP_TEST("abc", "qwjkl", "abc");
+ // strip one
+ LSTRIP_TEST("abc", "qwajkl", "bc");
+ RSTRIP_TEST("abc", "qwcjkl", "ab");
+ // strip lots
+ LSTRIP_TEST("bababbababccc", "qwabjkl", "ccc");
+ RSTRIP_TEST("aaabcbcbcbbcbbc", "qwcbjkl", "aaa");
+ // strip empty string
+ LSTRIP_TEST("", "qwjkl", "");
+ RSTRIP_TEST("", "qwjkl", "");
+ // strip to empty string
+ LSTRIP_TEST("abcabcabc", "qwbcajkl", "");
+ RSTRIP_TEST("abcabcabc", "qwbcajkl", "");
+ // don't strip wrong end
+ LSTRIP_TEST("abc", "qwcjkl", "abc");
+ LSTRIP_TEST("abca", "qwajkl", "bca");
+ RSTRIP_TEST("abc", "qwajkl", "abc");
+ RSTRIP_TEST("abca", "qwajkl", "abc");
+ // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
+ // and the same second as "ÿ" (\u00ff)
+ LSTRIP_UTF8_TEST("¿", "qwaµÿjkl", "¿");
+ RSTRIP_UTF8_TEST("¿", "qwaµÿjkl", "¿");
+ LSTRIP_UTF8_TEST("µ¿ÿ", "qwaµÿjkl", "¿ÿ");
+ RSTRIP_UTF8_TEST("µ¿ÿ", "qwaµÿjkl", "µ¿");
+
+ CHECK(state);
+
+#undef LSTRIP_TEST
+#undef RSTRIP_TEST
+#undef LSTRIP_UTF8_TEST
+#undef RSTRIP_UTF8_TEST
+}
+
+TEST_CASE("[GDNative String] Cyrillic to_lower()") {
+ godot_string upper, lower, test;
+ godot_string_new_with_utf8_chars(&upper, "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ");
+ godot_string_new_with_utf8_chars(&lower, "абвгдеёжзийклмнопрстуфхцчшщъыьэюя");
+
+ test = godot_string_to_lower(&upper);
+
+ CHECK((u32scmp(godot_string_get_data(&test), godot_string_get_data(&lower)) == 0));
+
+ godot_string_destroy(&upper);
+ godot_string_destroy(&lower);
+ godot_string_destroy(&test);
+}
+
+TEST_CASE("[GDNative String] Count and countn functionality") {
+#define COUNT_TEST(x, y, r) \
+ { \
+ godot_string s, t; \
+ godot_string_new_with_latin1_chars(&s, x); \
+ godot_string_new_with_latin1_chars(&t, y); \
+ state = state && (godot_string_count(&s, &t, 0, 0) == r); \
+ godot_string_destroy(&s); \
+ godot_string_destroy(&t); \
+ }
+
+#define COUNTR_TEST(x, y, a, b, r) \
+ { \
+ godot_string s, t; \
+ godot_string_new_with_latin1_chars(&s, x); \
+ godot_string_new_with_latin1_chars(&t, y); \
+ state = state && (godot_string_count(&s, &t, a, b) == r); \
+ godot_string_destroy(&s); \
+ godot_string_destroy(&t); \
+ }
+
+#define COUNTN_TEST(x, y, r) \
+ { \
+ godot_string s, t; \
+ godot_string_new_with_latin1_chars(&s, x); \
+ godot_string_new_with_latin1_chars(&t, y); \
+ state = state && (godot_string_countn(&s, &t, 0, 0) == r); \
+ godot_string_destroy(&s); \
+ godot_string_destroy(&t); \
+ }
+
+#define COUNTNR_TEST(x, y, a, b, r) \
+ { \
+ godot_string s, t; \
+ godot_string_new_with_latin1_chars(&s, x); \
+ godot_string_new_with_latin1_chars(&t, y); \
+ state = state && (godot_string_countn(&s, &t, a, b) == r); \
+ godot_string_destroy(&s); \
+ godot_string_destroy(&t); \
+ }
+ bool state = true;
+
+ COUNT_TEST("", "Test", 0);
+ COUNT_TEST("Test", "", 0);
+ COUNT_TEST("Test", "test", 0);
+ COUNT_TEST("Test", "TEST", 0);
+ COUNT_TEST("TEST", "TEST", 1);
+ COUNT_TEST("Test", "Test", 1);
+ COUNT_TEST("aTest", "Test", 1);
+ COUNT_TEST("Testa", "Test", 1);
+ COUNT_TEST("TestTestTest", "Test", 3);
+ COUNT_TEST("TestTestTest", "TestTest", 1);
+ COUNT_TEST("TestGodotTestGodotTestGodot", "Test", 3);
+
+ COUNTR_TEST("TestTestTestTest", "Test", 4, 8, 1);
+ COUNTR_TEST("TestTestTestTest", "Test", 4, 12, 2);
+ COUNTR_TEST("TestTestTestTest", "Test", 4, 16, 3);
+ COUNTR_TEST("TestTestTestTest", "Test", 4, 0, 3);
+
+ COUNTN_TEST("Test", "test", 1);
+ COUNTN_TEST("Test", "TEST", 1);
+ COUNTN_TEST("testTest-Testatest", "tEst", 4);
+ COUNTNR_TEST("testTest-TeStatest", "tEsT", 4, 16, 2);
+
+ CHECK(state);
+
+#undef COUNT_TEST
+#undef COUNTR_TEST
+#undef COUNTN_TEST
+#undef COUNTNR_TEST
+}
+
+TEST_CASE("[GDNative String] Bigrams") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, "abcd");
+ godot_packed_string_array bigr = godot_string_bigrams(&s);
+ godot_string_destroy(&s);
+
+ CHECK(godot_packed_string_array_size(&bigr) == 3);
+
+ t = godot_packed_string_array_get(&bigr, 0);
+ CHECK(u32scmp(godot_string_get_data(&t), U"ab") == 0);
+ godot_string_destroy(&t);
+
+ t = godot_packed_string_array_get(&bigr, 1);
+ CHECK(u32scmp(godot_string_get_data(&t), U"bc") == 0);
+ godot_string_destroy(&t);
+
+ t = godot_packed_string_array_get(&bigr, 2);
+ CHECK(u32scmp(godot_string_get_data(&t), U"cd") == 0);
+ godot_string_destroy(&t);
+
+ godot_packed_string_array_destroy(&bigr);
+}
+
+TEST_CASE("[GDNative String] c-escape/unescape") {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, "\\1\a2\b\f3\n45\r6\t7\v8\'9\?0\"");
+ godot_string t = godot_string_c_escape(&s);
+ godot_string u = godot_string_c_unescape(&t);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] dedent") {
+ godot_string s, t;
+ godot_string_new_with_latin1_chars(&s, " aaa\n bbb");
+ godot_string_new_with_latin1_chars(&t, "aaa\nbbb");
+ godot_string u = godot_string_dedent(&s);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Path functions") {
+ static const char *path[4] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc" };
+ static const char *base_dir[4] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot" };
+ static const char *base_name[4] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test" };
+ static const char *ext[4] = { "tscn", "xscn", "scn", "doc" };
+ static const char *file[4] = { "test.tscn", "test.xscn", "test.scn", "test.doc" };
+ static const bool abs[4] = { true, true, false, false };
+
+ for (int i = 0; i < 4; i++) {
+ godot_string s, t, u, f;
+ godot_string_new_with_latin1_chars(&s, path[i]);
+
+ t = godot_string_get_base_dir(&s);
+ godot_string_new_with_latin1_chars(&u, base_dir[i]);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ t = godot_string_get_basename(&s);
+ godot_string_new_with_latin1_chars(&u, base_name[i]);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ t = godot_string_get_extension(&s);
+ godot_string_new_with_latin1_chars(&u, ext[i]);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ t = godot_string_get_file(&s);
+ godot_string_new_with_latin1_chars(&u, file[i]);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string s_simp;
+ s_simp = godot_string_simplify_path(&s);
+ t = godot_string_get_base_dir(&s_simp);
+ godot_string_new_with_latin1_chars(&u, file[i]);
+ f = godot_string_plus_file(&t, &u);
+ CHECK(u32scmp(godot_string_get_data(&f), godot_string_get_data(&s_simp)) == 0);
+ godot_string_destroy(&f);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+ godot_string_destroy(&s_simp);
+
+ CHECK(godot_string_is_abs_path(&s) == abs[i]);
+ CHECK(godot_string_is_rel_path(&s) != abs[i]);
+
+ godot_string_destroy(&s);
+ }
+
+ static const char *file_name[3] = { "test.tscn", "test://.xscn", "?tes*t.scn" };
+ static const bool valid[3] = { true, false, false };
+ for (int i = 0; i < 3; i++) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, file_name[i]);
+ CHECK(godot_string_is_valid_filename(&s) == valid[i]);
+ godot_string_destroy(&s);
+ }
+}
+
+TEST_CASE("[GDNative String] hash") {
+ godot_string a, b, c;
+ godot_string_new_with_latin1_chars(&a, "Test");
+ godot_string_new_with_latin1_chars(&b, "Test");
+ godot_string_new_with_latin1_chars(&c, "West");
+ CHECK(godot_string_hash(&a) == godot_string_hash(&b));
+ CHECK(godot_string_hash(&a) != godot_string_hash(&c));
+
+ CHECK(godot_string_hash64(&a) == godot_string_hash64(&b));
+ CHECK(godot_string_hash64(&a) != godot_string_hash64(&c));
+
+ godot_string_destroy(&a);
+ godot_string_destroy(&b);
+ godot_string_destroy(&c);
+}
+
+TEST_CASE("[GDNative String] http_escape/unescape") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "Godot Engine:'docs'");
+ godot_string_new_with_latin1_chars(&t, "Godot%20Engine%3A%27docs%27");
+
+ u = godot_string_http_escape(&s);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+
+ u = godot_string_http_unescape(&t);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] percent_encode/decode") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "Godot Engine:'docs'");
+ godot_string_new_with_latin1_chars(&t, "Godot%20Engine%3a%27docs%27");
+
+ u = godot_string_percent_encode(&s);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+
+ u = godot_string_percent_decode(&t);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] xml_escape/unescape") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "\"Test\" <test@test&'test'>");
+
+ t = godot_string_xml_escape_with_quotes(&s);
+ u = godot_string_xml_unescape(&t);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ t = godot_string_xml_escape(&s);
+ u = godot_string_xml_unescape(&t);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Strip escapes") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "\t\tTest Test\r\n Test");
+ godot_string_new_with_latin1_chars(&t, "Test Test Test");
+
+ u = godot_string_strip_escapes(&s);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+
+ godot_string_destroy(&t);
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Strip edges") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "\t Test Test ");
+
+ godot_string_new_with_latin1_chars(&t, "Test Test ");
+ u = godot_string_strip_edges(&s, true, false);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "\t Test Test");
+ u = godot_string_strip_edges(&s, false, true);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "Test Test");
+ u = godot_string_strip_edges(&s, true, true);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Similarity") {
+ godot_string a, b, c;
+ godot_string_new_with_latin1_chars(&a, "Test");
+ godot_string_new_with_latin1_chars(&b, "West");
+ godot_string_new_with_latin1_chars(&c, "Toad");
+
+ CHECK(godot_string_similarity(&a, &b) > godot_string_similarity(&a, &c));
+
+ godot_string_destroy(&a);
+ godot_string_destroy(&b);
+ godot_string_destroy(&c);
+}
+
+TEST_CASE("[GDNative String] Trim") {
+ godot_string s, t, u, p;
+ godot_string_new_with_latin1_chars(&s, "aaaTestbbb");
+
+ godot_string_new_with_latin1_chars(&p, "aaa");
+ godot_string_new_with_latin1_chars(&t, "Testbbb");
+ u = godot_string_trim_prefix(&s, &p);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+ godot_string_destroy(&p);
+
+ godot_string_new_with_latin1_chars(&p, "bbb");
+ godot_string_new_with_latin1_chars(&t, "aaaTest");
+ u = godot_string_trim_suffix(&s, &p);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+ godot_string_destroy(&p);
+
+ godot_string_new_with_latin1_chars(&p, "Test");
+ u = godot_string_trim_suffix(&s, &p);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&s)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&p);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Right/Left") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, "aaaTestbbb");
+ // ^
+
+ godot_string_new_with_latin1_chars(&t, "tbbb");
+ u = godot_string_right(&s, 6);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&t, "aaaTes");
+ u = godot_string_left(&s, 6);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+}
+
+TEST_CASE("[GDNative String] Repeat") {
+ godot_string t, u;
+ godot_string_new_with_latin1_chars(&t, "ab");
+
+ u = godot_string_repeat(&t, 4);
+ CHECK(u32scmp(godot_string_get_data(&u), U"abababab") == 0);
+ godot_string_destroy(&u);
+
+ godot_string_destroy(&t);
+}
+
+TEST_CASE("[GDNative String] SHA1/SHA256/MD5") {
+ godot_string s, t, sha1, sha256, md5;
+ godot_string_new_with_latin1_chars(&s, "Godot");
+ godot_string_new_with_latin1_chars(&sha1, "a1e91f39b9fce6a9998b14bdbe2aa2b39dc2d201");
+ static uint8_t sha1_buf[20] = {
+ 0xA1, 0xE9, 0x1F, 0x39, 0xB9, 0xFC, 0xE6, 0xA9, 0x99, 0x8B, 0x14, 0xBD, 0xBE, 0x2A, 0xA2, 0xB3,
+ 0x9D, 0xC2, 0xD2, 0x01
+ };
+ godot_string_new_with_latin1_chars(&sha256, "2a02b2443f7985d89d09001086ae3dcfa6eb0f55c6ef170715d42328e16e6cb8");
+ static uint8_t sha256_buf[32] = {
+ 0x2A, 0x02, 0xB2, 0x44, 0x3F, 0x79, 0x85, 0xD8, 0x9D, 0x09, 0x00, 0x10, 0x86, 0xAE, 0x3D, 0xCF,
+ 0xA6, 0xEB, 0x0F, 0x55, 0xC6, 0xEF, 0x17, 0x07, 0x15, 0xD4, 0x23, 0x28, 0xE1, 0x6E, 0x6C, 0xB8
+ };
+ godot_string_new_with_latin1_chars(&md5, "4a336d087aeb0390da10ee2ea7cb87f8");
+ static uint8_t md5_buf[16] = {
+ 0x4A, 0x33, 0x6D, 0x08, 0x7A, 0xEB, 0x03, 0x90, 0xDA, 0x10, 0xEE, 0x2E, 0xA7, 0xCB, 0x87, 0xF8
+ };
+
+ godot_packed_byte_array buf = godot_string_sha1_buffer(&s);
+ CHECK(memcmp(sha1_buf, godot_packed_byte_array_ptr(&buf), 20) == 0);
+ godot_packed_byte_array_destroy(&buf);
+
+ t = godot_string_sha1_text(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), godot_string_get_data(&sha1)) == 0);
+ godot_string_destroy(&t);
+
+ buf = godot_string_sha256_buffer(&s);
+ CHECK(memcmp(sha256_buf, godot_packed_byte_array_ptr(&buf), 32) == 0);
+ godot_packed_byte_array_destroy(&buf);
+
+ t = godot_string_sha256_text(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), godot_string_get_data(&sha256)) == 0);
+ godot_string_destroy(&t);
+
+ buf = godot_string_md5_buffer(&s);
+ CHECK(memcmp(md5_buf, godot_packed_byte_array_ptr(&buf), 16) == 0);
+ godot_packed_byte_array_destroy(&buf);
+
+ t = godot_string_md5_text(&s);
+ CHECK(u32scmp(godot_string_get_data(&t), godot_string_get_data(&md5)) == 0);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+ godot_string_destroy(&sha1);
+ godot_string_destroy(&sha256);
+ godot_string_destroy(&md5);
+}
+
+TEST_CASE("[GDNative String] Join") {
+ godot_string s, t, u;
+ godot_string_new_with_latin1_chars(&s, ", ");
+
+ godot_packed_string_array parts;
+ godot_packed_string_array_new(&parts);
+ godot_string_new_with_latin1_chars(&t, "One");
+ godot_packed_string_array_push_back(&parts, &t);
+ godot_string_destroy(&t);
+ godot_string_new_with_latin1_chars(&t, "B");
+ godot_packed_string_array_push_back(&parts, &t);
+ godot_string_destroy(&t);
+ godot_string_new_with_latin1_chars(&t, "C");
+ godot_packed_string_array_push_back(&parts, &t);
+ godot_string_destroy(&t);
+
+ godot_string_new_with_latin1_chars(&u, "One, B, C");
+ t = godot_string_join(&s, &parts);
+ CHECK(u32scmp(godot_string_get_data(&u), godot_string_get_data(&t)) == 0);
+ godot_string_destroy(&u);
+ godot_string_destroy(&t);
+
+ godot_string_destroy(&s);
+ godot_packed_string_array_destroy(&parts);
+}
+
+TEST_CASE("[GDNative String] Is_*") {
+ static const char *data[12] = { "-30", "100", "10.1", "10,1", "1e2", "1e-2", "1e2e3", "0xAB", "AB", "Test1", "1Test", "Test*1" };
+ static bool isnum[12] = { true, true, true, false, false, false, false, false, false, false, false, false };
+ static bool isint[12] = { true, true, false, false, false, false, false, false, false, false, false, false };
+ static bool ishex[12] = { true, true, false, false, true, false, true, false, true, false, false, false };
+ static bool ishex_p[12] = { false, false, false, false, false, false, false, true, false, false, false, false };
+ static bool isflt[12] = { true, true, true, false, true, true, false, false, false, false, false, false };
+ static bool isid[12] = { false, false, false, false, false, false, false, false, true, true, false, false };
+
+ for (int i = 0; i < 12; i++) {
+ godot_string s;
+ godot_string_new_with_latin1_chars(&s, data[i]);
+ CHECK(godot_string_is_numeric(&s) == isnum[i]);
+ CHECK(godot_string_is_valid_integer(&s) == isint[i]);
+ CHECK(godot_string_is_valid_hex_number(&s, false) == ishex[i]);
+ CHECK(godot_string_is_valid_hex_number(&s, true) == ishex_p[i]);
+ CHECK(godot_string_is_valid_float(&s) == isflt[i]);
+ CHECK(godot_string_is_valid_identifier(&s) == isid[i]);
+ godot_string_destroy(&s);
+ }
+}
+
+TEST_CASE("[GDNative String] humanize_size") {
+ godot_string s;
+
+ s = godot_string_humanize_size(1000);
+ CHECK(u32scmp(godot_string_get_data(&s), U"1000 B") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_humanize_size(1025);
+ CHECK(u32scmp(godot_string_get_data(&s), U"1.00 KiB") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_humanize_size(1025300);
+ CHECK(u32scmp(godot_string_get_data(&s), U"1001.2 KiB") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_humanize_size(100523550);
+ CHECK(u32scmp(godot_string_get_data(&s), U"95.86 MiB") == 0);
+ godot_string_destroy(&s);
+
+ s = godot_string_humanize_size(5345555000);
+ CHECK(u32scmp(godot_string_get_data(&s), U"4.97 GiB") == 0);
+ godot_string_destroy(&s);
+}
+} // namespace TestGDNativeString
+
+#endif // TEST_GDNATIVE_STRING_H
diff --git a/modules/gdnative/text/SCsub b/modules/gdnative/text/SCsub
new file mode 100644
index 0000000000..0b2db3b504
--- /dev/null
+++ b/modules/gdnative/text/SCsub
@@ -0,0 +1,6 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_gdnative")
+
+env_gdnative.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/gdnative/xr/config.py b/modules/gdnative/text/config.py
index d22f9454ed..d22f9454ed 100644
--- a/modules/gdnative/xr/config.py
+++ b/modules/gdnative/text/config.py
diff --git a/modules/gdnative/text/register_types.cpp b/modules/gdnative/text/register_types.cpp
new file mode 100644
index 0000000000..67385d2fbf
--- /dev/null
+++ b/modules/gdnative/text/register_types.cpp
@@ -0,0 +1,36 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+#include "text_server_gdnative.h"
+
+void register_text_server_gdn_types() {}
+
+void unregister_text_server_gdn_types() {}
diff --git a/modules/gdnative/text/register_types.h b/modules/gdnative/text/register_types.h
new file mode 100644
index 0000000000..cd4f2a3089
--- /dev/null
+++ b/modules/gdnative/text/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEXT_REGISTER_TYPES_H
+#define TEXT_REGISTER_TYPES_H
+
+void register_text_server_gdn_types();
+void unregister_text_server_gdn_types();
+
+#endif // TEXT_REGISTER_TYPES_H
diff --git a/modules/gdnative/text/text_server_gdnative.cpp b/modules/gdnative/text/text_server_gdnative.cpp
new file mode 100644
index 0000000000..f670d4af6f
--- /dev/null
+++ b/modules/gdnative/text/text_server_gdnative.cpp
@@ -0,0 +1,853 @@
+/*************************************************************************/
+/* text_server_gdnative.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "text_server_gdnative.h"
+
+bool TextServerGDNative::has_feature(Feature p_feature) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->has_feature(data, (godot_int)p_feature);
+}
+
+String TextServerGDNative::get_name() const {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ godot_string result = interface->get_name(data);
+ String name = *(String *)&result;
+ godot_string_destroy(&result);
+ return name;
+}
+
+void TextServerGDNative::free(RID p_rid) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->free(data, (godot_rid *)&p_rid);
+}
+
+bool TextServerGDNative::has(RID p_rid) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->has(data, (godot_rid *)&p_rid);
+}
+
+bool TextServerGDNative::load_support_data(const String &p_filename) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->load_support_data(data, (godot_string *)&p_filename);
+}
+
+#ifdef TOOLS_ENABLED
+
+String TextServerGDNative::get_support_data_filename() {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ godot_string result = interface->get_support_data_filename(data);
+ String name = *(String *)&result;
+ godot_string_destroy(&result);
+ return name;
+}
+
+String TextServerGDNative::get_support_data_info() {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ godot_string result = interface->get_support_data_info(data);
+ String info = *(String *)&result;
+ godot_string_destroy(&result);
+ return info;
+}
+
+bool TextServerGDNative::save_support_data(const String &p_filename) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->save_support_data(data, (godot_string *)&p_filename);
+}
+
+#endif
+
+bool TextServerGDNative::is_locale_right_to_left(const String &p_locale) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->is_locale_right_to_left(data, (godot_string *)&p_locale);
+}
+
+/*************************************************************************/
+/* Font interface */
+/*************************************************************************/
+
+RID TextServerGDNative::create_font_system(const String &p_name, int p_base_size) {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->create_font_system(data, (const godot_string *)&p_name, p_base_size);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+RID TextServerGDNative::create_font_resource(const String &p_filename, int p_base_size) {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->create_font_resource(data, (const godot_string *)&p_filename, p_base_size);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+RID TextServerGDNative::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->create_font_memory(data, p_data, p_size, (godot_string *)&p_type, p_base_size);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+float TextServerGDNative::font_get_height(RID p_font, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_height(data, (godot_rid *)&p_font, p_size);
+}
+
+float TextServerGDNative::font_get_ascent(RID p_font, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_ascent(data, (godot_rid *)&p_font, p_size);
+}
+
+float TextServerGDNative::font_get_descent(RID p_font, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_descent(data, (godot_rid *)&p_font, p_size);
+}
+
+float TextServerGDNative::font_get_underline_position(RID p_font, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_underline_position(data, (godot_rid *)&p_font, p_size);
+}
+
+float TextServerGDNative::font_get_underline_thickness(RID p_font, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_underline_thickness(data, (godot_rid *)&p_font, p_size);
+}
+
+void TextServerGDNative::font_set_antialiased(RID p_font, bool p_antialiased) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_set_antialiased(data, (godot_rid *)&p_font, p_antialiased);
+}
+
+bool TextServerGDNative::font_get_antialiased(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_get_antialiased(data, (godot_rid *)&p_font);
+}
+
+Dictionary TextServerGDNative::font_get_variation_list(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, Dictionary());
+ godot_dictionary result = interface->font_get_variation_list(data, (godot_rid *)&p_font);
+ Dictionary info = *(Dictionary *)&result;
+ godot_dictionary_destroy(&result);
+
+ return info;
+}
+
+void TextServerGDNative::font_set_variation(RID p_font, const String &p_name, double p_value) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_set_variation(data, (godot_rid *)&p_font, (godot_string *)&p_name, p_value);
+}
+
+double TextServerGDNative::font_get_variation(RID p_font, const String &p_name) const {
+ return interface->font_get_variation(data, (godot_rid *)&p_font, (godot_string *)&p_name);
+}
+
+void TextServerGDNative::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_set_hinting(data, (godot_rid *)&p_font, (godot_int)p_hinting);
+}
+
+TextServer::Hinting TextServerGDNative::font_get_hinting(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, TextServer::HINTING_NONE);
+ return (TextServer::Hinting)interface->font_get_hinting(data, (godot_rid *)&p_font);
+}
+
+Dictionary TextServerGDNative::font_get_feature_list(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, Dictionary());
+ godot_dictionary result = interface->font_get_feature_list(data, (godot_rid *)&p_font);
+ Dictionary info = *(Dictionary *)&result;
+ godot_dictionary_destroy(&result);
+
+ return info;
+}
+
+void TextServerGDNative::font_set_distance_field_hint(RID p_font, bool p_distance_field) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_set_distance_field_hint(data, (godot_rid *)&p_font, p_distance_field);
+}
+
+bool TextServerGDNative::font_get_distance_field_hint(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_get_distance_field_hint(data, (godot_rid *)&p_font);
+}
+
+void TextServerGDNative::font_set_force_autohinter(RID p_font, bool p_enabeld) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_set_force_autohinter(data, (godot_rid *)&p_font, p_enabeld);
+}
+
+bool TextServerGDNative::font_get_force_autohinter(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_get_force_autohinter(data, (godot_rid *)&p_font);
+}
+
+bool TextServerGDNative::font_has_char(RID p_font, char32_t p_char) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_has_char(data, (godot_rid *)&p_font, p_char);
+}
+
+String TextServerGDNative::font_get_supported_chars(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ godot_string result = interface->font_get_supported_chars(data, (godot_rid *)&p_font);
+ String ret = *(String *)&result;
+ godot_string_destroy(&result);
+ return ret;
+}
+
+bool TextServerGDNative::font_has_outline(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_has_outline(data, (godot_rid *)&p_font);
+}
+
+float TextServerGDNative::font_get_base_size(RID p_font) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->font_get_base_size(data, (godot_rid *)&p_font);
+}
+
+bool TextServerGDNative::font_is_language_supported(RID p_font, const String &p_language) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_is_language_supported(data, (godot_rid *)&p_font, (godot_string *)&p_language);
+}
+
+void TextServerGDNative::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) {
+ ERR_FAIL_COND(interface == nullptr);
+ return interface->font_set_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language, p_supported);
+}
+
+bool TextServerGDNative::font_get_language_support_override(RID p_font, const String &p_language) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_get_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language);
+}
+
+void TextServerGDNative::font_remove_language_support_override(RID p_font, const String &p_language) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_remove_language_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_language);
+}
+
+Vector<String> TextServerGDNative::font_get_language_support_overrides(RID p_font) {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<String>());
+ godot_packed_string_array result = interface->font_get_language_support_overrides(data, (godot_rid *)&p_font);
+ Vector<String> ret = *(Vector<String> *)&result;
+ godot_packed_string_array_destroy(&result);
+ return ret;
+}
+
+bool TextServerGDNative::font_is_script_supported(RID p_font, const String &p_script) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_is_script_supported(data, (godot_rid *)&p_font, (godot_string *)&p_script);
+}
+
+void TextServerGDNative::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) {
+ ERR_FAIL_COND(interface == nullptr);
+ return interface->font_set_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script, p_supported);
+}
+
+bool TextServerGDNative::font_get_script_support_override(RID p_font, const String &p_script) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->font_get_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script);
+}
+
+void TextServerGDNative::font_remove_script_support_override(RID p_font, const String &p_script) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->font_remove_script_support_override(data, (godot_rid *)&p_font, (godot_string *)&p_script);
+}
+
+Vector<String> TextServerGDNative::font_get_script_support_overrides(RID p_font) {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<String>());
+ godot_packed_string_array result = interface->font_get_script_support_overrides(data, (godot_rid *)&p_font);
+ Vector<String> ret = *(Vector<String> *)&result;
+ godot_packed_string_array_destroy(&result);
+ return ret;
+}
+
+uint32_t TextServerGDNative::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0);
+ return interface->font_get_glyph_index(data, (godot_rid *)&p_font, p_char, p_variation_selector);
+}
+
+Vector2 TextServerGDNative::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector2());
+ godot_vector2 result = interface->font_get_glyph_advance(data, (godot_rid *)&p_font, p_index, p_size);
+ Vector2 advance = *(Vector2 *)&result;
+ return advance;
+}
+
+Vector2 TextServerGDNative::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector2());
+ godot_vector2 result = interface->font_get_glyph_kerning(data, (godot_rid *)&p_font, p_index_a, p_index_b, p_size);
+ Vector2 kerning = *(Vector2 *)&result;
+ return kerning;
+}
+
+Vector2 TextServerGDNative::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector2());
+ godot_vector2 result = interface->font_draw_glyph(data, (godot_rid *)&p_font, (godot_rid *)&p_canvas, p_size, (const godot_vector2 *)&p_pos, p_index, (const godot_color *)&p_color);
+ Vector2 advance = *(Vector2 *)&result;
+ return advance;
+}
+
+Vector2 TextServerGDNative::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector2());
+ godot_vector2 result = interface->font_draw_glyph_outline(data, (godot_rid *)&p_font, (godot_rid *)&p_canvas, p_size, p_outline_size, (const godot_vector2 *)&p_pos, p_index, (const godot_color *)&p_color);
+ Vector2 advance = *(Vector2 *)&result;
+ return advance;
+}
+
+float TextServerGDNative::font_get_oversampling() const {
+ ERR_FAIL_COND_V(interface == nullptr, 1.f);
+ return interface->font_get_oversampling(data);
+}
+
+void TextServerGDNative::font_set_oversampling(float p_oversampling) {
+ ERR_FAIL_COND(interface == nullptr);
+ return interface->font_set_oversampling(data, p_oversampling);
+}
+
+Vector<String> TextServerGDNative::get_system_fonts() const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<String>());
+ godot_packed_string_array result = interface->get_system_fonts(data);
+ Vector<String> fonts = *(Vector<String> *)&result;
+ godot_packed_string_array_destroy(&result);
+ return fonts;
+}
+
+/*************************************************************************/
+/* Shaped text buffer interface */
+/*************************************************************************/
+
+RID TextServerGDNative::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->create_shaped_text(data, (godot_int)p_direction, (godot_int)p_orientation);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+void TextServerGDNative::shaped_text_clear(RID p_shaped) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_clear(data, (godot_rid *)&p_shaped);
+}
+
+void TextServerGDNative::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_set_direction(data, (godot_rid *)&p_shaped, (godot_int)p_direction);
+}
+
+TextServer::Direction TextServerGDNative::shaped_text_get_direction(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, TextServer::DIRECTION_LTR);
+ return (TextServer::Direction)interface->shaped_text_get_direction(data, (godot_rid *)&p_shaped);
+}
+
+void TextServerGDNative::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_set_orientation(data, (godot_rid *)&p_shaped, (godot_int)p_orientation);
+}
+
+TextServer::Orientation TextServerGDNative::shaped_text_get_orientation(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, TextServer::ORIENTATION_HORIZONTAL);
+ return (TextServer::Orientation)interface->shaped_text_get_orientation(data, (godot_rid *)&p_shaped);
+}
+
+void TextServerGDNative::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_set_bidi_override(data, (godot_rid *)&p_shaped, (const godot_packed_vector2i_array *)&p_override);
+}
+
+void TextServerGDNative::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_set_preserve_invalid(data, (godot_rid *)&p_shaped, p_enabled);
+}
+
+bool TextServerGDNative::shaped_text_get_preserve_invalid(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return (TextServer::Orientation)interface->shaped_text_get_preserve_invalid(data, (godot_rid *)&p_shaped);
+}
+
+void TextServerGDNative::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) {
+ ERR_FAIL_COND(interface == nullptr);
+ interface->shaped_text_set_preserve_control(data, (godot_rid *)&p_shaped, p_enabled);
+}
+
+bool TextServerGDNative::shaped_text_get_preserve_control(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return (TextServer::Orientation)interface->shaped_text_get_preserve_control(data, (godot_rid *)&p_shaped);
+}
+
+bool TextServerGDNative::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_add_string(data, (godot_rid *)&p_shaped, (const godot_string *)&p_text, (const godot_rid **)p_fonts.ptr(), p_size, (const godot_dictionary *)&p_opentype_features, (const godot_string *)&p_language);
+}
+
+bool TextServerGDNative::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_add_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align, p_length);
+}
+
+bool TextServerGDNative::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_resize_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align);
+}
+
+RID TextServerGDNative::shaped_text_substr(RID p_shaped, int p_start, int p_length) const {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->shaped_text_substr(data, (godot_rid *)&p_shaped, (godot_int)p_start, (godot_int)p_length);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+RID TextServerGDNative::shaped_text_get_parent(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, RID());
+ godot_rid result = interface->shaped_text_get_parent(data, (godot_rid *)&p_shaped);
+ RID rid = *(RID *)&result;
+ return rid;
+}
+
+float TextServerGDNative::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t p_jst_flags) {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_fit_to_width(data, (godot_rid *)&p_shaped, p_width, p_jst_flags);
+}
+
+float TextServerGDNative::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_tab_align(data, (godot_rid *)&p_shaped, (godot_packed_float32_array *)&p_tab_stops);
+}
+
+bool TextServerGDNative::shaped_text_shape(RID p_shaped) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_shape(data, (godot_rid *)&p_shaped);
+}
+
+bool TextServerGDNative::shaped_text_update_breaks(RID p_shaped) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_update_breaks(data, (godot_rid *)&p_shaped);
+}
+
+bool TextServerGDNative::shaped_text_update_justification_ops(RID p_shaped) {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_update_justification_ops(data, (godot_rid *)&p_shaped);
+}
+
+bool TextServerGDNative::shaped_text_is_ready(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, false);
+ return interface->shaped_text_is_ready(data, (godot_rid *)&p_shaped);
+}
+
+Vector<TextServer::Glyph> TextServerGDNative::shaped_text_get_glyphs(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<TextServer::Glyph>());
+ godot_packed_glyph_array result = interface->shaped_text_get_glyphs(data, (godot_rid *)&p_shaped);
+ Vector<TextServer::Glyph> glyphs = *(Vector<TextServer::Glyph> *)&result;
+ godot_packed_glyph_array_destroy(&result);
+ return glyphs;
+}
+
+Vector2i TextServerGDNative::shaped_text_get_range(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector2i());
+ godot_vector2i result = interface->shaped_text_get_range(data, (godot_rid *)&p_shaped);
+ Vector2i range = *(Vector2i *)&result;
+ return range;
+}
+
+Vector<TextServer::Glyph> TextServerGDNative::shaped_text_sort_logical(RID p_shaped) {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<TextServer::Glyph>());
+ godot_packed_glyph_array result = interface->shaped_text_sort_logical(data, (godot_rid *)&p_shaped);
+ Vector<TextServer::Glyph> glyphs = *(Vector<TextServer::Glyph> *)&result;
+ godot_packed_glyph_array_destroy(&result);
+ return glyphs;
+}
+
+Vector<Vector2i> TextServerGDNative::shaped_text_get_line_breaks_adv(RID p_shaped, const Vector<float> &p_width, int p_start, bool p_once, uint8_t p_break_flags) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>());
+ if (interface->shaped_text_get_line_breaks_adv != nullptr) {
+ godot_packed_vector2i_array result = interface->shaped_text_get_line_breaks_adv(data, (godot_rid *)&p_shaped, (godot_packed_float32_array *)&p_width, p_start, p_once, p_break_flags);
+ Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result;
+ godot_packed_vector2i_array_destroy(&result);
+ return breaks;
+ } else {
+ return TextServer::shaped_text_get_line_breaks_adv(p_shaped, p_width, p_break_flags);
+ }
+}
+
+Vector<Vector2i> TextServerGDNative::shaped_text_get_line_breaks(RID p_shaped, float p_width, int p_start, uint8_t p_break_flags) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>());
+ if (interface->shaped_text_get_line_breaks != nullptr) {
+ godot_packed_vector2i_array result = interface->shaped_text_get_line_breaks(data, (godot_rid *)&p_shaped, p_width, p_start, p_break_flags);
+ Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result;
+ godot_packed_vector2i_array_destroy(&result);
+ return breaks;
+ } else {
+ return TextServer::shaped_text_get_line_breaks(p_shaped, p_width, p_break_flags);
+ }
+}
+
+Vector<Vector2i> TextServerGDNative::shaped_text_get_word_breaks(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>());
+ if (interface->shaped_text_get_word_breaks != nullptr) {
+ godot_packed_vector2i_array result = interface->shaped_text_get_word_breaks(data, (godot_rid *)&p_shaped);
+ Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result;
+ godot_packed_vector2i_array_destroy(&result);
+ return breaks;
+ } else {
+ return TextServer::shaped_text_get_word_breaks(p_shaped);
+ }
+}
+
+Array TextServerGDNative::shaped_text_get_objects(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, Array());
+ godot_array result = interface->shaped_text_get_objects(data, (godot_rid *)&p_shaped);
+ Array rect = *(Array *)&result;
+ return rect;
+}
+
+Rect2 TextServerGDNative::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const {
+ ERR_FAIL_COND_V(interface == nullptr, Rect2());
+ godot_rect2 result = interface->shaped_text_get_object_rect(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key);
+ Rect2 rect = *(Rect2 *)&result;
+ return rect;
+}
+
+Size2 TextServerGDNative::shaped_text_get_size(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, Size2());
+ godot_vector2 result = interface->shaped_text_get_size(data, (godot_rid *)&p_shaped);
+ Size2 size = *(Size2 *)&result;
+ return size;
+}
+
+float TextServerGDNative::shaped_text_get_ascent(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_get_ascent(data, (godot_rid *)&p_shaped);
+}
+
+float TextServerGDNative::shaped_text_get_descent(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_get_descent(data, (godot_rid *)&p_shaped);
+}
+
+float TextServerGDNative::shaped_text_get_width(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_get_width(data, (godot_rid *)&p_shaped);
+}
+
+float TextServerGDNative::shaped_text_get_underline_position(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_get_underline_position(data, (godot_rid *)&p_shaped);
+}
+
+float TextServerGDNative::shaped_text_get_underline_thickness(RID p_shaped) const {
+ ERR_FAIL_COND_V(interface == nullptr, 0.f);
+ return interface->shaped_text_get_underline_thickness(data, (godot_rid *)&p_shaped);
+}
+
+String TextServerGDNative::format_number(const String &p_string, const String &p_language) const {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ godot_string result = interface->format_number(data, (const godot_string *)&p_string, (const godot_string *)&p_language);
+ if (interface->format_number == nullptr) {
+ return p_string;
+ }
+ String ret = *(String *)&result;
+ godot_string_destroy(&result);
+ return ret;
+}
+
+String TextServerGDNative::parse_number(const String &p_string, const String &p_language) const {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ if (interface->parse_number == nullptr) {
+ return p_string;
+ }
+ godot_string result = interface->parse_number(data, (const godot_string *)&p_string, (const godot_string *)&p_language);
+ String ret = *(String *)&result;
+ godot_string_destroy(&result);
+ return ret;
+}
+
+String TextServerGDNative::percent_sign(const String &p_language) const {
+ ERR_FAIL_COND_V(interface == nullptr, String());
+ if (interface->percent_sign == nullptr) {
+ return "%";
+ }
+ godot_string result = interface->percent_sign(data, (const godot_string *)&p_language);
+ String ret = *(String *)&result;
+ godot_string_destroy(&result);
+ return ret;
+}
+
+TextServer *TextServerGDNative::create_func(Error &r_error, void *p_user_data) {
+ const godot_text_interface_gdnative *interface = (const godot_text_interface_gdnative *)p_user_data;
+ r_error = OK;
+
+ TextServerGDNative *server = memnew(TextServerGDNative());
+ server->interface = interface;
+ server->data = interface->constructor((godot_object *)server);
+
+ return server;
+}
+
+TextServerGDNative::TextServerGDNative() {
+ data = nullptr;
+ interface = nullptr;
+}
+
+TextServerGDNative::~TextServerGDNative() {
+ if (interface != nullptr) {
+ interface->destructor(data);
+ data = nullptr;
+ interface = nullptr;
+ }
+}
+
+/*************************************************************************/
+/* GDNative functions */
+/*************************************************************************/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+static_assert(sizeof(godot_glyph) == sizeof(TextServer::Glyph), "Glyph size mismatch");
+static_assert(sizeof(godot_packed_glyph_array) == sizeof(Vector<TextServer::Glyph>), "Vector<Glyph> size mismatch");
+
+void GDAPI godot_text_register_interface(const godot_text_interface_gdnative *p_interface, const godot_string *p_name, uint32_t p_features) {
+ ERR_FAIL_COND(p_interface->version.major != 1);
+ String name = *(String *)p_name;
+ TextServerManager::register_create_function(name + "(GDNative)", p_features, TextServerGDNative::create_func, (void *)p_interface);
+}
+
+// Glyph
+
+void GDAPI godot_glyph_new(godot_glyph *r_dest) {
+ TextServer::Glyph *dest = (TextServer::Glyph *)r_dest;
+ *dest = TextServer::Glyph();
+}
+
+godot_vector2i GDAPI godot_glyph_get_range(const godot_glyph *p_self) {
+ godot_vector2i dest;
+ Vector2i *d = (Vector2i *)&dest;
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ d->x = self->start;
+ d->y = self->end;
+ return dest;
+}
+
+void GDAPI godot_glyph_set_range(godot_glyph *p_self, const godot_vector2i *p_range) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ const Vector2i *range = (const Vector2i *)p_range;
+ self->start = range->x;
+ self->end = range->y;
+}
+
+godot_int GDAPI godot_glyph_get_count(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->count;
+}
+
+void GDAPI godot_glyph_set_count(godot_glyph *p_self, godot_int p_count) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->count = p_count;
+}
+
+godot_int GDAPI godot_glyph_get_repeat(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->repeat;
+}
+
+void GDAPI godot_glyph_set_repeat(godot_glyph *p_self, godot_int p_repeat) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->repeat = p_repeat;
+}
+
+godot_int GDAPI godot_glyph_get_flags(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->flags;
+}
+
+void GDAPI godot_glyph_set_flags(godot_glyph *p_self, godot_int p_flags) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->flags = p_flags;
+}
+
+godot_vector2 GDAPI godot_glyph_get_offset(const godot_glyph *p_self) {
+ godot_vector2 dest;
+ Vector2 *d = (Vector2 *)&dest;
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ d->x = self->x_off;
+ d->y = self->y_off;
+ return dest;
+}
+
+void GDAPI godot_glyph_set_offset(godot_glyph *p_self, const godot_vector2 *p_offset) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ const Vector2 *offset = (const Vector2 *)p_offset;
+ self->x_off = offset->x;
+ self->y_off = offset->y;
+}
+
+godot_real GDAPI godot_glyph_get_advance(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->advance;
+}
+
+void GDAPI godot_glyph_set_advance(godot_glyph *p_self, godot_real p_advance) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->advance = p_advance;
+}
+
+godot_rid GDAPI godot_glyph_get_font(const godot_glyph *p_self) {
+ godot_rid dest;
+ RID *d = (RID *)&dest;
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ *d = self->font_rid;
+ return dest;
+}
+
+void GDAPI godot_glyph_set_font(godot_glyph *p_self, godot_rid *p_font) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ const RID *font = (const RID *)p_font;
+ self->font_rid = *font;
+}
+
+godot_int GDAPI godot_glyph_get_font_size(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->font_size;
+}
+
+void GDAPI godot_glyph_set_font_size(godot_glyph *p_self, godot_int p_size) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->font_size = p_size;
+}
+
+godot_int GDAPI godot_glyph_get_index(const godot_glyph *p_self) {
+ const TextServer::Glyph *self = (const TextServer::Glyph *)p_self;
+ return self->index;
+}
+
+void GDAPI godot_glyph_set_index(godot_glyph *p_self, godot_int p_index) {
+ TextServer::Glyph *self = (TextServer::Glyph *)p_self;
+ self->index = p_index;
+}
+
+// GlyphArray
+
+void GDAPI godot_packed_glyph_array_new(godot_packed_glyph_array *r_dest) {
+ Vector<TextServer::Glyph> *dest = (Vector<TextServer::Glyph> *)r_dest;
+ memnew_placement(dest, Vector<TextServer::Glyph>);
+}
+
+void GDAPI godot_packed_glyph_array_new_copy(godot_packed_glyph_array *r_dest, const godot_packed_glyph_array *p_src) {
+ Vector<TextServer::Glyph> *dest = (Vector<TextServer::Glyph> *)r_dest;
+ const Vector<TextServer::Glyph> *src = (const Vector<TextServer::Glyph> *)p_src;
+ memnew_placement(dest, Vector<TextServer::Glyph>(*src));
+}
+
+const godot_glyph GDAPI *godot_packed_glyph_array_ptr(const godot_packed_glyph_array *p_self) {
+ const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self;
+ return (const godot_glyph *)self->ptr();
+}
+
+godot_glyph GDAPI *godot_packed_glyph_array_ptrw(godot_packed_glyph_array *p_self) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ return (godot_glyph *)self->ptrw();
+}
+
+void GDAPI godot_packed_glyph_array_append(godot_packed_glyph_array *p_self, const godot_glyph *p_data) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ TextServer::Glyph &s = *(TextServer::Glyph *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_glyph_array_append_array(godot_packed_glyph_array *p_self, const godot_packed_glyph_array *p_array) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ Vector<TextServer::Glyph> *array = (Vector<TextServer::Glyph> *)p_array;
+ self->append_array(*array);
+}
+
+godot_error GDAPI godot_packed_glyph_array_insert(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ TextServer::Glyph &s = *(TextServer::Glyph *)p_data;
+ return (godot_error)self->insert(p_idx, s);
+}
+
+godot_bool GDAPI godot_packed_glyph_array_has(godot_packed_glyph_array *p_self, const godot_glyph *p_value) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ TextServer::Glyph &v = *(TextServer::Glyph *)p_value;
+ return (godot_bool)self->has(v);
+}
+
+void GDAPI godot_packed_glyph_array_sort(godot_packed_glyph_array *p_self) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ self->sort();
+}
+
+void GDAPI godot_packed_glyph_array_invert(godot_packed_glyph_array *p_self) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ self->invert();
+}
+
+void GDAPI godot_packed_glyph_array_push_back(godot_packed_glyph_array *p_self, const godot_glyph *p_data) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ TextServer::Glyph &s = *(TextServer::Glyph *)p_data;
+ self->push_back(s);
+}
+
+void GDAPI godot_packed_glyph_array_remove(godot_packed_glyph_array *p_self, const godot_int p_idx) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ self->remove(p_idx);
+}
+
+void GDAPI godot_packed_glyph_array_resize(godot_packed_glyph_array *p_self, const godot_int p_size) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ self->resize(p_size);
+}
+
+void GDAPI godot_packed_glyph_array_set(godot_packed_glyph_array *p_self, const godot_int p_idx, const godot_glyph *p_data) {
+ Vector<TextServer::Glyph> *self = (Vector<TextServer::Glyph> *)p_self;
+ TextServer::Glyph &s = *(TextServer::Glyph *)p_data;
+ self->set(p_idx, s);
+}
+
+godot_glyph GDAPI godot_packed_glyph_array_get(const godot_packed_glyph_array *p_self, const godot_int p_idx) {
+ const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self;
+ godot_glyph v;
+ TextServer::Glyph *s = (TextServer::Glyph *)&v;
+ *s = self->get(p_idx);
+ return v;
+}
+
+godot_int GDAPI godot_packed_glyph_array_size(const godot_packed_glyph_array *p_self) {
+ const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self;
+ return self->size();
+}
+
+godot_bool GDAPI godot_packed_glyph_array_is_empty(const godot_packed_glyph_array *p_self) {
+ const Vector<TextServer::Glyph> *self = (const Vector<TextServer::Glyph> *)p_self;
+ return self->is_empty();
+}
+
+void GDAPI godot_packed_glyph_array_destroy(godot_packed_glyph_array *p_self) {
+ ((Vector<TextServer::Glyph> *)p_self)->~Vector();
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/modules/gdnative/text/text_server_gdnative.h b/modules/gdnative/text/text_server_gdnative.h
new file mode 100644
index 0000000000..9cbb94217e
--- /dev/null
+++ b/modules/gdnative/text/text_server_gdnative.h
@@ -0,0 +1,187 @@
+/*************************************************************************/
+/* text_server_gdnative.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEXT_SERVER_GDNATIVE_H
+#define TEXT_SERVER_GDNATIVE_H
+
+#include "modules/gdnative/gdnative.h"
+
+#include "servers/text_server.h"
+
+class TextServerGDNative : public TextServer {
+ GDCLASS(TextServerGDNative, TextServer);
+
+ const godot_text_interface_gdnative *interface = nullptr;
+ void *data = nullptr;
+
+protected:
+ static void _bind_methods(){};
+
+public:
+ virtual bool has_feature(Feature p_feature) override;
+ virtual String get_name() const override;
+
+ virtual void free(RID p_rid) override;
+ virtual bool has(RID p_rid) override;
+ virtual bool load_support_data(const String &p_filename) override;
+
+#ifdef TOOLS_ENABLED
+ virtual String get_support_data_filename() override;
+ virtual String get_support_data_info() override;
+ virtual bool save_support_data(const String &p_filename) override;
+#endif
+
+ virtual bool is_locale_right_to_left(const String &p_locale) override;
+
+ /* Font interface */
+ virtual RID create_font_system(const String &p_name, int p_base_size = 16) override;
+ virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override;
+ virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override;
+
+ virtual float font_get_height(RID p_font, int p_size) const override;
+ virtual float font_get_ascent(RID p_font, int p_size) const override;
+ virtual float font_get_descent(RID p_font, int p_size) const override;
+
+ virtual float font_get_underline_position(RID p_font, int p_size) const override;
+ virtual float font_get_underline_thickness(RID p_font, int p_size) const override;
+
+ virtual void font_set_antialiased(RID p_font, bool p_antialiased) override;
+ virtual bool font_get_antialiased(RID p_font) const override;
+
+ virtual Dictionary font_get_feature_list(RID p_font) const override;
+ virtual Dictionary font_get_variation_list(RID p_font) const override;
+
+ virtual void font_set_variation(RID p_font, const String &p_name, double p_value) override;
+ virtual double font_get_variation(RID p_font, const String &p_name) const override;
+
+ virtual void font_set_hinting(RID p_font, Hinting p_hinting) override;
+ virtual Hinting font_get_hinting(RID p_font) const override;
+
+ virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override;
+ virtual bool font_get_distance_field_hint(RID p_font) const override;
+
+ virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override;
+ virtual bool font_get_force_autohinter(RID p_font) const override;
+
+ virtual bool font_has_char(RID p_font, char32_t p_char) const override;
+ virtual String font_get_supported_chars(RID p_font) const override;
+
+ virtual bool font_has_outline(RID p_font) const override;
+ virtual float font_get_base_size(RID p_font) const override;
+
+ virtual bool font_is_language_supported(RID p_font, const String &p_language) const override;
+ virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override;
+ virtual bool font_get_language_support_override(RID p_font, const String &p_language) override;
+ virtual void font_remove_language_support_override(RID p_font, const String &p_language) override;
+ Vector<String> font_get_language_support_overrides(RID p_font) override;
+
+ virtual bool font_is_script_supported(RID p_font, const String &p_script) const override;
+ virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override;
+ virtual bool font_get_script_support_override(RID p_font, const String &p_script) override;
+ virtual void font_remove_script_support_override(RID p_font, const String &p_script) override;
+ Vector<String> font_get_script_support_overrides(RID p_font) override;
+
+ virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override;
+ virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override;
+ virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override;
+
+ virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+ virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+
+ virtual float font_get_oversampling() const override;
+ virtual void font_set_oversampling(float p_oversampling) override;
+
+ virtual Vector<String> get_system_fonts() const override;
+
+ /* Shaped text buffer interface */
+
+ virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+
+ virtual void shaped_text_clear(RID p_shaped) override;
+
+ virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override;
+ virtual Direction shaped_text_get_direction(RID p_shaped) const override;
+
+ virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override;
+
+ virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+ virtual Orientation shaped_text_get_orientation(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_control(RID p_shaped) const override;
+
+ virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override;
+ virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override;
+ virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override;
+
+ virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override;
+ virtual RID shaped_text_get_parent(RID p_shaped) const override;
+
+ virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override;
+ virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override;
+
+ virtual bool shaped_text_shape(RID p_shaped) override;
+ virtual bool shaped_text_update_breaks(RID p_shaped) override;
+ virtual bool shaped_text_update_justification_ops(RID p_shaped) override;
+
+ virtual bool shaped_text_is_ready(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override;
+
+ virtual Vector2i shaped_text_get_range(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override;
+ virtual Vector<Vector2i> shaped_text_get_line_breaks_adv(RID p_shaped, const Vector<float> &p_width, int p_start = 0, bool p_once = true, uint8_t /*TextBreakFlag*/ p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override;
+ virtual Vector<Vector2i> shaped_text_get_line_breaks(RID p_shaped, float p_width, int p_start = 0, uint8_t p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override;
+ virtual Vector<Vector2i> shaped_text_get_word_breaks(RID p_shaped) const override;
+ virtual Array shaped_text_get_objects(RID p_shaped) const override;
+ virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override;
+
+ virtual Size2 shaped_text_get_size(RID p_shaped) const override;
+ virtual float shaped_text_get_ascent(RID p_shaped) const override;
+ virtual float shaped_text_get_descent(RID p_shaped) const override;
+ virtual float shaped_text_get_width(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_position(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_thickness(RID p_shaped) const override;
+
+ virtual String format_number(const String &p_string, const String &p_language = "") const override;
+ virtual String parse_number(const String &p_string, const String &p_language = "") const override;
+ virtual String percent_sign(const String &p_language = "") const override;
+
+ static TextServer *create_func(Error &r_error, void *p_user_data);
+
+ TextServerGDNative();
+ ~TextServerGDNative();
+};
+
+#endif // TEXT_SERVER_GDNATIVE_H
diff --git a/modules/gdnative/videodecoder/register_types.cpp b/modules/gdnative/videodecoder/register_types.cpp
index c53e8f2c78..394831daeb 100644
--- a/modules/gdnative/videodecoder/register_types.cpp
+++ b/modules/gdnative/videodecoder/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "register_types.h"
-#include "core/class_db.h"
+#include "core/object/class_db.h"
#include "video_stream_gdnative.h"
static Ref<ResourceFormatLoaderVideoStreamGDNative> resource_loader_vsgdnative;
void register_videodecoder_types() {
-
resource_loader_vsgdnative.instance();
ResourceLoader::add_resource_format_loader(resource_loader_vsgdnative, true);
@@ -44,7 +43,6 @@ void register_videodecoder_types() {
}
void unregister_videodecoder_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_vsgdnative);
resource_loader_vsgdnative.unref();
}
diff --git a/modules/gdnative/videodecoder/register_types.h b/modules/gdnative/videodecoder/register_types.h
index b1a83d4071..809225c925 100644
--- a/modules/gdnative/videodecoder/register_types.h
+++ b/modules/gdnative/videodecoder/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.cpp b/modules/gdnative/videodecoder/video_stream_gdnative.cpp
index f7d87595af..18d26a9528 100644
--- a/modules/gdnative/videodecoder/video_stream_gdnative.cpp
+++ b/modules/gdnative/videodecoder/video_stream_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "video_stream_gdnative.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
#include "servers/audio_server.h"
VideoDecoderServer *VideoDecoderServer::instance = nullptr;
@@ -105,7 +105,6 @@ int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
}
void GDAPI godot_videodecoder_register_decoder(const godot_videodecoder_interface_gdnative *p_interface) {
-
decoder_server.register_decoder_interface(p_interface);
}
}
@@ -202,32 +201,24 @@ void VideoStreamPlaybackGDNative::update_texture() {
// ctor and dtor
VideoStreamPlaybackGDNative::VideoStreamPlaybackGDNative() :
- texture(Ref<ImageTexture>(memnew(ImageTexture))),
- playing(false),
- paused(false),
- mix_udata(nullptr),
- mix_callback(nullptr),
- num_channels(-1),
- time(0),
- seek_backward(false),
- mix_rate(0),
- delay_compensation(0),
- pcm(nullptr),
- pcm_write_idx(0),
- samples_decoded(0),
- file(nullptr),
- interface(nullptr),
- data_struct(nullptr) {}
+ texture(Ref<ImageTexture>(memnew(ImageTexture))) {}
VideoStreamPlaybackGDNative::~VideoStreamPlaybackGDNative() {
cleanup();
}
void VideoStreamPlaybackGDNative::cleanup() {
- if (data_struct)
+ if (data_struct) {
interface->destructor(data_struct);
- if (pcm)
+ }
+ if (pcm) {
memfree(pcm);
+ }
+ if (file) {
+ file->close();
+ memdelete(file);
+ file = nullptr;
+ }
pcm = nullptr;
time = 0;
num_channels = -1;
@@ -255,7 +246,6 @@ bool VideoStreamPlaybackGDNative::is_paused() const {
}
void VideoStreamPlaybackGDNative::play() {
-
stop();
playing = true;
@@ -274,8 +264,9 @@ void VideoStreamPlaybackGDNative::stop() {
void VideoStreamPlaybackGDNative::seek(float p_time) {
ERR_FAIL_COND(interface == nullptr);
interface->seek(data_struct, p_time);
- if (p_time < time)
+ if (p_time < time) {
seek_backward = true;
+ }
time = p_time;
// reset audio buffers
memset(pcm, 0, num_channels * AUX_BUFFER_SIZE * sizeof(float));
@@ -297,7 +288,6 @@ float VideoStreamPlaybackGDNative::get_length() const {
}
float VideoStreamPlaybackGDNative::get_playback_position() const {
-
ERR_FAIL_COND_V(interface == nullptr, 0);
return interface->get_playback_position(data_struct);
}
@@ -317,7 +307,6 @@ void VideoStreamPlaybackGDNative::set_audio_track(int p_idx) {
}
void VideoStreamPlaybackGDNative::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
-
mix_udata = p_userdata;
mix_callback = p_callback;
}
@@ -339,27 +328,26 @@ int VideoStreamPlaybackGDNative::get_mix_rate() const {
Ref<VideoStreamPlayback> VideoStreamGDNative::instance_playback() {
Ref<VideoStreamPlaybackGDNative> pb = memnew(VideoStreamPlaybackGDNative);
VideoDecoderGDNative *decoder = decoder_server.get_decoder(file.get_extension().to_lower());
- if (decoder == nullptr)
+ if (decoder == nullptr) {
return nullptr;
+ }
pb->set_interface(decoder->interface);
pb->set_audio_track(audio_track);
- if (pb->open_file(file))
+ if (pb->open_file(file)) {
return pb;
+ }
return nullptr;
}
void VideoStreamGDNative::set_file(const String &p_file) {
-
file = p_file;
}
String VideoStreamGDNative::get_file() {
-
return file;
}
void VideoStreamGDNative::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamGDNative::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamGDNative::get_file);
@@ -367,7 +355,6 @@ void VideoStreamGDNative::_bind_methods() {
}
void VideoStreamGDNative::set_audio_track(int p_track) {
-
audio_track = p_track;
}
@@ -405,7 +392,8 @@ bool ResourceFormatLoaderVideoStreamGDNative::handles_type(const String &p_type)
String ResourceFormatLoaderVideoStreamGDNative::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
- if (VideoDecoderServer::get_instance()->get_extensions().has(el))
+ if (VideoDecoderServer::get_instance()->get_extensions().has(el)) {
return "VideoStreamGDNative";
+ }
return "";
}
diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h
index 092e10a0f5..e64cda6602 100644
--- a/modules/gdnative/videodecoder/video_stream_gdnative.h
+++ b/modules/gdnative/videodecoder/video_stream_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,13 +37,11 @@
#include "scene/resources/video_stream.h"
struct VideoDecoderGDNative {
- const godot_videodecoder_interface_gdnative *interface;
- String plugin_name;
+ const godot_videodecoder_interface_gdnative *interface = nullptr;
+ String plugin_name = "none";
Vector<String> supported_extensions;
- VideoDecoderGDNative() :
- interface(nullptr),
- plugin_name("none") {}
+ VideoDecoderGDNative() {}
VideoDecoderGDNative(const godot_videodecoder_interface_gdnative *p_interface) :
interface(p_interface),
@@ -88,8 +86,9 @@ public:
}
VideoDecoderGDNative *get_decoder(const String &extension) {
- if (extensions.size() == 0 || !extensions.has(extension))
+ if (extensions.size() == 0 || !extensions.has(extension)) {
return nullptr;
+ }
return decoders[extensions[extension]];
}
@@ -107,27 +106,26 @@ public:
};
class VideoStreamPlaybackGDNative : public VideoStreamPlayback {
-
GDCLASS(VideoStreamPlaybackGDNative, VideoStreamPlayback);
Ref<ImageTexture> texture;
- bool playing;
- bool paused;
+ bool playing = false;
+ bool paused = false;
Vector2 texture_size;
- void *mix_udata;
- AudioMixCallback mix_callback;
+ void *mix_udata = nullptr;
+ AudioMixCallback mix_callback = nullptr;
- int num_channels;
- float time;
- bool seek_backward;
- int mix_rate;
- double delay_compensation;
+ int num_channels = -1;
+ float time = 0;
+ bool seek_backward = false;
+ int mix_rate = 0;
+ double delay_compensation = 0;
- float *pcm;
- int pcm_write_idx;
- int samples_decoded;
+ float *pcm = nullptr;
+ int pcm_write_idx = 0;
+ int samples_decoded = 0;
void cleanup();
void update_texture();
@@ -135,10 +133,10 @@ class VideoStreamPlaybackGDNative : public VideoStreamPlayback {
protected:
String file_name;
- FileAccess *file;
+ FileAccess *file = nullptr;
- const godot_videodecoder_interface_gdnative *interface;
- void *data_struct;
+ const godot_videodecoder_interface_gdnative *interface = nullptr;
+ void *data_struct = nullptr;
public:
VideoStreamPlaybackGDNative();
@@ -148,40 +146,39 @@ public:
bool open_file(const String &p_file);
- virtual void stop();
- virtual void play();
+ virtual void stop() override;
+ virtual void play() override;
- virtual bool is_playing() const;
+ virtual bool is_playing() const override;
- virtual void set_paused(bool p_paused);
- virtual bool is_paused() const;
+ virtual void set_paused(bool p_paused) override;
+ virtual bool is_paused() const override;
- virtual void set_loop(bool p_enable);
- virtual bool has_loop() const;
+ virtual void set_loop(bool p_enable) override;
+ virtual bool has_loop() const override;
- virtual float get_length() const;
+ virtual float get_length() const override;
- virtual float get_playback_position() const;
- virtual void seek(float p_time);
+ virtual float get_playback_position() const override;
+ virtual void seek(float p_time) override;
- virtual void set_audio_track(int p_idx);
+ virtual void set_audio_track(int p_idx) override;
//virtual int mix(int16_t* p_buffer,int p_frames)=0;
- virtual Ref<Texture2D> get_texture() const;
- virtual void update(float p_delta);
+ virtual Ref<Texture2D> get_texture() const override;
+ virtual void update(float p_delta) override;
- virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata);
- virtual int get_channels() const;
- virtual int get_mix_rate() const;
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) override;
+ virtual int get_channels() const override;
+ virtual int get_mix_rate() const override;
};
class VideoStreamGDNative : public VideoStream {
-
GDCLASS(VideoStreamGDNative, VideoStream);
String file;
- int audio_track;
+ int audio_track = 0;
protected:
static void
@@ -191,10 +188,10 @@ public:
void set_file(const String &p_file);
String get_file();
- virtual void set_audio_track(int p_track);
- virtual Ref<VideoStreamPlayback> instance_playback();
+ virtual void set_audio_track(int p_track) override;
+ virtual Ref<VideoStreamPlayback> instance_playback() override;
- VideoStreamGDNative() { audio_track = 0; }
+ VideoStreamGDNative() {}
};
class ResourceFormatLoaderVideoStreamGDNative : public ResourceFormatLoader {
diff --git a/modules/gdnative/xr/register_types.cpp b/modules/gdnative/xr/register_types.cpp
index da3a7dc4b8..b60a04f470 100644
--- a/modules/gdnative/xr/register_types.cpp
+++ b/modules/gdnative/xr/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/xr/register_types.h b/modules/gdnative/xr/register_types.h
index 2501d28651..4e7469abe9 100644
--- a/modules/gdnative/xr/register_types.h
+++ b/modules/gdnative/xr/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnative/xr/xr_interface_gdnative.cpp b/modules/gdnative/xr/xr_interface_gdnative.cpp
index d65089a123..d4fd2876b5 100644
--- a/modules/gdnative/xr/xr_interface_gdnative.cpp
+++ b/modules/gdnative/xr/xr_interface_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -80,7 +80,6 @@ void XRInterfaceGDNative::set_interface(const godot_xr_interface_gdnative *p_int
}
StringName XRInterfaceGDNative::get_name() const {
-
ERR_FAIL_COND_V(interface == nullptr, StringName());
godot_string result = interface->get_name(data);
@@ -103,21 +102,18 @@ int XRInterfaceGDNative::get_capabilities() const {
}
bool XRInterfaceGDNative::get_anchor_detection_is_enabled() const {
-
ERR_FAIL_COND_V(interface == nullptr, false);
return interface->get_anchor_detection_is_enabled(data);
}
void XRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) {
-
ERR_FAIL_COND(interface == nullptr);
interface->set_anchor_detection_is_enabled(data, p_enable);
}
int XRInterfaceGDNative::get_camera_feed_id() {
-
ERR_FAIL_COND_V(interface == nullptr, 0);
return (unsigned int)interface->get_camera_feed_id(data);
@@ -134,7 +130,6 @@ bool XRInterfaceGDNative::is_stereo() {
}
bool XRInterfaceGDNative::is_initialized() const {
-
ERR_FAIL_COND_V(interface == nullptr, false);
return interface->is_initialized(data);
@@ -170,7 +165,6 @@ void XRInterfaceGDNative::uninitialize() {
}
Size2 XRInterfaceGDNative::get_render_targetsize() {
-
ERR_FAIL_COND_V(interface == nullptr, Size2());
godot_vector2 result = interface->get_render_targetsize(data);
@@ -202,14 +196,12 @@ CameraMatrix XRInterfaceGDNative::get_projection_for_eye(XRInterface::Eyes p_eye
}
unsigned int XRInterfaceGDNative::get_external_texture_for_eye(XRInterface::Eyes p_eye) {
-
ERR_FAIL_COND_V(interface == nullptr, 0);
return (unsigned int)interface->get_external_texture_for_eye(data, (godot_int)p_eye);
}
void XRInterfaceGDNative::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) {
-
ERR_FAIL_COND(interface == nullptr);
interface->commit_for_eye(data, (godot_int)p_eye, (godot_rid *)&p_render_target, (godot_rect2 *)&p_screen_rect);
@@ -310,12 +302,12 @@ godot_int GDAPI godot_xr_add_controller(char *p_device_name, godot_int p_hand, g
ERR_FAIL_NULL_V(input, 0);
XRPositionalTracker *new_tracker = memnew(XRPositionalTracker);
- new_tracker->set_name(p_device_name);
- new_tracker->set_type(XRServer::TRACKER_CONTROLLER);
+ new_tracker->set_tracker_name(p_device_name);
+ new_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER);
if (p_hand == 1) {
- new_tracker->set_hand(XRPositionalTracker::TRACKER_LEFT_HAND);
+ new_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_LEFT);
} else if (p_hand == 2) {
- new_tracker->set_hand(XRPositionalTracker::TRACKER_RIGHT_HAND);
+ new_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_RIGHT);
}
// also register as joystick...
diff --git a/modules/gdnative/xr/xr_interface_gdnative.h b/modules/gdnative/xr/xr_interface_gdnative.h
index 64f1282a7e..84bd8fc731 100644
--- a/modules/gdnative/xr/xr_interface_gdnative.h
+++ b/modules/gdnative/xr/xr_interface_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -58,34 +58,34 @@ public:
void set_interface(const godot_xr_interface_gdnative *p_interface);
- virtual StringName get_name() const;
- virtual int get_capabilities() const;
+ virtual StringName get_name() const override;
+ virtual int get_capabilities() const override;
- virtual bool is_initialized() const;
- virtual bool initialize();
- virtual void uninitialize();
+ virtual bool is_initialized() const override;
+ virtual bool initialize() override;
+ virtual void uninitialize() override;
/** 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();
+ virtual bool get_anchor_detection_is_enabled() const override;
+ virtual void set_anchor_detection_is_enabled(bool p_enable) override;
+ virtual int get_camera_feed_id() override;
/** rendering and internal **/
- virtual Size2 get_render_targetsize();
- virtual bool is_stereo();
- virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform);
+ virtual Size2 get_render_targetsize() override;
+ virtual bool is_stereo() override;
+ virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override;
// we expose a Vector<float> version of this function to GDNative
Vector<float> _get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far);
// and a CameraMatrix version to XRServer
- virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far);
+ virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override;
- virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye);
- virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect);
+ virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override;
+ virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override;
- virtual void process();
- virtual void notification(int p_what);
+ virtual void process() override;
+ virtual void notification(int p_what) override;
};
#endif // XR_INTERFACE_GDNATIVE_H
diff --git a/modules/gdnavigation/SCsub b/modules/gdnavigation/SCsub
index 877d601c6a..22b5509b32 100644
--- a/modules/gdnavigation/SCsub
+++ b/modules/gdnavigation/SCsub
@@ -5,6 +5,10 @@ Import("env_modules")
env_navigation = env_modules.Clone()
+# Thirdparty source files
+
+thirdparty_obj = []
+
# Recast Thirdparty source files
if env["builtin_recast"]:
thirdparty_dir = "#thirdparty/recastnavigation/Recast/"
@@ -23,28 +27,37 @@ if env["builtin_recast"]:
]
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
- env_navigation.Prepend(CPPPATH=[thirdparty_dir + "/Include"])
+ env_navigation.Prepend(CPPPATH=[thirdparty_dir + "Include"])
env_thirdparty = env_navigation.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
-
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
# RVO Thirdparty source files
if env["builtin_rvo2"]:
- thirdparty_dir = "#thirdparty/rvo2"
+ thirdparty_dir = "#thirdparty/rvo2/"
thirdparty_sources = [
- "/src/Agent.cpp",
- "/src/KdTree.cpp",
+ "Agent.cpp",
+ "KdTree.cpp",
]
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
- env_navigation.Prepend(CPPPATH=[thirdparty_dir + "/src"])
+ env_navigation.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_navigation.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+
+
+env.modules_sources += thirdparty_obj
# Godot source files
-env_navigation.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_navigation.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/gdnavigation/gd_navigation_server.cpp b/modules/gdnavigation/gd_navigation_server.cpp
index 278c27ae22..4f61ad5040 100644
--- a/modules/gdnavigation/gd_navigation_server.cpp
+++ b/modules/gdnavigation/gd_navigation_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -114,8 +114,7 @@
void GdNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3)
GdNavigationServer::GdNavigationServer() :
- NavigationServer3D(),
- active(true) {
+ NavigationServer3D() {
}
GdNavigationServer::~GdNavigationServer() {
@@ -250,9 +249,9 @@ COMMAND_2(region_set_map, RID, p_region, RID, p_map) {
ERR_FAIL_COND(region == nullptr);
if (region->get_map() != nullptr) {
-
- if (region->get_map()->get_self() == p_map)
+ if (region->get_map()->get_self() == p_map) {
return; // Pointless
+ }
region->get_map()->remove_region(region);
region->set_map(nullptr);
@@ -305,8 +304,9 @@ COMMAND_2(agent_set_map, RID, p_agent, RID, p_map) {
ERR_FAIL_COND(agent == nullptr);
if (agent->get_map()) {
- if (agent->get_map()->get_self() == p_map)
+ if (agent->get_map()->get_self() == p_map) {
return; // Pointless
+ }
agent->get_map()->remove_agent(agent);
}
diff --git a/modules/gdnavigation/gd_navigation_server.h b/modules/gdnavigation/gd_navigation_server.h
index 01d1a4fba9..92f4ccfdd5 100644
--- a/modules/gdnavigation/gd_navigation_server.h
+++ b/modules/gdnavigation/gd_navigation_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef GD_NAVIGATION_SERVER_H
#define GD_NAVIGATION_SERVER_H
-#include "core/rid.h"
-#include "core/rid_owner.h"
+#include "core/templates/rid.h"
+#include "core/templates/rid_owner.h"
#include "servers/navigation_server_3d.h"
#include "nav_map.h"
@@ -78,7 +78,7 @@ class GdNavigationServer : public NavigationServer3D {
mutable RID_PtrOwner<NavRegion> region_owner;
mutable RID_PtrOwner<RvoAgent> agent_owner;
- bool active;
+ bool active = true;
Vector<NavMap *> active_maps;
public:
diff --git a/modules/gdnavigation/nav_map.cpp b/modules/gdnavigation/nav_map.cpp
index 7e6a3f7a26..2646a4cc0c 100644
--- a/modules/gdnavigation/nav_map.cpp
+++ b/modules/gdnavigation/nav_map.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,6 +33,7 @@
#include "core/os/threaded_array_processor.h"
#include "nav_region.h"
#include "rvo_agent.h"
+
#include <algorithm>
/**
@@ -41,16 +42,6 @@
#define USE_ENTRY_POINT
-NavMap::NavMap() :
- up(0, 1, 0),
- cell_size(0.3),
- edge_connection_margin(5.0),
- regenerate_polygons(true),
- regenerate_links(true),
- agents_dirty(false),
- deltatime(0.0),
- map_update_id(0) {}
-
void NavMap::set_up(Vector3 p_up) {
up = p_up;
regenerate_polygons = true;
@@ -80,7 +71,6 @@ gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
}
Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p_optimize) const {
-
const gd::Polygon *begin_poly = nullptr;
const gd::Polygon *end_poly = nullptr;
Vector3 begin_point;
@@ -94,7 +84,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
// For each point cast a face and check the distance between the origin/destination
for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
-
Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
Vector3 spoint = f.get_closest_point_to(p_origin);
float dpoint = spoint.distance_to(p_origin);
@@ -120,7 +109,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
}
if (begin_poly == end_poly) {
-
Vector<Vector3> path;
path.resize(2);
path.write[0] = begin_point;
@@ -151,15 +139,15 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
bool is_reachable = true;
while (found_route == false) {
-
{
// Takes the current least_cost_poly neighbors and compute the traveled_distance of each
for (size_t i = 0; i < navigation_polys[least_cost_id].poly->edges.size(); i++) {
gd::NavigationPoly *least_cost_poly = &navigation_polys[least_cost_id];
const gd::Edge &edge = least_cost_poly->poly->edges[i];
- if (!edge.other_polygon)
+ if (!edge.other_polygon) {
continue;
+ }
#ifdef USE_ENTRY_POINT
Vector3 edge_line[2] = {
@@ -167,7 +155,7 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
least_cost_poly->poly->points[(i + 1) % least_cost_poly->poly->points.size()].pos
};
- const Vector3 new_entry = Geometry::get_closest_point_to_segment(least_cost_poly->entry, edge_line);
+ const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly->entry, edge_line);
const float new_distance = least_cost_poly->entry.distance_to(new_entry) + least_cost_poly->traveled_distance;
#else
const float new_distance = least_cost_poly->poly->center.distance_to(edge.other_polygon->center) + least_cost_poly->traveled_distance;
@@ -181,7 +169,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
if (it != navigation_polys.end()) {
// Oh this was visited already, can we win the cost?
if (it->traveled_distance > new_distance) {
-
it->prev_navigation_poly_id = least_cost_id;
it->back_navigation_edge = edge.other_edge;
it->traveled_distance = new_distance;
@@ -283,10 +270,8 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
}
if (found_route) {
-
Vector<Vector3> path;
if (p_optimize) {
-
// String pulling
gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
@@ -300,7 +285,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
path.push_back(end_point);
while (p) {
-
Vector3 left;
Vector3 right;
@@ -315,7 +299,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
left = p->poly->points[prev].pos;
right = p->poly->points[prev_n].pos;
- //if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5).dot(up) < 0){
if (p->poly->clockwise) {
SWAP(left, right);
}
@@ -329,7 +312,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
left_poly = p;
portal_left = left;
} else {
-
clip_path(navigation_polys, path, apex_poly, portal_right, right_poly);
apex_point = portal_right;
@@ -349,7 +331,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
right_poly = p;
portal_right = right;
} else {
-
clip_path(navigation_polys, path, apex_poly, portal_left, left_poly);
apex_point = portal_left;
@@ -362,15 +343,17 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
}
}
- if (p->prev_navigation_poly_id != -1)
+ if (p->prev_navigation_poly_id != -1) {
p = &navigation_polys[p->prev_navigation_poly_id];
- else
+ } else {
// The end
p = nullptr;
+ }
}
- if (path[path.size() - 1] != begin_point)
+ if (path[path.size() - 1] != begin_point) {
path.push_back(begin_point);
+ }
path.invert();
@@ -380,7 +363,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
// Add mid points
int np_id = least_cost_id;
while (np_id != -1) {
-
#ifdef USE_ENTRY_POINT
Vector3 point = navigation_polys[np_id].entry;
#else
@@ -402,7 +384,6 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p
}
Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
-
bool use_collision = p_use_collision;
Vector3 closest_point;
real_t closest_point_d = 1e20;
@@ -413,7 +394,6 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector
// For each point cast a face and check the distance to the segment
for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
-
const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
Vector3 inters;
if (f.intersects_segment(p_from, p_to, &inters)) {
@@ -423,7 +403,6 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector
use_collision = true;
closest_point_d = d;
} else if (closest_point_d > d) {
-
closest_point = inters;
closest_point_d = d;
}
@@ -431,12 +410,10 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector
}
if (use_collision == false) {
-
for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
-
Vector3 a, b;
- Geometry::get_closest_points_between_segments(
+ Geometry3D::get_closest_points_between_segments(
p_from,
p_to,
p.points[point_id].pos,
@@ -446,7 +423,6 @@ Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector
const real_t d = a.distance_to(b);
if (d < closest_point_d) {
-
closest_point_d = d;
closest_point = b;
}
@@ -469,7 +445,6 @@ Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
// For each point cast a face and check the distance to the point
for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
-
const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
const Vector3 inters = f.get_closest_point_to(p_point);
const real_t d = inters.distance_to(p_point);
@@ -496,7 +471,6 @@ Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
// For each point cast a face and check the distance to the point
for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
-
const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
const Vector3 inters = f.get_closest_point_to(p_point);
const real_t d = inters.distance_to(p_point);
@@ -524,7 +498,6 @@ RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
// For each point cast a face and check the distance to the point
for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
-
const Face3 f(p.points[point_id - 2].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
const Vector3 inters = f.get_closest_point_to(p_point);
const real_t d = inters.distance_to(p_point);
@@ -588,7 +561,6 @@ void NavMap::remove_agent_as_controlled(RvoAgent *agent) {
}
void NavMap::sync() {
-
if (regenerate_polygons) {
for (size_t r(0); r < regions.size(); r++) {
regions[r]->scratch_polygons();
@@ -735,14 +707,15 @@ void NavMap::sync() {
}
if (regenerate_links) {
- map_update_id = map_update_id + 1 % 9999999;
+ map_update_id = (map_update_id + 1) % 9999999;
}
if (agents_dirty) {
std::vector<RVO::Agent *> raw_agents;
raw_agents.reserve(agents.size());
- for (size_t i(0); i < agents.size(); i++)
+ for (size_t i(0); i < agents.size(); i++) {
raw_agents.push_back(agents[i]->get_agent());
+ }
rvo.buildAgentTree(raw_agents);
}
@@ -776,17 +749,18 @@ void NavMap::dispatch_callbacks() {
void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly) const {
Vector3 from = path[path.size() - 1];
- if (from.distance_to(p_to_point) < CMP_EPSILON)
+ if (from.distance_to(p_to_point) < CMP_EPSILON) {
return;
+ }
Plane cut_plane;
cut_plane.normal = (from - p_to_point).cross(up);
- if (cut_plane.normal == Vector3())
+ if (cut_plane.normal == Vector3()) {
return;
+ }
cut_plane.normal.normalize();
cut_plane.d = cut_plane.normal.dot(from);
while (from_poly != p_to_poly) {
-
int back_nav_edge = from_poly->back_navigation_edge;
Vector3 a = from_poly->poly->points[back_nav_edge].pos;
Vector3 b = from_poly->poly->points[(back_nav_edge + 1) % from_poly->poly->points.size()].pos;
@@ -795,7 +769,6 @@ void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys
from_poly = &p_navigation_polys[from_poly->prev_navigation_poly_id];
if (a.distance_to(b) > CMP_EPSILON) {
-
Vector3 inters;
if (cut_plane.intersects_segment(a, b, &inters)) {
if (inters.distance_to(p_to_point) > CMP_EPSILON && inters.distance_to(path[path.size() - 1]) > CMP_EPSILON) {
diff --git a/modules/gdnavigation/nav_map.h b/modules/gdnavigation/nav_map.h
index 4543f00926..bffc1fbc1a 100644
--- a/modules/gdnavigation/nav_map.h
+++ b/modules/gdnavigation/nav_map.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,19 +46,18 @@ class RvoAgent;
class NavRegion;
class NavMap : public NavRid {
-
/// Map Up
- Vector3 up;
+ Vector3 up = Vector3(0, 1, 0);
/// To find the polygons edges the vertices are displaced in a grid where
/// each cell has the following cell_size.
- real_t cell_size;
+ real_t cell_size = 0.3;
/// This value is used to detect the near edges to connect.
- real_t edge_connection_margin;
+ real_t edge_connection_margin = 5.0;
- bool regenerate_polygons;
- bool regenerate_links;
+ bool regenerate_polygons = true;
+ bool regenerate_links = true;
std::vector<NavRegion *> regions;
@@ -69,7 +68,7 @@ class NavMap : public NavRid {
RVO::KdTree rvo;
/// Is agent array modified?
- bool agents_dirty;
+ bool agents_dirty = false;
/// All the Agents (even the controlled one)
std::vector<RvoAgent *> agents;
@@ -78,13 +77,13 @@ class NavMap : public NavRid {
std::vector<RvoAgent *> controlled_agents;
/// Physics delta time
- real_t deltatime;
+ real_t deltatime = 0.0;
/// Change the id each time the map is updated.
- uint32_t map_update_id;
+ uint32_t map_update_id = 0;
public:
- NavMap();
+ NavMap() {}
void set_up(Vector3 p_up);
Vector3 get_up() const {
diff --git a/modules/gdnavigation/nav_region.cpp b/modules/gdnavigation/nav_region.cpp
index b91376f761..383b0f15a6 100644
--- a/modules/gdnavigation/nav_region.cpp
+++ b/modules/gdnavigation/nav_region.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,11 +36,6 @@
@author AndreaCatania
*/
-NavRegion::NavRegion() :
- map(nullptr),
- polygons_dirty(true) {
-}
-
void NavRegion::set_map(NavMap *p_map) {
map = p_map;
polygons_dirty = true;
@@ -75,13 +70,15 @@ void NavRegion::update_polygons() {
return;
}
- if (mesh.is_null())
+ if (mesh.is_null()) {
return;
+ }
Vector<Vector3> vertices = mesh->get_vertices();
int len = vertices.size();
- if (len == 0)
+ if (len == 0) {
return;
+ }
const Vector3 *vertices_r = vertices.ptr();
@@ -89,7 +86,6 @@ void NavRegion::update_polygons() {
// Build
for (size_t i(0); i < polygons.size(); i++) {
-
gd::Polygon &p = polygons[i];
p.owner = this;
@@ -103,7 +99,6 @@ void NavRegion::update_polygons() {
float sum(0);
for (int j(0); j < mesh_poly.size(); j++) {
-
int idx = indices[j];
if (idx < 0 || idx >= len) {
valid = false;
diff --git a/modules/gdnavigation/nav_region.h b/modules/gdnavigation/nav_region.h
index f35ee4bea0..954780033b 100644
--- a/modules/gdnavigation/nav_region.h
+++ b/modules/gdnavigation/nav_region.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,17 +45,17 @@ class NavMap;
class NavRegion;
class NavRegion : public NavRid {
- NavMap *map;
+ NavMap *map = nullptr;
Transform transform;
Ref<NavigationMesh> mesh;
- bool polygons_dirty;
+ bool polygons_dirty = true;
/// Cache
std::vector<gd::Polygon> polygons;
public:
- NavRegion();
+ NavRegion() {}
void scratch_polygons() {
polygons_dirty = true;
diff --git a/modules/gdnavigation/nav_rid.h b/modules/gdnavigation/nav_rid.h
index c119ecc5e0..a0a60a3643 100644
--- a/modules/gdnavigation/nav_rid.h
+++ b/modules/gdnavigation/nav_rid.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef NAV_RID_H
#define NAV_RID_H
-#include "core/rid.h"
+#include "core/templates/rid.h"
/**
@author AndreaCatania
diff --git a/modules/gdnavigation/nav_utils.h b/modules/gdnavigation/nav_utils.h
index 3401284c31..d1d1687a1f 100644
--- a/modules/gdnavigation/nav_utils.h
+++ b/modules/gdnavigation/nav_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,6 +32,7 @@
#define NAV_UTILS_H
#include "core/math/vector3.h"
+
#include <vector>
/**
@@ -44,7 +45,6 @@ namespace gd {
struct Polygon;
union PointKey {
-
struct {
int64_t x : 21;
int64_t y : 22;
@@ -56,7 +56,6 @@ union PointKey {
};
struct EdgeKey {
-
PointKey a;
PointKey b;
@@ -80,19 +79,15 @@ struct Point {
struct Edge {
/// This edge ID
- int this_edge;
+ int this_edge = -1;
/// Other Polygon
- Polygon *other_polygon;
+ Polygon *other_polygon = nullptr;
/// The other `Polygon` at this edge id has this `Polygon`.
- int other_edge;
+ int other_edge = -1;
- Edge() {
- this_edge = -1;
- other_polygon = nullptr;
- other_edge = -1;
- }
+ Edge() {}
};
struct Polygon {
@@ -112,40 +107,29 @@ struct Polygon {
};
struct Connection {
+ Polygon *A = nullptr;
+ int A_edge = -1;
+ Polygon *B = nullptr;
+ int B_edge = -1;
- Polygon *A;
- int A_edge;
- Polygon *B;
- int B_edge;
-
- Connection() {
- A = nullptr;
- B = nullptr;
- A_edge = -1;
- B_edge = -1;
- }
+ Connection() {}
};
struct NavigationPoly {
- uint32_t self_id;
+ uint32_t self_id = 0;
/// This poly.
const Polygon *poly;
/// The previous navigation poly (id in the `navigation_poly` array).
- int prev_navigation_poly_id;
+ int prev_navigation_poly_id = -1;
/// The edge id in this `Poly` to reach the `prev_navigation_poly_id`.
- uint32_t back_navigation_edge;
+ uint32_t back_navigation_edge = 0;
/// The entry location of this poly.
Vector3 entry;
/// The distance to the destination.
- float traveled_distance;
+ float traveled_distance = 0.0;
NavigationPoly(const Polygon *p_poly) :
- self_id(0),
- poly(p_poly),
- prev_navigation_poly_id(-1),
- back_navigation_edge(0),
- traveled_distance(0.0) {
- }
+ poly(p_poly) {}
bool operator==(const NavigationPoly &other) const {
return this->poly == other.poly;
diff --git a/modules/gdnavigation/navigation_mesh_editor_plugin.cpp b/modules/gdnavigation/navigation_mesh_editor_plugin.cpp
index abaf73ba6a..aa9248d2a1 100644
--- a/modules/gdnavigation/navigation_mesh_editor_plugin.cpp
+++ b/modules/gdnavigation/navigation_mesh_editor_plugin.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -38,7 +38,6 @@
#include "scene/gui/box_container.h"
void NavigationMeshEditor::_node_removed(Node *p_node) {
-
if (p_node == node) {
node = nullptr;
@@ -47,9 +46,7 @@ void NavigationMeshEditor::_node_removed(Node *p_node) {
}
void NavigationMeshEditor::_notification(int p_option) {
-
if (p_option == NOTIFICATION_ENTER_TREE) {
-
button_bake->set_icon(get_theme_icon("Bake", "EditorIcons"));
button_reset->set_icon(get_theme_icon("Reload", "EditorIcons"));
}
@@ -72,9 +69,9 @@ void NavigationMeshEditor::_bake_pressed() {
}
void NavigationMeshEditor::_clear_pressed() {
-
- if (node)
+ if (node) {
NavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh());
+ }
button_bake->set_pressed(false);
bake_info->set_text("");
@@ -85,7 +82,6 @@ void NavigationMeshEditor::_clear_pressed() {
}
void NavigationMeshEditor::edit(NavigationRegion3D *p_nav_region) {
-
if (p_nav_region == nullptr || node == p_nav_region) {
return;
}
@@ -97,16 +93,17 @@ void NavigationMeshEditor::_bind_methods() {
}
NavigationMeshEditor::NavigationMeshEditor() {
-
bake_hbox = memnew(HBoxContainer);
- button_bake = memnew(ToolButton);
+ button_bake = memnew(Button);
+ button_bake->set_flat(true);
bake_hbox->add_child(button_bake);
button_bake->set_toggle_mode(true);
button_bake->set_text(TTR("Bake NavMesh"));
button_bake->connect("pressed", callable_mp(this, &NavigationMeshEditor::_bake_pressed));
- button_reset = memnew(ToolButton);
+ button_reset = memnew(Button);
+ button_reset->set_flat(true);
bake_hbox->add_child(button_reset);
// No button text, we only use a revert icon which is set when entering the tree.
button_reset->set_tooltip(TTR("Clear the navigation mesh."));
@@ -124,22 +121,18 @@ NavigationMeshEditor::~NavigationMeshEditor() {
}
void NavigationMeshEditorPlugin::edit(Object *p_object) {
-
navigation_mesh_editor->edit(Object::cast_to<NavigationRegion3D>(p_object));
}
bool NavigationMeshEditorPlugin::handles(Object *p_object) const {
-
return p_object->is_class("NavigationRegion3D");
}
void NavigationMeshEditorPlugin::make_visible(bool p_visible) {
-
if (p_visible) {
navigation_mesh_editor->show();
navigation_mesh_editor->bake_hbox->show();
} else {
-
navigation_mesh_editor->hide();
navigation_mesh_editor->bake_hbox->hide();
navigation_mesh_editor->edit(nullptr);
@@ -147,10 +140,9 @@ void NavigationMeshEditorPlugin::make_visible(bool p_visible) {
}
NavigationMeshEditorPlugin::NavigationMeshEditorPlugin(EditorNode *p_node) {
-
editor = p_node;
navigation_mesh_editor = memnew(NavigationMeshEditor);
- editor->get_viewport()->add_child(navigation_mesh_editor);
+ editor->get_main_control()->add_child(navigation_mesh_editor);
add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, navigation_mesh_editor->bake_hbox);
navigation_mesh_editor->hide();
navigation_mesh_editor->bake_hbox->hide();
diff --git a/modules/gdnavigation/navigation_mesh_editor_plugin.h b/modules/gdnavigation/navigation_mesh_editor_plugin.h
index 434981c9e0..c39269865b 100644
--- a/modules/gdnavigation/navigation_mesh_editor_plugin.h
+++ b/modules/gdnavigation/navigation_mesh_editor_plugin.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,8 +46,8 @@ class NavigationMeshEditor : public Control {
AcceptDialog *err_dialog;
HBoxContainer *bake_hbox;
- ToolButton *button_bake;
- ToolButton *button_reset;
+ Button *button_bake;
+ Button *button_reset;
Label *bake_info;
NavigationRegion3D *node;
@@ -67,18 +67,17 @@ public:
};
class NavigationMeshEditorPlugin : public EditorPlugin {
-
GDCLASS(NavigationMeshEditorPlugin, EditorPlugin);
NavigationMeshEditor *navigation_mesh_editor;
EditorNode *editor;
public:
- virtual String get_name() const { return "NavigationMesh"; }
- bool has_main_screen() const { return false; }
- virtual void edit(Object *p_object);
- virtual bool handles(Object *p_object) const;
- virtual void make_visible(bool p_visible);
+ virtual String get_name() const override { return "NavigationMesh"; }
+ bool has_main_screen() const override { return false; }
+ virtual void edit(Object *p_object) override;
+ virtual bool handles(Object *p_object) const override;
+ virtual void make_visible(bool p_visible) override;
NavigationMeshEditorPlugin(EditorNode *p_node);
~NavigationMeshEditorPlugin();
diff --git a/modules/gdnavigation/navigation_mesh_generator.cpp b/modules/gdnavigation/navigation_mesh_generator.cpp
index acb4f0461f..a7d4e79148 100644
--- a/modules/gdnavigation/navigation_mesh_generator.cpp
+++ b/modules/gdnavigation/navigation_mesh_generator.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -74,8 +74,9 @@ void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform
for (int i = 0; i < p_mesh->get_surface_count(); i++) {
current_vertex_count = p_verticies.size() / 3;
- if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
+ if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue;
+ }
int index_count = 0;
if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
@@ -94,7 +95,6 @@ void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform
const Vector3 *vr = mesh_vertices.ptr();
if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
-
Vector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
const int *ir = mesh_indices.ptr();
@@ -139,9 +139,7 @@ void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, cons
}
void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) {
-
if (Object::cast_to<MeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
-
MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_node);
Ref<Mesh> mesh = mesh_instance->get_mesh();
if (mesh.is_valid()) {
@@ -151,10 +149,9 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
#ifdef MODULE_CSG_ENABLED
if (Object::cast_to<CSGShape3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
-
CSGShape3D *csg_shape = Object::cast_to<CSGShape3D>(p_node);
Array meshes = csg_shape->get_meshes();
- if (!meshes.empty()) {
+ if (!meshes.is_empty()) {
Ref<Mesh> mesh = meshes[1];
if (mesh.is_valid()) {
_add_mesh(mesh, p_accumulated_transform * csg_shape->get_transform(), p_verticies, p_indices);
@@ -167,7 +164,6 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
StaticBody3D *static_body = Object::cast_to<StaticBody3D>(p_node);
if (static_body->get_collision_layer() & p_collision_mask) {
-
for (int i = 0; i < p_node->get_child_count(); ++i) {
Node *child = p_node->get_child(i);
if (Object::cast_to<CollisionShape3D>(child)) {
@@ -180,10 +176,10 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
BoxShape3D *box = Object::cast_to<BoxShape3D>(*s);
if (box) {
- Ref<CubeMesh> cube_mesh;
- cube_mesh.instance();
- cube_mesh->set_size(box->get_extents() * 2.0);
- mesh = cube_mesh;
+ Ref<BoxMesh> box_mesh;
+ box_mesh.instance();
+ box_mesh->set_size(box->get_size());
+ mesh = box_mesh;
}
CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s);
@@ -222,7 +218,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
ConvexPolygonShape3D *convex_polygon = Object::cast_to<ConvexPolygonShape3D>(*s);
if (convex_polygon) {
Vector<Vector3> varr = Variant(convex_polygon->get_points());
- Geometry::MeshData md;
+ Geometry3D::MeshData md;
Error err = QuickHull::build(varr, md);
@@ -230,7 +226,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
PackedVector3Array faces;
for (int j = 0; j < md.faces.size(); ++j) {
- Geometry::MeshData::Face face = md.faces[j];
+ Geometry3D::MeshData::Face face = md.faces[j];
for (int k = 2; k < face.indices.size(); ++k) {
faces.push_back(md.vertices[face.indices[0]]);
@@ -278,7 +274,6 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform,
}
void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
-
Vector<Vector3> nav_vertices;
for (int i = 0; i < p_detail_mesh->nverts; i++) {
@@ -320,8 +315,9 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
rcContext ctx;
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Setting up Configuration..."), 1);
+ }
#endif
const float *verts = vertices.ptr();
@@ -357,14 +353,16 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
cfg.bmax[2] = bmax[2];
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Calculating grid size..."), 2);
+ }
#endif
rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Creating heightfield..."), 3);
+ }
#endif
hf = rcAllocHeightfield();
@@ -372,8 +370,9 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Marking walkable triangles..."), 4);
+ }
#endif
{
Vector<unsigned char> tri_areas;
@@ -387,16 +386,20 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
}
- if (p_nav_mesh->get_filter_low_hanging_obstacles())
+ if (p_nav_mesh->get_filter_low_hanging_obstacles()) {
rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
- if (p_nav_mesh->get_filter_ledge_spans())
+ }
+ if (p_nav_mesh->get_filter_ledge_spans()) {
rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
- if (p_nav_mesh->get_filter_walkable_low_height_spans())
+ }
+ if (p_nav_mesh->get_filter_walkable_low_height_spans()) {
rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
+ }
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Constructing compact heightfield..."), 5);
+ }
#endif
chf = rcAllocCompactHeightfield();
@@ -408,15 +411,17 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
hf = nullptr;
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Eroding walkable area..."), 6);
+ }
#endif
ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Partitioning..."), 7);
+ }
#endif
if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
@@ -429,8 +434,9 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
}
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Creating contours..."), 8);
+ }
#endif
cset = rcAllocContourSet();
@@ -439,8 +445,9 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Creating polymesh..."), 9);
+ }
#endif
poly_mesh = rcAllocPolyMesh();
@@ -457,8 +464,9 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh(
cset = nullptr;
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Converting to native navigation mesh..."), 10);
+ }
#endif
_convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
@@ -481,7 +489,6 @@ NavigationMeshGenerator::~NavigationMeshGenerator() {
}
void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
-
ERR_FAIL_COND(!p_nav_mesh.is_valid());
#ifdef TOOLS_ENABLED
@@ -490,8 +497,9 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node)
ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11));
}
- if (ep)
+ if (ep) {
ep->step(TTR("Parsing Geometry..."), 0);
+ }
#endif
Vector<float> vertices;
@@ -514,7 +522,6 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node)
}
if (vertices.size() > 0 && indices.size() > 0) {
-
rcHeightfield *hf = nullptr;
rcCompactHeightfield *chf = nullptr;
rcContourSet *cset = nullptr;
@@ -551,11 +558,13 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node)
}
#ifdef TOOLS_ENABLED
- if (ep)
+ if (ep) {
ep->step(TTR("Done!"), 11);
+ }
- if (ep)
+ if (ep) {
memdelete(ep);
+ }
#endif
}
diff --git a/modules/gdnavigation/navigation_mesh_generator.h b/modules/gdnavigation/navigation_mesh_generator.h
index c5f7b2ab81..88ccdb1c41 100644
--- a/modules/gdnavigation/navigation_mesh_generator.h
+++ b/modules/gdnavigation/navigation_mesh_generator.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnavigation/register_types.cpp b/modules/gdnavigation/register_types.cpp
index 088b26bf17..8443d3d242 100644
--- a/modules/gdnavigation/register_types.cpp
+++ b/modules/gdnavigation/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "register_types.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "gd_navigation_server.h"
#include "servers/navigation_server_3d.h"
diff --git a/modules/gdnavigation/register_types.h b/modules/gdnavigation/register_types.h
index cdbff1b937..c2bb08c649 100644
--- a/modules/gdnavigation/register_types.h
+++ b/modules/gdnavigation/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdnavigation/rvo_agent.cpp b/modules/gdnavigation/rvo_agent.cpp
index 3c39f02c26..21e43d08c1 100644
--- a/modules/gdnavigation/rvo_agent.cpp
+++ b/modules/gdnavigation/rvo_agent.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,8 +36,7 @@
@author AndreaCatania
*/
-RvoAgent::RvoAgent() :
- map(nullptr) {
+RvoAgent::RvoAgent() {
callback.id = ObjectID();
}
diff --git a/modules/gdnavigation/rvo_agent.h b/modules/gdnavigation/rvo_agent.h
index 914cbaa7d9..d9e3345498 100644
--- a/modules/gdnavigation/rvo_agent.h
+++ b/modules/gdnavigation/rvo_agent.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,9 @@
#ifndef RVO_AGENT_H
#define RVO_AGENT_H
-#include "core/object.h"
+#include "core/object/class_db.h"
#include "nav_rid.h"
+
#include <Agent.h>
/**
@@ -49,7 +50,7 @@ class RvoAgent : public NavRid {
Variant new_velocity;
};
- NavMap *map;
+ NavMap *map = nullptr;
RVO::Agent agent;
AvoidanceComputedCallback callback;
uint32_t map_update_id;
diff --git a/modules/gdscript/SCsub b/modules/gdscript/SCsub
index e58a1d8edc..5c8cbdf869 100644
--- a/modules/gdscript/SCsub
+++ b/modules/gdscript/SCsub
@@ -17,3 +17,7 @@ if env["tools"]:
# Using a define in the disabled case, to avoid having an extra define
# in regular builds where all modules are enabled.
env_gdscript.Append(CPPDEFINES=["GDSCRIPT_NO_LSP"])
+
+if env["tests"]:
+ env_gdscript.Append(CPPDEFINES=["TESTS_ENABLED"])
+ env_gdscript.add_source_files(env.modules_sources, "./tests/*.cpp")
diff --git a/modules/gdscript/config.py b/modules/gdscript/config.py
index 6fc227e7f5..61ce6185a5 100644
--- a/modules/gdscript/config.py
+++ b/modules/gdscript/config.py
@@ -10,7 +10,6 @@ def get_doc_classes():
return [
"@GDScript",
"GDScript",
- "GDScriptFunctionState",
]
diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml
index be159b6407..9e974b6fdc 100644
--- a/modules/gdscript/doc_classes/@GDScript.xml
+++ b/modules/gdscript/doc_classes/@GDScript.xml
@@ -7,6 +7,7 @@
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>
+ <link title="Random number generation">https://docs.godotengine.org/en/latest/tutorials/math/random_number_generation.html</link>
</tutorials>
<methods>
<method name="Color8">
@@ -31,60 +32,6 @@
[/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 standardized [code]name[/code] with [code]alpha[/code] ranging from 0 to 1.
- [codeblock]
- red = ColorN("red", 1)
- [/codeblock]
- Supported color names are the same as the constants defined in [Color].
- </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>
@@ -93,85 +40,23 @@
<argument index="1" name="message" type="String" default="&quot;&quot;">
</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.
+ Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users.
+ [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode.
The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed.
[codeblock]
- # Imagine we always want speed to be between 0 and 20
- speed = -10
+ # Imagine we always want speed to be between 0 and 20.
+ var 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
+ assert(speed &gt;= 0 and speed &lt; 20) # You can also combine the two conditional statements in one check
assert(speed &lt; 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details
[/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="PackedByteArray">
- </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="code" type="int">
+ <argument index="0" name="char" type="int">
</argument>
<description>
Returns a character as a String of the given Unicode code point (which is compatible with ASCII code).
@@ -180,29 +65,6 @@
a = char(65 + 32) # a is "a"
a = char(8364) # a is "€"
[/codeblock]
- This is the inverse of [method ord].
- </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">
@@ -224,185 +86,13 @@
[/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="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 index="0" name="dictionary" 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.
- For exponents to other bases use the method [method pow].
- [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.0
- a = floor(2.99)
- # a is -3.0
- a = floor(-2.99)
- [/codeblock]
- [b]Note:[/b] This method returns a float. If you need an integer, you can use [code]int(s)[/code] directly.
- </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="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]
+ Converts a dictionary (previously created with [method inst2dict]) back to an instance. Useful for deserializing.
</description>
</method>
<method name="get_stack">
@@ -426,22 +116,10 @@
[/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 index="0" name="instance" type="Object">
</argument>
<description>
Returns the passed instance converted to a dictionary (useful for serializing).
@@ -459,89 +137,6 @@
[/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. This is the opposite of [method lerp].
- [codeblock]
- var middle = lerp(20, 30, 0.75)
- # `middle` is now 27.5.
- # Now, we pretend to have forgotten the original ratio and want to get it back.
- var ratio = inverse_lerp(20, 30, 27.5)
- # `ratio` is now 0.75.
- [/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 [code]true[/code] if [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 [code]true[/code] if [code]s[/code] is zero or almost zero.
- </description>
- </method>
<method name="len">
<return type="int">
</return>
@@ -556,239 +151,20 @@
[/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. This is the opposite of [method inverse_lerp].
- 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]lerp[/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="lerp_angle">
- <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>
- Linearly interpolates between two angles (in radians) by a normalized value.
- Similar to [method lerp], but interpolates correctly when the angles wrap around [constant @GDScript.TAU].
- [codeblock]
- extends Sprite
- var elapsed = 0.0
- func _process(delta):
- var min_angle = deg2rad(0.0)
- var max_angle = deg2rad(90.0)
- rotation = lerp_angle(min_angle, max_angle, elapsed)
- elapsed += delta
- [/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). This can be used to implement volume sliders that behave as expected (since volume isn't linear). Example:
- [codeblock]
- # "Slider" refers to a node that inherits Range such as HSlider or VSlider.
- # Its range must be configured to go from 0 to 1.
- # Change the bus name if you'd like to change the volume of a specific bus only.
- AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), linear2db($Slider.value))
- [/codeblock]
- </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].
+ Loads a resource from the filesystem located at [code]path[/code]. The resource is loaded on the method call (unless it's referenced already elsewhere, e.g. in another script or in the scene), which might cause slight delay, especially when loading scenes. To avoid unnecessary delays when loading something multiple times, either store the resource in a variable or use [method preload].
+ [b]Note:[/b] Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script.
[codeblock]
- # Load a scene called main located in the root of the project directory.
- var main = load("res://main.tscn")
+ # Load a scene called main located in the root of the project directory and cache it in a variable.
+ var main = load("res://main.tscn") # main will contain a PackedScene resource.
[/codeblock]
[b]Important:[/b] The path must be absolute, a local path will just return [code]null[/code].
- </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="ord">
- <return type="int">
- </return>
- <argument index="0" name="char" type="String">
- </argument>
- <description>
- Returns an integer representing the Unicode code point of the given Unicode character [code]char[/code].
- [codeblock]
- a = ord("A") # a is 65
- a = ord("a") # a is 97
- a = ord("€") # a is 8364
- [/codeblock]
- This is the inverse of [method char].
- </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="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="pow">
- <return type="float">
- </return>
- <argument index="0" name="base" type="float">
- </argument>
- <argument index="1" name="exp" 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]
+ This method is a simplified version of [method ResourceLoader.load], which can be used for more advanced scenarios.
</description>
</method>
<method name="preload">
@@ -797,22 +173,11 @@
<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".
+ Returns a [Resource] from the filesystem located at [code]path[/code]. The resource is loaded during script parsing, i.e. is loaded with the script and [method preload] effectively acts as a reference to that resource. Note that the method requires a constant path. If you want to load a resource from a dynamic/variable path, use [method load].
+ [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path" or by dragging the file from the FileSystem dock into the script.
[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]
+ # Instance a scene.
+ var diamond = preload("res://diamond.tscn").instance()
[/codeblock]
</description>
</method>
@@ -820,7 +185,7 @@
<return type="void">
</return>
<description>
- Like [method print], but prints only when used in debug mode.
+ Like [method @GlobalScope.print], but prints only when used in debug mode.
</description>
</method>
<method name="print_stack">
@@ -834,315 +199,21 @@
[/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]
- [b]Note:[/b] Due to limitations with Godot's built-in console, this only prints to the terminal. If you need to print in the editor, use another method, such as [method print].
- </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 - 1][/code] (where N is smaller than 2^32).
- [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)
+ print(range(4))
+ print(range(2, 5))
+ print(range(0, 6, 2))
[/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. Note that the maximum return value is 10, which is a design decision in the implementation.
- [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]. This can also be used to round a floating point number to an arbitrary number of decimals.
- [codeblock]
- stepify(100, 32) # Returns 96
- stepify(3.14159, 0.01) # Returns 3.14
+ [0, 1, 2, 3]
+ [2, 3, 4]
+ [0, 2, 4]
[/codeblock]
</description>
</method>
@@ -1159,264 +230,27 @@
[/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("Sprite2D") # 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 [enum Variant.Type] values.
- [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 an empty string if valid, or an error message otherwise.
- [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="PackedByteArray">
- </return>
- <argument index="0" name="var" type="Variant">
- </argument>
- <argument index="1" name="full_objects" type="bool" default="false">
+ <argument index="0" name="type" type="StringName">
</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.
- You can also use [code]yield[/code] to wait for a function to finish:
- [codeblock]
- func _ready():
- yield(countdown(), "completed") # waiting for the countdown() function to complete
- print('Ready')
-
- func countdown():
- yield(get_tree(), "idle_frame") # returns a GDScriptFunctionState object to _ready()
- print(3)
- yield(get_tree().create_timer(1.0), "timeout")
- print(2)
- yield(get_tree().create_timer(1.0), "timeout")
- print(1)
- yield(get_tree().create_timer(1.0), "timeout")
-
- # prints:
- # 3
- # 2
- # 1
- # Ready
- [/codeblock]
- When yielding on a function, the [code]completed[/code] signal will be emitted automatically when the function returns. It can, therefore, be used as the [code]signal[/code] parameter of the [code]yield[/code] method to resume.
- In order to yield on a function, the resulting function should also return a [code]GDScriptFunctionState[/code]. Notice [code]yield(get_tree(), "idle_frame")[/code] from the above example.
</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 that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to [code]TAU / 2[/code].
</constant>
<constant name="TAU" value="6.283185">
- The circle constant, the circumference of the unit circle.
+ The circle constant, the circumference of the unit circle in radians.
</constant>
<constant name="INF" value="inf">
- A positive infinity. (For negative infinity, use -INF).
+ 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.
+ "Not a Number", an invalid value. [code]NaN[/code] has special properties, including that it is not equal to itself. It is output by some invalid operations, such as dividing zero by zero.
</constant>
</constants>
</class>
diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml
index 62ccb93901..631a102130 100644
--- a/modules/gdscript/doc_classes/GDScript.xml
+++ b/modules/gdscript/doc_classes/GDScript.xml
@@ -8,7 +8,7 @@
[method new] creates a new instance of the script. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes.
</description>
<tutorials>
- <link>https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/index.html</link>
+ <link title="GDScript tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/index.html</link>
</tutorials>
<methods>
<method name="get_as_byte_code" qualifiers="const">
diff --git a/modules/gdscript/doc_classes/GDScriptFunctionState.xml b/modules/gdscript/doc_classes/GDScriptFunctionState.xml
deleted file mode 100644
index 9a73764646..0000000000
--- a/modules/gdscript/doc_classes/GDScriptFunctionState.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="GDScriptFunctionState" inherits="Reference" version="4.0">
- <brief_description>
- State of a function call after yielding.
- </brief_description>
- <description>
- Calling [method @GDScript.yield] within a function will cause that function to yield and return its current state as an object of this type. The yielded function call can then be resumed later by calling [method resume] on this state object.
- </description>
- <tutorials>
- </tutorials>
- <methods>
- <method name="is_valid" qualifiers="const">
- <return type="bool">
- </return>
- <argument index="0" name="extended_check" type="bool" default="false">
- </argument>
- <description>
- Check whether the function call may be resumed. This is not the case if the function state was already resumed.
- If [code]extended_check[/code] is enabled, it also checks if the associated script and object still exist. The extended check is done in debug mode as part of [method GDScriptFunctionState.resume], but you can use this if you know you may be trying to resume without knowing for sure the object and/or script have survived up to that point.
- </description>
- </method>
- <method name="resume">
- <return type="Variant">
- </return>
- <argument index="0" name="arg" type="Variant" default="null">
- </argument>
- <description>
- Resume execution of the yielded function call.
- If handed an argument, return the argument from the [method @GDScript.yield] call in the yielded function call. You can pass e.g. an [Array] to hand multiple arguments.
- This function returns what the resumed function call returns, possibly another function state if yielded again.
- </description>
- </method>
- </methods>
- <signals>
- <signal name="completed">
- <argument index="0" name="result" type="Variant">
- </argument>
- <description>
- </description>
- </signal>
- </signals>
- <constants>
- </constants>
-</class>
diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp
index 0aca4dbc5e..b792ff54d6 100644
--- a/modules/gdscript/editor/gdscript_highlighter.cpp
+++ b/modules/gdscript/editor/gdscript_highlighter.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,39 +29,24 @@
/*************************************************************************/
#include "gdscript_highlighter.h"
+#include "../gdscript.h"
#include "../gdscript_tokenizer.h"
#include "editor/editor_settings.h"
-#include "scene/gui/text_edit.h"
-
-inline bool _is_symbol(CharType c) {
-
- return is_symbol(c);
-}
-
-static bool _is_text_char(CharType c) {
-
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
-}
-
-static bool _is_char(CharType c) {
+static bool _is_char(char32_t c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
-static bool _is_number(CharType c) {
- return (c >= '0' && c <= '9');
-}
-
-static bool _is_hex_symbol(CharType c) {
+static bool _is_hex_symbol(char32_t c) {
return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
-static bool _is_bin_symbol(CharType c) {
+static bool _is_bin_symbol(char32_t c) {
return (c == '0' || c == '1');
}
-Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {
- Map<int, TextEdit::HighlighterInfo> color_map;
+Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {
+ Dictionary color_map;
Type next_type = NONE;
Type current_type = NONE;
@@ -85,36 +70,146 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
Color keyword_color;
Color color;
- int in_region = text_editor->_is_line_in_region(p_line);
- int deregion = 0;
+ color_region_cache[p_line] = -1;
+ int in_region = -1;
+ if (p_line != 0) {
+ int prev_region_line = p_line - 1;
+ while (prev_region_line > 0 && !color_region_cache.has(prev_region_line)) {
+ prev_region_line--;
+ }
+ for (int i = prev_region_line; i < p_line - 1; i++) {
+ get_line_syntax_highlighting(i);
+ }
+ if (!color_region_cache.has(p_line - 1)) {
+ get_line_syntax_highlighting(p_line - 1);
+ }
+ in_region = color_region_cache[p_line - 1];
+ }
- const Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text_editor->_get_line_color_region_info(p_line);
- const String &str = text_editor->get_line(p_line);
+ const String &str = text_edit->get_line(p_line);
+ const int line_length = str.length();
Color prev_color;
+
+ if (in_region != -1 && str.length() == 0) {
+ color_region_cache[p_line] = in_region;
+ }
for (int j = 0; j < str.length(); j++) {
- TextEdit::HighlighterInfo highlighter_info;
+ Dictionary highlighter_info;
- if (deregion > 0) {
- deregion--;
- if (deregion == 0) {
- in_region = -1;
+ color = font_color;
+ bool is_char = !is_symbol(str[j]);
+ bool is_a_symbol = is_symbol(str[j]);
+ bool is_number = (str[j] >= '0' && str[j] <= '9');
+
+ /* color regions */
+ if (is_a_symbol || in_region != -1) {
+ int from = j;
+ for (; from < line_length; from++) {
+ if (str[from] == '\\') {
+ from++;
+ continue;
+ }
+ break;
}
- }
- if (deregion != 0) {
- if (color != prev_color) {
- prev_color = color;
- highlighter_info.color = color;
- color_map[j] = highlighter_info;
- }
- continue;
- }
+ if (from != line_length) {
+ /* check if we are in entering a region */
+ if (in_region == -1) {
+ for (int c = 0; c < color_regions.size(); c++) {
+ /* check there is enough room */
+ int chars_left = line_length - from;
+ int start_key_length = color_regions[c].start_key.length();
+ int end_key_length = color_regions[c].end_key.length();
+ if (chars_left < start_key_length) {
+ continue;
+ }
+
+ /* search the line */
+ bool match = true;
+ const char32_t *start_key = color_regions[c].start_key.get_data();
+ for (int k = 0; k < start_key_length; k++) {
+ if (start_key[k] != str[from + k]) {
+ match = false;
+ break;
+ }
+ }
+ if (!match) {
+ continue;
+ }
+ in_region = c;
+ from += start_key_length;
+
+ /* check if it's the whole line */
+ if (end_key_length == 0 || color_regions[c].line_only || from + end_key_length > line_length) {
+ prev_color = color_regions[in_region].color;
+ highlighter_info["color"] = color_regions[c].color;
+ color_map[j] = highlighter_info;
+
+ j = line_length;
+ if (!color_regions[c].line_only) {
+ color_region_cache[p_line] = c;
+ }
+ }
+ break;
+ }
- color = font_color;
+ if (j == line_length) {
+ continue;
+ }
+ }
+
+ /* if we are in one find the end key */
+ if (in_region != -1) {
+ /* search the line */
+ int region_end_index = -1;
+ int end_key_length = color_regions[in_region].end_key.length();
+ const char32_t *end_key = color_regions[in_region].end_key.get_data();
+ for (; from < line_length; from++) {
+ if (line_length - from < end_key_length) {
+ break;
+ }
+
+ if (!is_symbol(str[from])) {
+ continue;
+ }
+
+ if (str[from] == '\\') {
+ from++;
+ continue;
+ }
+
+ region_end_index = from;
+ for (int k = 0; k < end_key_length; k++) {
+ if (end_key[k] != str[from + k]) {
+ region_end_index = -1;
+ break;
+ }
+ }
+
+ if (region_end_index != -1) {
+ break;
+ }
+ }
+
+ prev_color = color_regions[in_region].color;
+ highlighter_info["color"] = color_regions[in_region].color;
+ color_map[j] = highlighter_info;
+
+ previous_type = REGION;
+ previous_text = "";
+ previous_column = j;
+ j = from + (end_key_length - 1);
+ if (region_end_index == -1) {
+ color_region_cache[p_line] = in_region;
+ }
- bool is_char = _is_text_char(str[j]);
- bool is_symbol = _is_symbol(str[j]);
- bool is_number = _is_number(str[j]);
+ in_region = -1;
+ prev_is_char = false;
+ prev_is_number = false;
+ continue;
+ }
+ }
+ }
// allow ABCDEF in hex notation
if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) {
@@ -136,7 +231,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
// 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] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
is_number = true;
- is_symbol = false;
+ is_a_symbol = false;
is_char = false;
if (str[j] == 'x' && str[j - 1] == '0') {
@@ -154,43 +249,26 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
is_number = false;
}
- if (is_symbol && str[j] != '.' && in_word) {
+ if (is_a_symbol && str[j] != '.' && in_word) {
in_word = false;
}
- if (is_symbol && cri_map.has(j)) {
- const TextEdit::Text::ColorRegionInfo &cri = cri_map[j];
-
- if (in_region == -1) {
- if (!cri.end) {
- in_region = cri.region;
- }
- } else {
- TextEdit::ColorRegion cr = text_editor->_get_color_region(cri.region);
- if (in_region == cri.region && !cr.line_only) { //ignore otherwise
- if (cri.end || cr.eq) {
- deregion = cr.eq ? cr.begin_key.length() : cr.end_key.length();
- }
- }
- }
- }
-
if (!is_char) {
in_keyword = false;
}
- if (in_region == -1 && !in_keyword && is_char && !prev_is_char) {
-
+ if (!in_keyword && is_char && !prev_is_char) {
int to = j;
- while (to < str.length() && _is_text_char(str[to]))
+ while (to < str.length() && !is_symbol(str[to])) {
to++;
+ }
String word = str.substr(j, to - j);
Color col = Color();
- if (text_editor->has_keyword_color(word)) {
- col = text_editor->get_keyword_color(word);
- } else if (text_editor->has_member_color(word)) {
- col = text_editor->get_member_color(word);
+ if (keywords.has(word)) {
+ col = keywords[word];
+ } else if (member_keywords.has(word)) {
+ col = member_keywords[word];
for (int k = j - 1; k >= 0; k--) {
if (str[k] == '.') {
col = Color(); //member indexing not allowed
@@ -208,9 +286,8 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
}
if (!in_function_name && in_word && !in_keyword) {
-
int k = j;
- while (k < str.length() && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
+ while (k < str.length() && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k++;
}
@@ -221,14 +298,14 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
if (str[k] == '(') {
in_function_name = true;
- } else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_VAR)) {
+ } else if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::VAR)) {
in_variable_declaration = true;
}
}
if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) {
int k = j;
- while (k > 0 && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
+ while (k > 0 && !is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') {
k--;
}
@@ -237,8 +314,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
}
}
- if (is_symbol) {
-
+ if (is_a_symbol) {
if (in_function_name) {
in_function_args = true;
}
@@ -275,14 +351,11 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
if (!in_node_path && in_region == -1 && str[j] == '$') {
in_node_path = true;
- } else if (in_region != -1 || (is_symbol && str[j] != '/')) {
+ } else if (in_region != -1 || (is_a_symbol && str[j] != '/')) {
in_node_path = false;
}
- if (in_region >= 0) {
- next_type = REGION;
- color = text_editor->_get_color_region(in_region).color;
- } else if (in_node_path) {
+ if (in_node_path) {
next_type = NODE_PATH;
color = node_path_color;
} else if (in_keyword) {
@@ -294,12 +367,12 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
} else if (in_function_name) {
next_type = FUNCTION;
- if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::TK_PR_FUNCTION)) {
+ if (previous_text == GDScriptTokenizer::get_token_name(GDScriptTokenizer::Token::FUNC)) {
color = function_definition_color;
} else {
color = function_color;
}
- } else if (is_symbol) {
+ } else if (is_a_symbol) {
next_type = SYMBOL;
color = symbol_color;
} else if (is_number) {
@@ -340,32 +413,133 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
if (color != prev_color) {
prev_color = color;
- highlighter_info.color = color;
+ highlighter_info["color"] = color;
color_map[j] = highlighter_info;
}
}
return color_map;
}
-String GDScriptSyntaxHighlighter::get_name() const {
+String GDScriptSyntaxHighlighter::_get_name() const {
return "GDScript";
}
-List<String> GDScriptSyntaxHighlighter::get_supported_languages() {
- List<String> languages;
+Array GDScriptSyntaxHighlighter::_get_supported_languages() const {
+ Array languages;
languages.push_back("GDScript");
return languages;
}
void GDScriptSyntaxHighlighter::_update_cache() {
- font_color = text_editor->get_theme_color("font_color");
- symbol_color = text_editor->get_theme_color("symbol_color");
- function_color = text_editor->get_theme_color("function_color");
- number_color = text_editor->get_theme_color("number_color");
- member_color = text_editor->get_theme_color("member_variable_color");
+ keywords.clear();
+ member_keywords.clear();
+ color_regions.clear();
+ color_region_cache.clear();
+
+ font_color = text_edit->get_theme_color("font_color");
+ symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color");
+ function_color = EDITOR_GET("text_editor/highlighting/function_color");
+ number_color = EDITOR_GET("text_editor/highlighting/number_color");
+ member_color = EDITOR_GET("text_editor/highlighting/member_variable_color");
+
+ /* Engine types. */
+ const Color types_color = EDITOR_GET("text_editor/highlighting/engine_type_color");
+ List<StringName> types;
+ ClassDB::get_class_list(&types);
+ for (List<StringName>::Element *E = types.front(); E; E = E->next()) {
+ String n = E->get();
+ if (n.begins_with("_")) {
+ n = n.substr(1, n.length());
+ }
+ keywords[n] = types_color;
+ }
+
+ /* User types. */
+ const Color usertype_color = EDITOR_GET("text_editor/highlighting/user_type_color");
+ List<StringName> global_classes;
+ ScriptServer::get_global_class_list(&global_classes);
+ for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
+ keywords[String(E->get())] = usertype_color;
+ }
+
+ /* Autoloads. */
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ const ProjectSettings::AutoloadInfo &info = E->value();
+ if (info.is_singleton) {
+ keywords[info.name] = usertype_color;
+ }
+ }
+
+ const GDScriptLanguage *gdscript = GDScriptLanguage::get_singleton();
+
+ /* Core types. */
+ const Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color");
+ List<String> core_types;
+ gdscript->get_core_type_words(&core_types);
+ for (List<String>::Element *E = core_types.front(); E; E = E->next()) {
+ keywords[E->get()] = basetype_color;
+ }
+
+ /* Reserved words. */
+ const Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color");
+ List<String> keyword_list;
+ gdscript->get_reserved_words(&keyword_list);
+ for (List<String>::Element *E = keyword_list.front(); E; E = E->next()) {
+ keywords[E->get()] = keyword_color;
+ }
+
+ /* Comments */
+ const Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color");
+ List<String> comments;
+ gdscript->get_comment_delimiters(&comments);
+ for (List<String>::Element *E = comments.front(); E; E = E->next()) {
+ String comment = E->get();
+ String beg = comment.get_slice(" ", 0);
+ String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String();
+ add_color_region(beg, end, comment_color, end == "");
+ }
- const String text_editor_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme");
- const bool default_theme = text_editor_color_theme == "Default";
+ /* Strings */
+ const Color string_color = EDITOR_GET("text_editor/highlighting/string_color");
+ List<String> strings;
+ gdscript->get_string_delimiters(&strings);
+ for (List<String>::Element *E = strings.front(); E; E = E->next()) {
+ String string = E->get();
+ String beg = string.get_slice(" ", 0);
+ String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String();
+ add_color_region(beg, end, string_color, end == "");
+ }
+
+ const Ref<Script> script = _get_edited_resource();
+ if (script.is_valid()) {
+ /* Member types. */
+ const Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color");
+ StringName instance_base = script->get_instance_base_type();
+ if (instance_base != StringName()) {
+ List<PropertyInfo> plist;
+ ClassDB::get_property_list(instance_base, &plist);
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
+ String name = E->get().name;
+ if (E->get().usage & PROPERTY_USAGE_CATEGORY || E->get().usage & PROPERTY_USAGE_GROUP || E->get().usage & PROPERTY_USAGE_SUBGROUP) {
+ continue;
+ }
+ if (name.find("/") != -1) {
+ continue;
+ }
+ member_keywords[name] = member_variable_color;
+ }
+
+ List<String> clist;
+ ClassDB::get_integer_constant_list(instance_base, &clist);
+ for (List<String>::Element *E = clist.front(); E; E = E->next()) {
+ member_keywords[E->get()] = member_variable_color;
+ }
+ }
+ }
+
+ const String text_edit_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme");
+ const bool default_theme = text_edit_color_theme == "Default";
if (default_theme || EditorSettings::get_singleton()->is_dark_theme()) {
function_definition_color = Color(0.4, 0.9, 1.0);
@@ -377,7 +551,7 @@ void GDScriptSyntaxHighlighter::_update_cache() {
EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color);
EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color);
- if (text_editor_color_theme == "Adaptive" || default_theme) {
+ if (text_edit_color_theme == "Adaptive" || default_theme) {
EditorSettings::get_singleton()->set_initial_value(
"text_editor/highlighting/gdscript/function_definition_color",
function_definition_color,
@@ -393,6 +567,36 @@ void GDScriptSyntaxHighlighter::_update_cache() {
type_color = EDITOR_GET("text_editor/highlighting/base_type_color");
}
-SyntaxHighlighter *GDScriptSyntaxHighlighter::create() {
- return memnew(GDScriptSyntaxHighlighter);
+void GDScriptSyntaxHighlighter::add_color_region(const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only) {
+ for (int i = 0; i < p_start_key.length(); i++) {
+ ERR_FAIL_COND_MSG(!is_symbol(p_start_key[i]), "color regions must start with a symbol");
+ }
+
+ if (p_end_key.length() > 0) {
+ for (int i = 0; i < p_end_key.length(); i++) {
+ ERR_FAIL_COND_MSG(!is_symbol(p_end_key[i]), "color regions must end with a symbol");
+ }
+ }
+
+ int at = 0;
+ for (int i = 0; i < color_regions.size(); i++) {
+ ERR_FAIL_COND_MSG(color_regions[i].start_key == p_start_key, "color region with start key '" + p_start_key + "' already exists.");
+ if (p_start_key.length() < color_regions[i].start_key.length()) {
+ at++;
+ }
+ }
+
+ ColorRegion color_region;
+ color_region.color = p_color;
+ color_region.start_key = p_start_key;
+ color_region.end_key = p_end_key;
+ color_region.line_only = p_line_only;
+ color_regions.insert(at, color_region);
+ clear_highlighting_cache();
+}
+
+Ref<EditorSyntaxHighlighter> GDScriptSyntaxHighlighter::_create() const {
+ Ref<GDScriptSyntaxHighlighter> syntax_highlighter;
+ syntax_highlighter.instance();
+ return syntax_highlighter;
}
diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h
index e652fb1471..1b57cb1923 100644
--- a/modules/gdscript/editor/gdscript_highlighter.h
+++ b/modules/gdscript/editor/gdscript_highlighter.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,10 +31,25 @@
#ifndef GDSCRIPT_HIGHLIGHTER_H
#define GDSCRIPT_HIGHLIGHTER_H
+#include "editor/plugins/script_editor_plugin.h"
#include "scene/gui/text_edit.h"
-class GDScriptSyntaxHighlighter : public SyntaxHighlighter {
+class GDScriptSyntaxHighlighter : public EditorSyntaxHighlighter {
+ GDCLASS(GDScriptSyntaxHighlighter, EditorSyntaxHighlighter)
+
private:
+ struct ColorRegion {
+ Color color;
+ String start_key;
+ String end_key;
+ bool line_only = false;
+ };
+ Vector<ColorRegion> color_regions;
+ Map<int, int> color_region_cache;
+
+ Dictionary keywords;
+ Dictionary member_keywords;
+
enum Type {
NONE,
REGION,
@@ -59,14 +74,16 @@ private:
Color node_path_color;
Color type_color;
+ void add_color_region(const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only = false);
+
public:
- static SyntaxHighlighter *create();
+ virtual void _update_cache() override;
+ virtual Dictionary _get_line_syntax_highlighting(int p_line) override;
- virtual void _update_cache();
- virtual Map<int, TextEdit::HighlighterInfo> _get_line_syntax_highlighting(int p_line);
+ virtual String _get_name() const override;
+ virtual Array _get_supported_languages() const override;
- virtual String get_name() const;
- virtual List<String> get_supported_languages();
+ virtual Ref<EditorSyntaxHighlighter> _create() const override;
};
#endif // GDSCRIPT_HIGHLIGHTER_H
diff --git a/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp b/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp
new file mode 100644
index 0000000000..6e930b6bf4
--- /dev/null
+++ b/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp
@@ -0,0 +1,351 @@
+/*************************************************************************/
+/* gdscript_translation_parser_plugin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_translation_parser_plugin.h"
+
+#include "core/io/resource_loader.h"
+#include "modules/gdscript/gdscript.h"
+
+void GDScriptEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const {
+ GDScriptLanguage::get_singleton()->get_recognized_extensions(r_extensions);
+}
+
+Error GDScriptEditorTranslationParserPlugin::parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) {
+ // Extract all translatable strings using the parsed tree from GDSriptParser.
+ // The strategy is to find all ExpressionNode and AssignmentNode from the tree and extract strings if relevant, i.e
+ // Search strings in ExpressionNode -> CallNode -> tr(), set_text(), set_placeholder() etc.
+ // Search strings in AssignmentNode -> text = "__", hint_tooltip = "__" etc.
+
+ Error err;
+ RES loaded_res = ResourceLoader::load(p_path, "", false, &err);
+ if (err) {
+ ERR_PRINT("Failed to load " + p_path);
+ return err;
+ }
+
+ ids = r_ids;
+ ids_ctx_plural = r_ids_ctx_plural;
+ Ref<GDScript> gdscript = loaded_res;
+ String source_code = gdscript->get_source_code();
+
+ GDScriptParser parser;
+ err = parser.parse(source_code, p_path, false);
+ if (err != OK) {
+ ERR_PRINT("Failed to parse with GDScript with GDScriptParser.");
+ return err;
+ }
+
+ // Traverse through the parsed tree from GDScriptParser.
+ GDScriptParser::ClassNode *c = parser.get_tree();
+ _traverse_class(c);
+
+ return OK;
+}
+
+void GDScriptEditorTranslationParserPlugin::_traverse_class(const GDScriptParser::ClassNode *p_class) {
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &m = p_class->members[i];
+ // There are 7 types of Member, but only class, function and variable can contain translatable strings.
+ switch (m.type) {
+ case GDScriptParser::ClassNode::Member::CLASS:
+ _traverse_class(m.m_class);
+ break;
+ case GDScriptParser::ClassNode::Member::FUNCTION:
+ _traverse_function(m.function);
+ break;
+ case GDScriptParser::ClassNode::Member::VARIABLE:
+ _read_variable(m.variable);
+ break;
+ default:
+ break;
+ }
+ }
+}
+
+void GDScriptEditorTranslationParserPlugin::_traverse_function(const GDScriptParser::FunctionNode *p_func) {
+ _traverse_block(p_func->body);
+}
+
+void GDScriptEditorTranslationParserPlugin::_read_variable(const GDScriptParser::VariableNode *p_var) {
+ _assess_expression(p_var->initializer);
+}
+
+void GDScriptEditorTranslationParserPlugin::_traverse_block(const GDScriptParser::SuiteNode *p_suite) {
+ if (!p_suite) {
+ return;
+ }
+
+ const Vector<GDScriptParser::Node *> &statements = p_suite->statements;
+ for (int i = 0; i < statements.size(); i++) {
+ GDScriptParser::Node *statement = statements[i];
+
+ // Statements with Node type constant, break, continue, pass, breakpoint are skipped because they can't contain translatable strings.
+ switch (statement->type) {
+ case GDScriptParser::Node::VARIABLE:
+ _assess_expression(static_cast<GDScriptParser::VariableNode *>(statement)->initializer);
+ break;
+ case GDScriptParser::Node::IF: {
+ GDScriptParser::IfNode *if_node = static_cast<GDScriptParser::IfNode *>(statement);
+ _assess_expression(if_node->condition);
+ //FIXME : if the elif logic is changed in GDScriptParser, then this probably will have to change as well. See GDScriptParser::TreePrinter::print_if().
+ _traverse_block(if_node->true_block);
+ _traverse_block(if_node->false_block);
+ break;
+ }
+ case GDScriptParser::Node::FOR: {
+ GDScriptParser::ForNode *for_node = static_cast<GDScriptParser::ForNode *>(statement);
+ _assess_expression(for_node->list);
+ _traverse_block(for_node->loop);
+ break;
+ }
+ case GDScriptParser::Node::WHILE: {
+ GDScriptParser::WhileNode *while_node = static_cast<GDScriptParser::WhileNode *>(statement);
+ _assess_expression(while_node->condition);
+ _traverse_block(while_node->loop);
+ break;
+ }
+ case GDScriptParser::Node::MATCH: {
+ GDScriptParser::MatchNode *match_node = static_cast<GDScriptParser::MatchNode *>(statement);
+ _assess_expression(match_node->test);
+ for (int j = 0; j < match_node->branches.size(); j++) {
+ _traverse_block(match_node->branches[j]->block);
+ }
+ break;
+ }
+ case GDScriptParser::Node::RETURN:
+ _assess_expression(static_cast<GDScriptParser::ReturnNode *>(statement)->return_value);
+ break;
+ case GDScriptParser::Node::ASSERT:
+ _assess_expression((static_cast<GDScriptParser::AssertNode *>(statement))->condition);
+ break;
+ case GDScriptParser::Node::ASSIGNMENT:
+ _assess_assignment(static_cast<GDScriptParser::AssignmentNode *>(statement));
+ break;
+ default:
+ if (statement->is_expression()) {
+ _assess_expression(static_cast<GDScriptParser::ExpressionNode *>(statement));
+ }
+ break;
+ }
+ }
+}
+
+void GDScriptEditorTranslationParserPlugin::_assess_expression(GDScriptParser::ExpressionNode *p_expression) {
+ // Explore all ExpressionNodes to find CallNodes which contain translation strings, such as tr(), set_text() etc.
+ // tr() can be embedded quite deep within multiple ExpressionNodes so need to dig down to search through all ExpressionNodes.
+ if (!p_expression) {
+ return;
+ }
+
+ // ExpressionNode of type await, cast, get_node, identifier, literal, preload, self, subscript, unary are ignored as they can't be CallNode
+ // containing translation strings.
+ switch (p_expression->type) {
+ case GDScriptParser::Node::ARRAY: {
+ GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(p_expression);
+ for (int i = 0; i < array_node->elements.size(); i++) {
+ _assess_expression(array_node->elements[i]);
+ }
+ break;
+ }
+ case GDScriptParser::Node::ASSIGNMENT:
+ _assess_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::BINARY_OPERATOR: {
+ GDScriptParser::BinaryOpNode *binary_op_node = static_cast<GDScriptParser::BinaryOpNode *>(p_expression);
+ _assess_expression(binary_op_node->left_operand);
+ _assess_expression(binary_op_node->right_operand);
+ break;
+ }
+ case GDScriptParser::Node::CALL: {
+ GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_expression);
+ _extract_from_call(call_node);
+ for (int i = 0; i < call_node->arguments.size(); i++) {
+ _assess_expression(call_node->arguments[i]);
+ }
+ } break;
+ case GDScriptParser::Node::DICTIONARY: {
+ GDScriptParser::DictionaryNode *dict_node = static_cast<GDScriptParser::DictionaryNode *>(p_expression);
+ for (int i = 0; i < dict_node->elements.size(); i++) {
+ _assess_expression(dict_node->elements[i].key);
+ _assess_expression(dict_node->elements[i].value);
+ }
+ break;
+ }
+ case GDScriptParser::Node::TERNARY_OPERATOR: {
+ GDScriptParser::TernaryOpNode *ternary_op_node = static_cast<GDScriptParser::TernaryOpNode *>(p_expression);
+ _assess_expression(ternary_op_node->condition);
+ _assess_expression(ternary_op_node->true_expr);
+ _assess_expression(ternary_op_node->false_expr);
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+void GDScriptEditorTranslationParserPlugin::_assess_assignment(GDScriptParser::AssignmentNode *p_assignment) {
+ // Extract the translatable strings coming from assignments. For example, get_node("Label").text = "____"
+
+ StringName assignee_name;
+ if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
+ assignee_name = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee)->name;
+ } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
+ assignee_name = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->attribute->name;
+ }
+
+ if (assignment_patterns.has(assignee_name) && p_assignment->assigned_value->type == GDScriptParser::Node::LITERAL) {
+ // If the assignment is towards one of the extract patterns (text, hint_tooltip etc.), and the value is a string literal, we collect the string.
+ ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_assignment->assigned_value)->value);
+ } else if (assignee_name == fd_filters && p_assignment->assigned_value->type == GDScriptParser::Node::CALL) {
+ // FileDialog.filters accepts assignment in the form of PackedStringArray. For example,
+ // get_node("FileDialog").filters = PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"]).
+
+ GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value);
+ if (call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {
+ GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(call_node->arguments[0]);
+
+ // Extract the name in "extension ; name" of PackedStringArray.
+ for (int i = 0; i < array_node->elements.size(); i++) {
+ _extract_fd_literals(array_node->elements[i]);
+ }
+ }
+ } else {
+ // If the assignee is not in extract patterns or the assigned_value is not Literal type, try to see if the assigned_value contains tr().
+ _assess_expression(p_assignment->assigned_value);
+ }
+}
+
+void GDScriptEditorTranslationParserPlugin::_extract_from_call(GDScriptParser::CallNode *p_call) {
+ // Extract the translatable strings coming from function calls. For example:
+ // tr("___"), get_node("Label").set_text("____"), get_node("LineEdit").set_placeholder("____").
+
+ StringName function_name = p_call->function_name;
+
+ // Variables for extracting tr() and tr_n().
+ Vector<String> id_ctx_plural;
+ id_ctx_plural.resize(3);
+ bool extract_id_ctx_plural = true;
+
+ if (function_name == tr_func) {
+ // Extract from tr(id, ctx).
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ if (p_call->arguments[i]->type == GDScriptParser::Node::LITERAL) {
+ id_ctx_plural.write[i] = static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[i])->value;
+ } else {
+ // Avoid adding something like tr("Flying dragon", var_context_level_1). We want to extract both id and context together.
+ extract_id_ctx_plural = false;
+ }
+ }
+ if (extract_id_ctx_plural) {
+ ids_ctx_plural->push_back(id_ctx_plural);
+ }
+ } else if (function_name == trn_func) {
+ // Extract from tr_n(id, plural, n, ctx).
+ Vector<int> indices;
+ indices.push_back(0);
+ indices.push_back(3);
+ indices.push_back(1);
+ for (int i = 0; i < indices.size(); i++) {
+ if (indices[i] >= p_call->arguments.size()) {
+ continue;
+ }
+
+ if (p_call->arguments[indices[i]]->type == GDScriptParser::Node::LITERAL) {
+ id_ctx_plural.write[i] = static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[indices[i]])->value;
+ } else {
+ extract_id_ctx_plural = false;
+ }
+ }
+ if (extract_id_ctx_plural) {
+ ids_ctx_plural->push_back(id_ctx_plural);
+ }
+ } else if (first_arg_patterns.has(function_name)) {
+ // Extracting argument with only string literals. In other words, not extracting something like set_text("hello " + some_var).
+ if (p_call->arguments[0]->type == GDScriptParser::Node::LITERAL) {
+ ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[0])->value);
+ }
+ } else if (second_arg_patterns.has(function_name)) {
+ if (p_call->arguments[1]->type == GDScriptParser::Node::LITERAL) {
+ ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[1])->value);
+ }
+ } else if (function_name == fd_add_filter) {
+ // Extract the 'JPE Images' in this example - get_node("FileDialog").add_filter("*.jpg; JPE Images").
+ _extract_fd_literals(p_call->arguments[0]);
+
+ } else if (function_name == fd_set_filter && p_call->arguments[0]->type == GDScriptParser::Node::CALL) {
+ // FileDialog.set_filters() accepts assignment in the form of PackedStringArray. For example,
+ // get_node("FileDialog").set_filters( PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"])).
+
+ GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_call->arguments[0]);
+ if (call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {
+ GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(call_node->arguments[0]);
+ for (int i = 0; i < array_node->elements.size(); i++) {
+ _extract_fd_literals(array_node->elements[i]);
+ }
+ }
+ }
+}
+
+void GDScriptEditorTranslationParserPlugin::_extract_fd_literals(GDScriptParser::ExpressionNode *p_expression) {
+ // Extract the name in "extension ; name".
+
+ if (p_expression->type == GDScriptParser::Node::LITERAL) {
+ String arg_val = String(static_cast<GDScriptParser::LiteralNode *>(p_expression)->value);
+ PackedStringArray arr = arg_val.split(";", true);
+ if (arr.size() != 2) {
+ ERR_PRINT("Argument for setting FileDialog has bad format.");
+ return;
+ }
+ ids->push_back(arr[1].strip_edges());
+ }
+}
+
+GDScriptEditorTranslationParserPlugin::GDScriptEditorTranslationParserPlugin() {
+ assignment_patterns.insert("text");
+ assignment_patterns.insert("placeholder_text");
+ assignment_patterns.insert("hint_tooltip");
+
+ first_arg_patterns.insert("set_text");
+ first_arg_patterns.insert("set_tooltip");
+ first_arg_patterns.insert("set_placeholder");
+ first_arg_patterns.insert("add_tab");
+ first_arg_patterns.insert("add_check_item");
+ first_arg_patterns.insert("add_item");
+ first_arg_patterns.insert("add_multistate_item");
+ first_arg_patterns.insert("add_radio_check_item");
+ first_arg_patterns.insert("add_separator");
+ first_arg_patterns.insert("add_submenu_item");
+
+ second_arg_patterns.insert("set_tab_title");
+ second_arg_patterns.insert("add_icon_check_item");
+ second_arg_patterns.insert("add_icon_item");
+ second_arg_patterns.insert("add_icon_radio_check_item");
+ second_arg_patterns.insert("set_item_text");
+}
diff --git a/modules/gdscript/editor/gdscript_translation_parser_plugin.h b/modules/gdscript/editor/gdscript_translation_parser_plugin.h
new file mode 100644
index 0000000000..5358a77140
--- /dev/null
+++ b/modules/gdscript/editor/gdscript_translation_parser_plugin.h
@@ -0,0 +1,73 @@
+/*************************************************************************/
+/* gdscript_translation_parser_plugin.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_TRANSLATION_PARSER_PLUGIN_H
+#define GDSCRIPT_TRANSLATION_PARSER_PLUGIN_H
+
+#include "core/templates/set.h"
+#include "editor/editor_translation_parser.h"
+#include "modules/gdscript/gdscript_parser.h"
+#include "modules/regex/regex.h"
+
+class GDScriptEditorTranslationParserPlugin : public EditorTranslationParserPlugin {
+ GDCLASS(GDScriptEditorTranslationParserPlugin, EditorTranslationParserPlugin);
+
+ Vector<String> *ids;
+ Vector<Vector<String>> *ids_ctx_plural;
+
+ // List of patterns used for extracting translation strings.
+ StringName tr_func = "tr";
+ StringName trn_func = "tr_n";
+ Set<StringName> assignment_patterns;
+ Set<StringName> first_arg_patterns;
+ Set<StringName> second_arg_patterns;
+ // FileDialog patterns.
+ StringName fd_add_filter = "add_filter";
+ StringName fd_set_filter = "set_filters";
+ StringName fd_filters = "filters";
+
+ void _traverse_class(const GDScriptParser::ClassNode *p_class);
+ void _traverse_function(const GDScriptParser::FunctionNode *p_func);
+ void _traverse_block(const GDScriptParser::SuiteNode *p_suite);
+
+ void _read_variable(const GDScriptParser::VariableNode *p_var);
+ void _assess_expression(GDScriptParser::ExpressionNode *p_expression);
+ void _assess_assignment(GDScriptParser::AssignmentNode *p_assignment);
+ void _extract_from_call(GDScriptParser::CallNode *p_call);
+ void _extract_fd_literals(GDScriptParser::ExpressionNode *p_expression);
+
+public:
+ virtual Error parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) override;
+ virtual void get_recognized_extensions(List<String> *r_extensions) const override;
+
+ GDScriptEditorTranslationParserPlugin();
+};
+
+#endif // GDSCRIPT_TRANSLATION_PARSER_PLUGIN_H
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 06ab9e226d..502e294275 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,24 +32,26 @@
#include <stdint.h>
+#include "core/config/engine.h"
+#include "core/config/project_settings.h"
+#include "core/core_constants.h"
#include "core/core_string_names.h"
-#include "core/engine.h"
-#include "core/global_constants.h"
#include "core/io/file_access_encrypted.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
+#include "gdscript_analyzer.h"
+#include "gdscript_cache.h"
#include "gdscript_compiler.h"
+#include "gdscript_parser.h"
+#include "gdscript_warning.h"
///////////////////////////
GDScriptNativeClass::GDScriptNativeClass(const StringName &p_name) {
-
name = p_name;
}
bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
-
bool ok;
int v = ClassDB::get_integer_constant(name, p_name, &ok);
@@ -62,12 +64,10 @@ bool GDScriptNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
}
void GDScriptNativeClass::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("new"), &GDScriptNativeClass::_new);
}
Variant GDScriptNativeClass::_new() {
-
Object *o = instance();
ERR_FAIL_COND_V_MSG(!o, Variant(), "Class type: '" + String(name) + "' is not instantiable.");
@@ -80,12 +80,21 @@ Variant GDScriptNativeClass::_new() {
}
Object *GDScriptNativeClass::instance() {
-
return ClassDB::instance(name);
}
-GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) {
+void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) {
+ GDScript *base = p_script->_base;
+ if (base != nullptr) {
+ _super_implicit_constructor(base, p_instance, r_error);
+ if (r_error.error != Callable::CallError::CALL_OK) {
+ return;
+ }
+ }
+ p_script->implicit_initializer->call(p_instance, nullptr, 0, r_error);
+}
+GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) {
/* STEP 1, CREATE */
GDScriptInstance *instance = memnew(GDScriptInstance);
@@ -107,10 +116,8 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco
MutexLock lock(GDScriptLanguage::singleton->lock);
instances.insert(instance->owner);
}
- if (p_argcount < 0) {
- return instance;
- }
- initializer->call(instance, p_args, p_argcount, r_error);
+
+ _super_implicit_constructor(this, instance, r_error);
if (r_error.error != Callable::CallError::CALL_OK) {
instance->script = Ref<GDScript>();
instance->owner->set_script_instance(nullptr);
@@ -120,12 +127,27 @@ GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argco
}
ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance.");
}
+
+ if (p_argcount < 0) {
+ return instance;
+ }
+ if (initializer != nullptr) {
+ initializer->call(instance, p_args, p_argcount, r_error);
+ if (r_error.error != Callable::CallError::CALL_OK) {
+ instance->script = Ref<GDScript>();
+ instance->owner->set_script_instance(nullptr);
+ {
+ MutexLock lock(GDScriptLanguage::singleton->lock);
+ instances.erase(p_owner);
+ }
+ ERR_FAIL_V_MSG(nullptr, "Error constructing a GDScriptInstance.");
+ }
+ }
//@TODO make thread safe
return instance;
}
Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
/* STEP 1, CREATE */
if (!valid) {
@@ -171,7 +193,6 @@ Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallErr
}
bool GDScript::can_instance() const {
-
#ifdef TOOLS_ENABLED
return valid && (tool || ScriptServer::is_scripting_enabled());
#else
@@ -180,7 +201,6 @@ bool GDScript::can_instance() const {
}
Ref<Script> GDScript::get_base_script() const {
-
if (_base) {
return Ref<GDScript>(_base);
} else {
@@ -189,16 +209,16 @@ Ref<Script> GDScript::get_base_script() const {
}
StringName GDScript::get_instance_base_type() const {
-
- if (native.is_valid())
+ if (native.is_valid()) {
return native->get_name();
- if (base.is_valid() && base->is_valid())
+ }
+ if (base.is_valid() && base->is_valid()) {
return base->get_instance_base_type();
+ }
return StringName();
}
struct _GDScriptMemberSort {
-
int index;
StringName name;
_FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
@@ -207,13 +227,11 @@ struct _GDScriptMemberSort {
#ifdef TOOLS_ENABLED
void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
-
placeholders.erase(p_placeholder);
}
#endif
-void GDScript::get_script_method_list(List<MethodInfo> *p_list) const {
-
+void GDScript::_get_script_method_list(List<MethodInfo> *r_list, bool p_include_base) const {
const GDScript *current = this;
while (current) {
for (const Map<StringName, GDScriptFunction *>::Element *E = current->member_functions.front(); E; E = E->next()) {
@@ -221,27 +239,35 @@ void GDScript::get_script_method_list(List<MethodInfo> *p_list) const {
MethodInfo mi;
mi.name = E->key();
for (int i = 0; i < func->get_argument_count(); i++) {
- mi.arguments.push_back(func->get_argument_type(i));
+ PropertyInfo arginfo = func->get_argument_type(i);
+#ifdef TOOLS_ENABLED
+ arginfo.name = func->get_argument_name(i);
+#endif
+ mi.arguments.push_back(arginfo);
}
mi.return_val = func->get_return_type();
- p_list->push_back(mi);
+ r_list->push_back(mi);
+ }
+ if (!p_include_base) {
+ return;
}
current = current->_base;
}
}
-void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const {
+void GDScript::get_script_method_list(List<MethodInfo> *r_list) const {
+ _get_script_method_list(r_list, true);
+}
+void GDScript::_get_script_property_list(List<PropertyInfo> *r_list, bool p_include_base) const {
const GDScript *sptr = this;
List<PropertyInfo> props;
while (sptr) {
-
Vector<_GDScriptMemberSort> msort;
for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) {
-
_GDScriptMemberSort ms;
ERR_CONTINUE(!sptr->member_indices.has(E->key()));
ms.index = sptr->member_indices[E->key()].index;
@@ -252,28 +278,33 @@ void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const {
msort.sort();
msort.invert();
for (int i = 0; i < msort.size(); i++) {
-
props.push_front(sptr->member_info[msort[i].name]);
}
+ if (!p_include_base) {
+ break;
+ }
sptr = sptr->_base;
}
for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- p_list->push_back(E->get());
+ r_list->push_back(E->get());
}
}
-bool GDScript::has_method(const StringName &p_method) const {
+void GDScript::get_script_property_list(List<PropertyInfo> *r_list) const {
+ _get_script_property_list(r_list, true);
+}
+bool GDScript::has_method(const StringName &p_method) const {
return member_functions.has(p_method);
}
MethodInfo GDScript::get_method_info(const StringName &p_method) const {
-
const Map<StringName, GDScriptFunction *>::Element *E = member_functions.find(p_method);
- if (!E)
+ if (!E) {
return MethodInfo();
+ }
GDScriptFunction *func = E->get();
MethodInfo mi;
@@ -287,7 +318,6 @@ MethodInfo GDScript::get_method_info(const StringName &p_method) const {
}
bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
-
#ifdef TOOLS_ENABLED
const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property);
@@ -304,14 +334,13 @@ bool GDScript::get_property_default_value(const StringName &p_property, Variant
}
ScriptInstance *GDScript::instance_create(Object *p_this) {
-
GDScript *top = this;
- while (top->_base)
+ while (top->_base) {
top = top->_base;
+ }
if (top->native.is_valid()) {
if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
-
if (EngineDebugger::is_active()) {
GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
}
@@ -335,24 +364,23 @@ PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this)
}
bool GDScript::instance_has(const Object *p_this) const {
-
MutexLock lock(GDScriptLanguage::singleton->lock);
return instances.has((Object *)p_this);
}
bool GDScript::has_source_code() const {
-
return source != "";
}
-String GDScript::get_source_code() const {
+String GDScript::get_source_code() const {
return source;
}
-void GDScript::set_source_code(const String &p_code) {
- if (source == p_code)
+void GDScript::set_source_code(const String &p_code) {
+ if (source == p_code) {
return;
+ }
source = p_code;
#ifdef TOOLS_ENABLED
source_changed_cache = true;
@@ -361,7 +389,6 @@ void GDScript::set_source_code(const String &p_code) {
#ifdef TOOLS_ENABLED
void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
-
if (base_cache.is_valid()) {
base_cache->_update_exports_values(values, propnames);
}
@@ -374,12 +401,194 @@ void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<Pro
propnames.push_back(E->get());
}
}
-#endif
-bool GDScript::_update_exports() {
+void GDScript::_add_doc(const DocData::ClassDoc &p_inner_class) {
+ if (_owner) {
+ _owner->_add_doc(p_inner_class);
+ } else {
+ for (int i = 0; i < docs.size(); i++) {
+ if (docs[i].name == p_inner_class.name) {
+ docs.remove(i);
+ break;
+ }
+ }
+ docs.append(p_inner_class);
+ }
+}
+
+void GDScript::_clear_doc() {
+ docs.clear();
+ doc = DocData::ClassDoc();
+}
+
+void GDScript::_update_doc() {
+ _clear_doc();
+
+ doc.script_path = "\"" + get_path().get_slice("://", 1) + "\"";
+ if (!name.is_empty()) {
+ doc.name = name;
+ } else {
+ doc.name = doc.script_path;
+ }
+
+ if (_owner) {
+ doc.name = _owner->doc.name + "." + doc.name;
+ doc.script_path = doc.script_path + "." + doc.name;
+ }
+
+ doc.is_script_doc = true;
+
+ if (base.is_valid() && base->is_valid()) {
+ if (base->doc.name != String()) {
+ doc.inherits = base->doc.name;
+ } else {
+ doc.inherits = base->get_instance_base_type();
+ }
+ } else if (native.is_valid()) {
+ doc.inherits = native->get_name();
+ }
+
+ doc.brief_description = doc_brief_description;
+ doc.description = doc_description;
+ doc.tutorials = doc_tutorials;
+
+ for (Map<String, DocData::EnumDoc>::Element *E = doc_enums.front(); E; E = E->next()) {
+ if (E->value().description != "") {
+ doc.enums[E->key()] = E->value().description;
+ }
+ }
+
+ List<MethodInfo> methods;
+ _get_script_method_list(&methods, false);
+ for (int i = 0; i < methods.size(); i++) {
+ // Ignore internal methods.
+ if (methods[i].name[0] == '@') {
+ continue;
+ }
+
+ DocData::MethodDoc method_doc;
+ const String &class_name = methods[i].name;
+ if (member_functions.has(class_name)) {
+ GDScriptFunction *fn = member_functions[class_name];
+
+ // Change class name if return type is script reference.
+ GDScriptDataType return_type = fn->get_return_type();
+ if (return_type.kind == GDScriptDataType::GDSCRIPT) {
+ methods[i].return_val.class_name = _get_gdscript_reference_class_name(Object::cast_to<GDScript>(return_type.script_type));
+ }
+
+ // Change class name if argumetn is script reference.
+ for (int j = 0; j < fn->get_argument_count(); j++) {
+ GDScriptDataType arg_type = fn->get_argument_type(j);
+ if (arg_type.kind == GDScriptDataType::GDSCRIPT) {
+ methods[i].arguments[j].class_name = _get_gdscript_reference_class_name(Object::cast_to<GDScript>(arg_type.script_type));
+ }
+ }
+ }
+ if (doc_functions.has(methods[i].name)) {
+ DocData::method_doc_from_methodinfo(method_doc, methods[i], doc_functions[methods[i].name]);
+ } else {
+ DocData::method_doc_from_methodinfo(method_doc, methods[i], String());
+ }
+ doc.methods.push_back(method_doc);
+ }
+
+ List<PropertyInfo> props;
+ _get_script_property_list(&props, false);
+ for (int i = 0; i < props.size(); i++) {
+ ScriptMemberInfo scr_member_info;
+ scr_member_info.propinfo = props[i];
+ scr_member_info.propinfo.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ if (member_indices.has(props[i].name)) {
+ const MemberInfo &mi = member_indices[props[i].name];
+ scr_member_info.setter = mi.setter;
+ scr_member_info.getter = mi.getter;
+ if (mi.data_type.kind == GDScriptDataType::GDSCRIPT) {
+ scr_member_info.propinfo.class_name = _get_gdscript_reference_class_name(
+ Object::cast_to<GDScript>(mi.data_type.script_type));
+ }
+ }
+ if (member_default_values.has(props[i].name)) {
+ scr_member_info.has_default_value = true;
+ scr_member_info.default_value = member_default_values[props[i].name];
+ }
+ if (doc_variables.has(props[i].name)) {
+ scr_member_info.doc_string = doc_variables[props[i].name];
+ }
+
+ DocData::PropertyDoc prop_doc;
+ DocData::property_doc_from_scriptmemberinfo(prop_doc, scr_member_info);
+ doc.properties.push_back(prop_doc);
+ }
+
+ List<MethodInfo> signals;
+ _get_script_signal_list(&signals, false);
+ for (int i = 0; i < signals.size(); i++) {
+ DocData::MethodDoc signal_doc;
+ if (doc_signals.has(signals[i].name)) {
+ DocData::signal_doc_from_methodinfo(signal_doc, signals[i], signals[i].name);
+ } else {
+ DocData::signal_doc_from_methodinfo(signal_doc, signals[i], String());
+ }
+ doc.signals.push_back(signal_doc);
+ }
+
+ for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
+ if (subclasses.has(E->key())) {
+ continue;
+ }
+
+ // Enums.
+ bool is_enum = false;
+ if (E->value().get_type() == Variant::DICTIONARY) {
+ if (doc_enums.has(E->key())) {
+ is_enum = true;
+ for (int i = 0; i < doc_enums[E->key()].values.size(); i++) {
+ doc_enums[E->key()].values.write[i].enumeration = E->key();
+ doc.constants.push_back(doc_enums[E->key()].values[i]);
+ }
+ }
+ }
+ if (!is_enum && doc_enums.has("@unnamed_enums")) {
+ for (int i = 0; i < doc_enums["@unnamed_enums"].values.size(); i++) {
+ if (E->key() == doc_enums["@unnamed_enums"].values[i].name) {
+ is_enum = true;
+ DocData::ConstantDoc constant_doc;
+ constant_doc.enumeration = "@unnamed_enums";
+ DocData::constant_doc_from_variant(constant_doc, E->key(), E->value(), doc_enums["@unnamed_enums"].values[i].description);
+ doc.constants.push_back(constant_doc);
+ break;
+ }
+ }
+ }
+ if (!is_enum) {
+ DocData::ConstantDoc constant_doc;
+ String doc_description;
+ if (doc_constants.has(E->key())) {
+ doc_description = doc_constants[E->key()];
+ }
+ DocData::constant_doc_from_variant(constant_doc, E->key(), E->value(), doc_description);
+ doc.constants.push_back(constant_doc);
+ }
+ }
+
+ for (Map<StringName, Ref<GDScript>>::Element *E = subclasses.front(); E; E = E->next()) {
+ E->get()->_update_doc();
+ }
+
+ _add_doc(doc);
+}
+#endif
+bool GDScript::_update_exports(bool *r_err, bool p_recursive_call) {
#ifdef TOOLS_ENABLED
+ static Vector<GDScript *> base_caches;
+ if (!p_recursive_call) {
+ base_caches.clear();
+ }
+ base_caches.append(this);
+
bool changed = false;
if (source_changed_cache) {
@@ -388,21 +597,20 @@ bool GDScript::_update_exports() {
String basedir = path;
- if (basedir == "")
+ if (basedir == "") {
basedir = get_path();
+ }
- if (basedir != "")
+ if (basedir != "") {
basedir = basedir.get_base_dir();
+ }
GDScriptParser parser;
- Error err = parser.parse(source, basedir, true, path);
+ GDScriptAnalyzer analyzer(&parser);
+ Error err = parser.parse(source, path, false);
- if (err == OK) {
-
- const GDScriptParser::Node *root = parser.get_parse_tree();
- ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, false);
-
- const GDScriptParser::ClassNode *c = static_cast<const GDScriptParser::ClassNode *>(root);
+ if (err == OK && analyzer.analyze() == OK) {
+ const GDScriptParser::ClassNode *c = parser.get_tree();
if (base_cache.is_valid()) {
base_cache->inheriters_cache.erase(get_instance_id());
@@ -411,32 +619,29 @@ bool GDScript::_update_exports() {
if (c->extends_used) {
String path = "";
- if (String(c->extends_file) != "" && String(c->extends_file) != get_path()) {
- path = c->extends_file;
+ if (String(c->extends_path) != "" && String(c->extends_path) != get_path()) {
+ path = c->extends_path;
if (path.is_rel_path()) {
-
String base = get_path();
if (base == "" || base.is_rel_path()) {
-
ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data());
} else {
path = base.get_base_dir().plus_file(path);
}
}
- } else if (c->extends_class.size() != 0) {
- String base = c->extends_class[0];
+ } else if (c->extends.size() != 0) {
+ const StringName &base = c->extends[0];
- if (ScriptServer::is_global_class(base))
+ if (ScriptServer::is_global_class(base)) {
path = ScriptServer::get_global_class_path(base);
+ }
}
if (path != "") {
if (path != get_path()) {
-
Ref<GDScript> bf = ResourceLoader::load(path);
if (bf.is_valid()) {
-
base_cache = bf;
bf->inheriters_cache.insert(get_instance_id());
}
@@ -448,19 +653,36 @@ bool GDScript::_update_exports() {
members_cache.clear();
member_default_values_cache.clear();
+ _signals.clear();
- for (int i = 0; i < c->variables.size(); i++) {
- if (c->variables[i]._export.type == Variant::NIL)
- continue;
-
- members_cache.push_back(c->variables[i]._export);
- member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value;
- }
+ for (int i = 0; i < c->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = c->members[i];
- _signals.clear();
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::VARIABLE: {
+ if (!member.variable->exported) {
+ continue;
+ }
- for (int i = 0; i < c->_signals.size(); i++) {
- _signals[c->_signals[i].name] = c->_signals[i].arguments;
+ members_cache.push_back(member.variable->export_info);
+ Variant default_value;
+ if (member.variable->initializer && member.variable->initializer->is_constant) {
+ default_value = member.variable->initializer->reduced_value;
+ }
+ member_default_values_cache[member.variable->identifier->name] = default_value;
+ } break;
+ case GDScriptParser::ClassNode::Member::SIGNAL: {
+ // TODO: Cache this in parser to avoid loops like this.
+ Vector<StringName> parameters_names;
+ parameters_names.resize(member.signal->parameters.size());
+ for (int j = 0; j < member.signal->parameters.size(); j++) {
+ parameters_names.write[j] = member.signal->parameters[j]->identifier->name;
+ }
+ _signals[member.signal->identifier->name] = parameters_names;
+ } break;
+ default:
+ break; // Nothing.
+ }
}
} else {
placeholder_fallback_enabled = true;
@@ -473,7 +695,24 @@ bool GDScript::_update_exports() {
placeholder_fallback_enabled = false;
if (base_cache.is_valid() && base_cache->is_valid()) {
- if (base_cache->_update_exports()) {
+ for (int i = 0; i < base_caches.size(); i++) {
+ if (base_caches[i] == base_cache.ptr()) {
+ if (r_err) {
+ *r_err = true;
+ }
+ valid = false; // to show error in the editor
+ base_cache->valid = false;
+ base_cache->inheriters_cache.clear(); // to prevent future stackoverflows
+ base_cache.unref();
+ base.unref();
+ _base = nullptr;
+ ERR_FAIL_V_MSG(false, "Cyclic inheritance in script class.");
+ }
+ }
+ if (base_cache->_update_exports(r_err, true)) {
+ if (r_err && *r_err) {
+ return false;
+ }
changed = true;
}
}
@@ -498,18 +737,22 @@ bool GDScript::_update_exports() {
}
void GDScript::update_exports() {
-
#ifdef TOOLS_ENABLED
- _update_exports();
+ bool cyclic_error = false;
+ _update_exports(&cyclic_error);
+ if (cyclic_error) {
+ return;
+ }
Set<ObjectID> copy = inheriters_cache; //might get modified
for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
Object *id = ObjectDB::get_instance(E->get());
GDScript *s = Object::cast_to<GDScript>(id);
- if (!s)
+ if (!s) {
continue;
+ }
s->update_exports();
}
@@ -517,16 +760,13 @@ void GDScript::update_exports() {
}
void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) {
-
p_sc->path = p_path;
for (Map<StringName, Ref<GDScript>>::Element *E = p_sc->subclasses.front(); E; E = E->next()) {
-
_set_subclass_path(E->get(), p_path);
}
}
Error GDScript::reload(bool p_keep_state) {
-
bool has_instances;
{
MutexLock lock(GDScriptLanguage::singleton->lock);
@@ -538,40 +778,75 @@ Error GDScript::reload(bool p_keep_state) {
String basedir = path;
- if (basedir == "")
+ if (basedir == "") {
basedir = get_path();
+ }
- if (basedir != "")
+ if (basedir != "") {
basedir = basedir.get_base_dir();
+ }
if (source.find("%BASE%") != -1) {
//loading a template, don't parse
return OK;
}
+ {
+ String source_path = path;
+ if (source_path.is_empty()) {
+ source_path = get_path();
+ }
+ if (!source_path.is_empty()) {
+ MutexLock lock(GDScriptCache::singleton->lock);
+ if (!GDScriptCache::singleton->shallow_gdscript_cache.has(source_path)) {
+ GDScriptCache::singleton->shallow_gdscript_cache[source_path] = this;
+ }
+ }
+ }
+
valid = false;
GDScriptParser parser;
- Error err = parser.parse(source, basedir, false, path);
+ Error err = parser.parse(source, path, false);
+ if (err) {
+ if (EngineDebugger::is_active()) {
+ GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
+ }
+ // TODO: Show all error messages.
+ _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_errors().front()->get().line, ("Parse Error: " + parser.get_errors().front()->get().message).utf8().get_data(), ERR_HANDLER_SCRIPT);
+ ERR_FAIL_V(ERR_PARSE_ERROR);
+ }
+
+ GDScriptAnalyzer analyzer(&parser);
+ err = analyzer.analyze();
+
if (err) {
if (EngineDebugger::is_active()) {
- GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error());
+ GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_errors().front()->get().line, "Parser Error: " + parser.get_errors().front()->get().message);
+ }
+
+ const List<GDScriptParser::ParserError>::Element *e = parser.get_errors().front();
+ while (e != nullptr) {
+ _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), e->get().line, ("Parse Error: " + e->get().message).utf8().get_data(), ERR_HANDLER_SCRIPT);
+ e = e->next();
}
- _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
ERR_FAIL_V(ERR_PARSE_ERROR);
}
- bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script();
+ bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool();
GDScriptCompiler compiler;
err = compiler.compile(&parser, this, p_keep_state);
- if (err) {
+#ifdef TOOLS_ENABLED
+ _update_doc();
+#endif
+ if (err) {
if (can_run) {
if (EngineDebugger::is_active()) {
GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error());
}
- _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
+ _err_print_error("GDScript::reload", path.is_empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
ERR_FAIL_V(ERR_COMPILATION_FAILED);
} else {
return err;
@@ -582,7 +857,7 @@ Error GDScript::reload(bool p_keep_state) {
const GDScriptWarning &warning = E->get();
if (EngineDebugger::is_active()) {
Vector<ScriptLanguage::StackInfo> si;
- EngineDebugger::get_script_debugger()->send_error("", get_path(), warning.line, warning.get_name(), warning.get_message(), ERR_HANDLER_WARNING, si);
+ EngineDebugger::get_script_debugger()->send_error("", get_path(), warning.start_line, warning.get_name(), warning.get_message(), ERR_HANDLER_WARNING, si);
}
}
#endif
@@ -590,7 +865,6 @@ Error GDScript::reload(bool p_keep_state) {
valid = true;
for (Map<StringName, Ref<GDScript>>::Element *E = subclasses.front(); E; E = E->next()) {
-
_set_subclass_path(E->get(), path);
}
@@ -600,12 +874,10 @@ Error GDScript::reload(bool p_keep_state) {
}
ScriptLanguage *GDScript::get_language() const {
-
return GDScriptLanguage::get_singleton();
}
void GDScript::get_constants(Map<StringName, Variant> *p_constants) {
-
if (p_constants) {
for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
(*p_constants)[E->key()] = E->value();
@@ -635,12 +907,16 @@ uint16_t GDScript::get_rpc_method_id(const StringName &p_method) const {
}
StringName GDScript::get_rpc_method(const uint16_t p_rpc_method_id) const {
- if (p_rpc_method_id >= rpc_functions.size()) return StringName();
+ if (p_rpc_method_id >= rpc_functions.size()) {
+ return StringName();
+ }
return rpc_functions[p_rpc_method_id].name;
}
MultiplayerAPI::RPCMode GDScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const {
- if (p_rpc_method_id >= rpc_functions.size()) return MultiplayerAPI::RPC_MODE_DISABLED;
+ if (p_rpc_method_id >= rpc_functions.size()) {
+ return MultiplayerAPI::RPC_MODE_DISABLED;
+ }
return rpc_functions[p_rpc_method_id].mode;
}
@@ -662,12 +938,16 @@ uint16_t GDScript::get_rset_property_id(const StringName &p_variable) const {
}
StringName GDScript::get_rset_property(const uint16_t p_rset_member_id) const {
- if (p_rset_member_id >= rpc_variables.size()) return StringName();
+ if (p_rset_member_id >= rpc_variables.size()) {
+ return StringName();
+ }
return rpc_variables[p_rset_member_id].name;
}
MultiplayerAPI::RPCMode GDScript::get_rset_mode_by_id(const uint16_t p_rset_member_id) const {
- if (p_rset_member_id >= rpc_variables.size()) return MultiplayerAPI::RPC_MODE_DISABLED;
+ if (p_rset_member_id >= rpc_variables.size()) {
+ return MultiplayerAPI::RPC_MODE_DISABLED;
+ }
return rpc_variables[p_rset_member_id].mode;
}
@@ -676,13 +956,10 @@ MultiplayerAPI::RPCMode GDScript::get_rset_mode(const StringName &p_variable) co
}
Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
GDScript *top = this;
while (top) {
-
Map<StringName, GDScriptFunction *>::Element *E = top->member_functions.find(p_method);
if (E) {
-
ERR_FAIL_COND_V_MSG(!E->get()->is_static(), Variant(), "Can't call non-static function '" + String(p_method) + "' in script.");
return E->get()->call(nullptr, p_args, p_argcount, r_error);
@@ -696,16 +973,12 @@ Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p
}
bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
-
{
-
const GDScript *top = this;
while (top) {
-
{
const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
if (E) {
-
r_ret = E->get();
return true;
}
@@ -714,7 +987,6 @@ bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
{
const Map<StringName, Ref<GDScript>>::Element *E = subclasses.find(p_name);
if (E) {
-
r_ret = E->get();
return true;
}
@@ -723,7 +995,6 @@ bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
}
if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
-
r_ret = get_source_code();
return true;
}
@@ -731,120 +1002,42 @@ bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
return false;
}
-bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
+bool GDScript::_set(const StringName &p_name, const Variant &p_value) {
if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
-
set_source_code(p_value);
reload();
- } else
+ } else {
return false;
+ }
return true;
}
void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const {
-
p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
}
void GDScript::_bind_methods() {
-
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo("new"));
ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
}
Vector<uint8_t> GDScript::get_as_byte_code() const {
-
- GDScriptTokenizerBuffer tokenizer;
- return tokenizer.parse_code_string(source);
+ return Vector<uint8_t>();
};
+// TODO: Fully remove this. There's not this kind of "bytecode" anymore.
Error GDScript::load_byte_code(const String &p_path) {
-
- Vector<uint8_t> bytecode;
-
- if (p_path.ends_with("gde")) {
-
- FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
- ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN);
-
- FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
- ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN);
-
- Vector<uint8_t> key;
- key.resize(32);
- for (int i = 0; i < key.size(); i++) {
- key.write[i] = script_encryption_key[i];
- }
-
- Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
-
- if (err) {
- fa->close();
- memdelete(fa);
- memdelete(fae);
-
- ERR_FAIL_COND_V(err, err);
- }
-
- bytecode.resize(fae->get_len());
- fae->get_buffer(bytecode.ptrw(), bytecode.size());
- fae->close();
- memdelete(fae);
-
- } else {
-
- bytecode = FileAccess::get_file_as_array(p_path);
- }
-
- ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
- path = p_path;
-
- String basedir = path;
-
- if (basedir == "")
- basedir = get_path();
-
- if (basedir != "")
- basedir = basedir.get_base_dir();
-
- valid = false;
- GDScriptParser parser;
- Error err = parser.parse_bytecode(bytecode, basedir, get_path());
- if (err) {
- _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
- ERR_FAIL_V(ERR_PARSE_ERROR);
- }
-
- GDScriptCompiler compiler;
- err = compiler.compile(&parser, this);
-
- if (err) {
- _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT);
- ERR_FAIL_V(ERR_COMPILATION_FAILED);
- }
-
- valid = true;
-
- for (Map<StringName, Ref<GDScript>>::Element *E = subclasses.front(); E; E = E->next()) {
-
- _set_subclass_path(E->get(), path);
- }
-
- _init_rpc_methods_properties();
-
- return OK;
+ return ERR_COMPILATION_FAILED;
}
Error GDScript::load_source_code(const String &p_path) {
-
Vector<uint8_t> sourcef;
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
-
ERR_FAIL_COND_V(err, err);
}
@@ -859,7 +1052,6 @@ Error GDScript::load_source_code(const String &p_path) {
String s;
if (s.parse_utf8((const char *)w)) {
-
ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
}
@@ -872,23 +1064,20 @@ Error GDScript::load_source_code(const String &p_path) {
}
const Map<StringName, GDScriptFunction *> &GDScript::debug_get_member_functions() const {
-
return member_functions;
}
StringName GDScript::debug_get_member_by_index(int p_idx) const {
-
for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
-
- if (E->get().index == p_idx)
+ if (E->get().index == p_idx) {
return E->key();
+ }
}
return "<error>";
}
Ref<GDScript> GDScript::get_base() const {
-
return base;
}
@@ -911,8 +1100,9 @@ bool GDScript::inherits_script(const Ref<Script> &p_script) const {
}
bool GDScript::has_script_signal(const StringName &p_signal) const {
- if (_signals.has(p_signal))
+ if (_signals.has(p_signal)) {
return true;
+ }
if (base.is_valid()) {
return base->has_script_signal(p_signal);
}
@@ -923,10 +1113,9 @@ bool GDScript::has_script_signal(const StringName &p_signal) const {
#endif
return false;
}
-void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
+void GDScript::_get_script_signal_list(List<MethodInfo> *r_list, bool p_include_base) const {
for (const Map<StringName, Vector<StringName>>::Element *E = _signals.front(); E; E = E->next()) {
-
MethodInfo mi;
mi.name = E->key();
for (int i = 0; i < E->get().size(); i++) {
@@ -934,23 +1123,45 @@ void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
arg.name = E->get()[i];
mi.arguments.push_back(arg);
}
- r_signals->push_back(mi);
+ r_list->push_back(mi);
+ }
+
+ if (!p_include_base) {
+ return;
}
if (base.is_valid()) {
- base->get_script_signal_list(r_signals);
+ base->get_script_signal_list(r_list);
}
#ifdef TOOLS_ENABLED
else if (base_cache.is_valid()) {
- base_cache->get_script_signal_list(r_signals);
+ base_cache->get_script_signal_list(r_list);
}
#endif
}
+void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
+ _get_script_signal_list(r_signals, true);
+}
+
+String GDScript::_get_gdscript_reference_class_name(const GDScript *p_gdscript) {
+ ERR_FAIL_NULL_V(p_gdscript, String());
+
+ String class_name;
+ while (p_gdscript) {
+ if (class_name == "") {
+ class_name = p_gdscript->get_script_class_name();
+ } else {
+ class_name = p_gdscript->get_script_class_name() + "." + class_name;
+ }
+ p_gdscript = p_gdscript->_owner;
+ }
+ return class_name;
+}
+
GDScript::GDScript() :
script_list(this) {
-
valid = false;
subclass_count = 0;
initializer = nullptr;
@@ -995,8 +1206,9 @@ void GDScript::_save_orphaned_subclasses() {
for (int i = 0; i < weak_subclasses.size(); i++) {
ClassRefWithName subclass = weak_subclasses[i];
Object *obj = ObjectDB::get_instance(subclass.id);
- if (!obj)
+ if (!obj) {
continue;
+ }
// subclass is not released
GDScriptLanguage::get_singleton()->add_orphan_subclass(subclass.fully_qualified_name, subclass.id);
}
@@ -1037,13 +1249,15 @@ void GDScript::_init_rpc_methods_properties() {
}
}
- if (cscript != this)
+ if (cscript != this) {
sub_E = sub_E->next();
+ }
- if (sub_E)
+ if (sub_E) {
cscript = sub_E->get().ptr();
- else
+ } else {
cscript = nullptr;
+ }
}
// Sort so we are 100% that they are always the same.
@@ -1052,12 +1266,34 @@ void GDScript::_init_rpc_methods_properties() {
}
GDScript::~GDScript() {
+ {
+ MutexLock lock(GDScriptLanguage::get_singleton()->lock);
+
+ while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
+ // Order matters since clearing the stack may already cause
+ // the GDSCriptFunctionState to be destroyed and thus removed from the list.
+ pending_func_states.remove(E);
+ E->self()->_clear_stack();
+ }
+ }
+
for (Map<StringName, GDScriptFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
memdelete(E->get());
}
+ if (GDScriptCache::singleton) { // Cache may have been already destroyed at engine shutdown.
+ GDScriptCache::remove_script(get_path());
+ }
+
_save_orphaned_subclasses();
+#ifdef TOOLS_ENABLED
+ // Clearing inner class doc, script doc only cleared when the script source deleted.
+ if (_owner) {
+ _clear_doc();
+ }
+#endif
+
#ifdef DEBUG_ENABLED
{
MutexLock lock(GDScriptLanguage::get_singleton()->lock);
@@ -1072,7 +1308,6 @@ GDScript::~GDScript() {
//////////////////////////////
bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
-
//member
{
const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
@@ -1090,7 +1325,8 @@ bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
// Try conversion
Callable::CallError ce;
const Variant *value = &p_value;
- Variant converted = Variant::construct(member->data_type.builtin_type, &value, 1, ce);
+ Variant converted;
+ Variant::construct(member->data_type.builtin_type, converted, &value, 1, ce);
if (ce.error == Callable::CallError::CALL_OK) {
members.write[member->index] = converted;
return true;
@@ -1107,17 +1343,16 @@ bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
GDScript *sptr = script.ptr();
while (sptr) {
-
Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
if (E) {
-
Variant name = p_name;
const Variant *args[2] = { &name, &p_value };
Callable::CallError err;
Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
- if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
+ if (err.error == Callable::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) {
return true;
+ }
}
sptr = sptr->_base;
}
@@ -1126,10 +1361,8 @@ bool GDScriptInstance::set(const StringName &p_name, const Variant &p_value) {
}
bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
-
const GDScript *sptr = script.ptr();
while (sptr) {
-
{
const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
if (E) {
@@ -1146,7 +1379,6 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
}
{
-
const GDScript *sl = sptr;
while (sl) {
const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
@@ -1159,9 +1391,34 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
}
{
+ // Signals.
+ const GDScript *sl = sptr;
+ while (sl) {
+ const Map<StringName, Vector<StringName>>::Element *E = sl->_signals.find(p_name);
+ if (E) {
+ r_ret = Signal(this->owner, E->key());
+ return true; //index found
+ }
+ sl = sl->_base;
+ }
+ }
+
+ {
+ // Methods.
+ const GDScript *sl = sptr;
+ while (sl) {
+ const Map<StringName, GDScriptFunction *>::Element *E = sl->member_functions.find(p_name);
+ if (E) {
+ r_ret = Callable(this->owner, E->key());
+ return true; //index found
+ }
+ sl = sl->_base;
+ }
+ }
+
+ {
const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
if (E) {
-
Variant name = p_name;
const Variant *args[1] = { &name };
@@ -1180,20 +1437,20 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
}
Variant::Type GDScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
-
const GDScript *sptr = script.ptr();
while (sptr) {
-
if (sptr->member_info.has(p_name)) {
- if (r_is_valid)
+ if (r_is_valid) {
*r_is_valid = true;
+ }
return sptr->member_info[p_name].type;
}
sptr = sptr->_base;
}
- if (r_is_valid)
+ if (r_is_valid) {
*r_is_valid = false;
+ }
return Variant::NIL;
}
@@ -1204,19 +1461,15 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
List<PropertyInfo> props;
while (sptr) {
-
const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
if (E) {
-
Callable::CallError err;
Variant ret = const_cast<GDScriptFunction *>(E->get())->call(const_cast<GDScriptInstance *>(this), nullptr, 0, err);
if (err.error == Callable::CallError::CALL_OK) {
-
ERR_FAIL_COND_MSG(ret.get_type() != Variant::ARRAY, "Wrong type for _get_property_list, must be an array of dictionaries.");
Array arr = ret;
for (int i = 0; i < arr.size(); i++) {
-
Dictionary d = arr[i];
ERR_CONTINUE(!d.has("name"));
ERR_CONTINUE(!d.has("type"));
@@ -1225,12 +1478,15 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
pinfo.name = d["name"];
ERR_CONTINUE(pinfo.name == "");
- if (d.has("hint"))
+ if (d.has("hint")) {
pinfo.hint = PropertyHint(d["hint"].operator int());
- if (d.has("hint_string"))
+ }
+ if (d.has("hint_string")) {
pinfo.hint_string = d["hint_string"];
- if (d.has("usage"))
+ }
+ if (d.has("usage")) {
pinfo.usage = d["usage"];
+ }
props.push_back(pinfo);
}
@@ -1241,7 +1497,6 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
Vector<_GDScriptMemberSort> msort;
for (Map<StringName, PropertyInfo>::Element *F = sptr->member_info.front(); F; F = F->next()) {
-
_GDScriptMemberSort ms;
ERR_CONTINUE(!sptr->member_indices.has(F->key()));
ms.index = sptr->member_indices[F->key()].index;
@@ -1252,7 +1507,6 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
msort.sort();
msort.invert();
for (int i = 0; i < msort.size(); i++) {
-
props.push_front(sptr->member_info[msort[i].name]);
}
@@ -1260,23 +1514,20 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const
}
for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
-
p_properties->push_back(E->get());
}
}
void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
-
const GDScript *sptr = script.ptr();
while (sptr) {
-
for (Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) {
-
MethodInfo mi;
mi.name = E->key();
mi.flags |= METHOD_FLAG_FROM_SCRIPT;
- for (int i = 0; i < E->get()->get_argument_count(); i++)
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
+ }
p_list->push_back(mi);
}
sptr = sptr->_base;
@@ -1284,19 +1535,19 @@ void GDScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
}
bool GDScriptInstance::has_method(const StringName &p_method) const {
-
const GDScript *sptr = script.ptr();
while (sptr) {
const Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
- if (E)
+ if (E) {
return true;
+ }
sptr = sptr->_base;
}
return false;
}
-Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
+Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
GDScript *sptr = script.ptr();
while (sptr) {
Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
@@ -1309,42 +1560,7 @@ Variant GDScriptInstance::call(const StringName &p_method, const Variant **p_arg
return Variant();
}
-void GDScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- GDScript *sptr = script.ptr();
- Callable::CallError ce;
-
- while (sptr) {
- Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
- if (E) {
- E->get()->call(this, p_args, p_argcount, ce);
- }
- sptr = sptr->_base;
- }
-}
-
-void GDScriptInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- if (sptr->_base)
- _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
-
- Callable::CallError ce;
-
- Map<StringName, GDScriptFunction *>::Element *E = sptr->member_functions.find(p_method);
- if (E) {
- E->get()->call(this, p_args, p_argcount, ce);
- }
-}
-
-void GDScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- if (script.ptr()) {
- _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
- }
-}
-
void GDScriptInstance::notification(int p_notification) {
-
//notification is not virtual, it gets called at ALL levels just like in C.
Variant value = p_notification;
const Variant *args[1] = { &value };
@@ -1369,27 +1585,28 @@ String GDScriptInstance::to_string(bool *r_valid) {
Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce);
if (ce.error == Callable::CallError::CALL_OK) {
if (ret.get_type() != Variant::STRING) {
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String.");
}
- if (r_valid)
+ if (r_valid) {
*r_valid = true;
+ }
return ret.operator String();
}
}
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
Ref<Script> GDScriptInstance::get_script() const {
-
return script;
}
ScriptLanguage *GDScriptInstance::get_language() {
-
return GDScriptLanguage::get_singleton();
}
@@ -1434,7 +1651,6 @@ MultiplayerAPI::RPCMode GDScriptInstance::get_rset_mode(const StringName &p_vari
}
void GDScriptInstance::reload_members() {
-
#ifdef DEBUG_ENABLED
members.resize(script->member_indices.size()); //resize
@@ -1444,7 +1660,6 @@ void GDScriptInstance::reload_members() {
//pass the values to the new indices
for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
-
if (member_indices_cache.has(E->key())) {
Variant value = members[member_indices_cache[E->key()]];
new_members.write[E->get().index] = value;
@@ -1457,7 +1672,6 @@ void GDScriptInstance::reload_members() {
//pass the values to the new indices
member_indices_cache.clear();
for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
-
member_indices_cache[E->key()] = E->get().index;
}
@@ -1470,9 +1684,16 @@ GDScriptInstance::GDScriptInstance() {
}
GDScriptInstance::~GDScriptInstance() {
- if (script.is_valid() && owner) {
- MutexLock lock(GDScriptLanguage::singleton->lock);
+ MutexLock lock(GDScriptLanguage::get_singleton()->lock);
+ while (SelfList<GDScriptFunctionState> *E = pending_func_states.first()) {
+ // Order matters since clearing the stack may already cause
+ // the GDSCriptFunctionState to be destroyed and thus removed from the list.
+ pending_func_states.remove(E);
+ E->self()->_clear_stack();
+ }
+
+ if (script.is_valid() && owner) {
script->instances.erase(owner);
}
}
@@ -1482,14 +1703,12 @@ GDScriptInstance::~GDScriptInstance() {
GDScriptLanguage *GDScriptLanguage::singleton = nullptr;
String GDScriptLanguage::get_name() const {
-
return "GDScript";
}
/* LANGUAGE FUNCTIONS */
void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
-
if (globals.has(p_name)) {
//overwrite existing
global_array.write[globals[p_name]] = p_value;
@@ -1501,7 +1720,6 @@ void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_va
}
void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
-
_add_global(p_variable, p_value);
}
@@ -1515,12 +1733,10 @@ void GDScriptLanguage::remove_named_global_constant(const StringName &p_name) {
}
void GDScriptLanguage::init() {
-
//populate global constants
- int gcc = GlobalConstants::get_global_constant_count();
+ int gcc = CoreConstants::get_global_constant_count();
for (int i = 0; i < gcc; i++) {
-
- _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
+ _add_global(StaticCString::create(CoreConstants::get_global_constant_name(i)), CoreConstants::get_global_constant_value(i));
}
_add_global(StaticCString::create("PI"), Math_PI);
@@ -1533,14 +1749,15 @@ void GDScriptLanguage::init() {
List<StringName> class_list;
ClassDB::get_class_list(&class_list);
for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
-
StringName n = E->get();
String s = String(n);
- if (s.begins_with("_"))
+ if (s.begins_with("_")) {
n = s.substr(1, s.length());
+ }
- if (globals.has(n))
+ if (globals.has(n)) {
continue;
+ }
Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(E->get()));
_add_global(n, nc);
}
@@ -1550,29 +1767,27 @@ void GDScriptLanguage::init() {
List<Engine::Singleton> singletons;
Engine::get_singleton()->get_singletons(&singletons);
for (List<Engine::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
-
_add_global(E->get().name, E->get().ptr);
}
}
String GDScriptLanguage::get_type() const {
-
return "GDScript";
}
-String GDScriptLanguage::get_extension() const {
+String GDScriptLanguage::get_extension() const {
return "gd";
}
-Error GDScriptLanguage::execute_file(const String &p_path) {
+Error GDScriptLanguage::execute_file(const String &p_path) {
// ??
return OK;
}
+
void GDScriptLanguage::finish() {
}
void GDScriptLanguage::profiling_start() {
-
#ifdef DEBUG_ENABLED
MutexLock lock(this->lock);
@@ -1595,7 +1810,6 @@ void GDScriptLanguage::profiling_start() {
}
void GDScriptLanguage::profiling_stop() {
-
#ifdef DEBUG_ENABLED
MutexLock lock(this->lock);
@@ -1604,7 +1818,6 @@ void GDScriptLanguage::profiling_stop() {
}
int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
-
int current = 0;
#ifdef DEBUG_ENABLED
@@ -1612,8 +1825,9 @@ int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,
SelfList<GDScriptFunction> *elem = function_list.first();
while (elem) {
- if (current >= p_info_max)
+ if (current >= p_info_max) {
break;
+ }
p_info_arr[current].call_count = elem->self()->profile.call_count;
p_info_arr[current].self_time = elem->self()->profile.self_time;
p_info_arr[current].total_time = elem->self()->profile.total_time;
@@ -1627,7 +1841,6 @@ int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,
}
int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
-
int current = 0;
#ifdef DEBUG_ENABLED
@@ -1635,8 +1848,9 @@ int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_
SelfList<GDScriptFunction> *elem = function_list.first();
while (elem) {
- if (current >= p_info_max)
+ if (current >= p_info_max) {
break;
+ }
if (elem->self()->profile.last_frame_call_count > 0) {
p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count;
p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time;
@@ -1652,12 +1866,11 @@ int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_
}
struct GDScriptDepSort {
-
//must support sorting so inheritance works properly (parent must be reloaded first)
bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const {
-
- if (A == B)
+ if (A == B) {
return false; //shouldn't happen but..
+ }
const GDScript *I = B->get_base().ptr();
while (I) {
if (I == A.ptr()) {
@@ -1673,7 +1886,6 @@ struct GDScriptDepSort {
};
void GDScriptLanguage::reload_all_scripts() {
-
#ifdef DEBUG_ENABLED
print_verbose("GDScript: Reloading all scripts");
List<Ref<GDScript>> scripts;
@@ -1695,7 +1907,6 @@ void GDScriptLanguage::reload_all_scripts() {
scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
for (List<Ref<GDScript>>::Element *E = scripts.front(); E; E = E->next()) {
-
print_verbose("GDScript: Reloading: " + E->get()->get_path());
E->get()->load_source_code(E->get()->get_path());
E->get()->reload(true);
@@ -1704,7 +1915,6 @@ void GDScriptLanguage::reload_all_scripts() {
}
void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
-
#ifdef DEBUG_ENABLED
List<Ref<GDScript>> scripts;
@@ -1714,7 +1924,6 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
SelfList<GDScript> *elem = script_list.first();
while (elem) {
if (elem->self()->get_path().is_resource_file()) {
-
scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
}
elem = elem->next();
@@ -1730,16 +1939,15 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
for (List<Ref<GDScript>>::Element *E = scripts.front(); E; E = E->next()) {
-
bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
- if (!reload)
+ if (!reload) {
continue;
+ }
to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant>>>());
if (!p_soft_reload) {
-
//save state and remove script from instances
Map<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[E->get()];
@@ -1748,7 +1956,6 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
//save instance info
List<Pair<StringName, Variant>> state;
if (obj->get_script_instance()) {
-
obj->get_script_instance()->get_property_state(state);
map[obj->get_instance_id()] = state;
obj->set_script(Variant());
@@ -1763,7 +1970,6 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
//save instance info
if (obj->get_script_instance()) {
-
map.insert(obj->get_instance_id(), List<Pair<StringName, Variant>>());
List<Pair<StringName, Variant>> &state = map[obj->get_instance_id()];
obj->get_script_instance()->get_property_state(state);
@@ -1783,18 +1989,17 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
}
for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant>>>>::Element *E = to_reload.front(); E; E = E->next()) {
-
Ref<GDScript> scr = E->key();
scr->reload(p_soft_reload);
//restore state if saved
for (Map<ObjectID, List<Pair<StringName, Variant>>>::Element *F = E->get().front(); F; F = F->next()) {
-
List<Pair<StringName, Variant>> &saved_state = F->get();
Object *obj = ObjectDB::get_instance(F->key());
- if (!obj)
+ if (!obj) {
continue;
+ }
if (!p_soft_reload) {
//clear it just in case (may be a pending reload state)
@@ -1833,7 +2038,6 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so
}
void GDScriptLanguage::frame() {
-
calls = 0;
#ifdef DEBUG_ENABLED
@@ -1857,7 +2061,7 @@ void GDScriptLanguage::frame() {
/* EDITOR FUNCTIONS */
void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
-
+ // TODO: Add annotations here?
static const char *_reserved_words[] = {
// operators
"and",
@@ -1880,6 +2084,7 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
// functions
"as",
"assert",
+ "await",
"breakpoint",
"class",
"class_name",
@@ -1887,15 +2092,13 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
"is",
"func",
"preload",
- "setget",
"signal",
- "tool",
+ "super",
+ "trait",
"yield",
// var
"const",
"enum",
- "export",
- "onready",
"static",
"var",
// control flow
@@ -1909,35 +2112,29 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
"return",
"match",
"while",
- "remote",
- "master",
- "puppet",
- "remotesync",
- "mastersync",
- "puppetsync",
nullptr
};
const char **w = _reserved_words;
while (*w) {
-
p_words->push_back(*w);
w++;
}
- for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
- p_words->push_back(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i)));
+ List<StringName> functions;
+ GDScriptUtilityFunctions::get_function_list(&functions);
+
+ for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) {
+ p_words->push_back(String(E->get()));
}
}
bool GDScriptLanguage::handles_global_class_type(const String &p_type) const {
-
return p_type == "GDScript";
}
String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
-
Vector<uint8_t> sourcef;
Error err;
FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
@@ -1948,60 +2145,61 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
String source = f->get_as_utf8_string();
GDScriptParser parser;
- parser.parse(source, p_path.get_base_dir(), true, p_path, false, nullptr, true);
-
- if (parser.get_parse_tree() && parser.get_parse_tree()->type == GDScriptParser::Node::TYPE_CLASS) {
+ err = parser.parse(source, p_path, false);
- const GDScriptParser::ClassNode *c = static_cast<const GDScriptParser::ClassNode *>(parser.get_parse_tree());
+ // TODO: Simplify this code by using the analyzer to get full inheritance.
+ if (err == OK) {
+ const GDScriptParser::ClassNode *c = parser.get_tree();
if (r_icon_path) {
- if (c->icon_path.empty() || c->icon_path.is_abs_path())
+ if (c->icon_path.is_empty() || c->icon_path.is_abs_path()) {
*r_icon_path = c->icon_path;
- else if (c->icon_path.is_rel_path())
+ } else if (c->icon_path.is_rel_path()) {
*r_icon_path = p_path.get_base_dir().plus_file(c->icon_path).simplify_path();
+ }
}
if (r_base_type) {
-
const GDScriptParser::ClassNode *subclass = c;
String path = p_path;
GDScriptParser subparser;
while (subclass) {
if (subclass->extends_used) {
- if (subclass->extends_file) {
- if (subclass->extends_class.size() == 0) {
- get_global_class_name(subclass->extends_file, r_base_type);
+ if (!subclass->extends_path.is_empty()) {
+ if (subclass->extends.size() == 0) {
+ get_global_class_name(subclass->extends_path, r_base_type);
subclass = nullptr;
break;
} else {
- Vector<StringName> extend_classes = subclass->extends_class;
+ Vector<StringName> extend_classes = subclass->extends;
- FileAccessRef subfile = FileAccess::open(subclass->extends_file, FileAccess::READ);
+ FileAccessRef subfile = FileAccess::open(subclass->extends_path, FileAccess::READ);
if (!subfile) {
break;
}
String subsource = subfile->get_as_utf8_string();
- if (subsource.empty()) {
+ if (subsource.is_empty()) {
break;
}
- String subpath = subclass->extends_file;
+ String subpath = subclass->extends_path;
if (subpath.is_rel_path()) {
subpath = path.get_base_dir().plus_file(subpath).simplify_path();
}
- if (OK != subparser.parse(subsource, subpath.get_base_dir(), true, subpath, false, nullptr, true)) {
+ if (OK != subparser.parse(subsource, subpath, false)) {
break;
}
path = subpath;
- if (!subparser.get_parse_tree() || subparser.get_parse_tree()->type != GDScriptParser::Node::TYPE_CLASS) {
- break;
- }
- subclass = static_cast<const GDScriptParser::ClassNode *>(subparser.get_parse_tree());
+ subclass = subparser.get_tree();
while (extend_classes.size() > 0) {
bool found = false;
- for (int i = 0; i < subclass->subclasses.size(); i++) {
- const GDScriptParser::ClassNode *inner_class = subclass->subclasses[i];
- if (inner_class->name == extend_classes[0]) {
+ for (int i = 0; i < subclass->members.size(); i++) {
+ if (subclass->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
+ continue;
+ }
+
+ const GDScriptParser::ClassNode *inner_class = subclass->members[i].m_class;
+ if (inner_class->identifier->name == extend_classes[0]) {
extend_classes.remove(0);
found = true;
subclass = inner_class;
@@ -2014,8 +2212,8 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
}
}
}
- } else if (subclass->extends_class.size() == 1) {
- *r_base_type = subclass->extends_class[0];
+ } else if (subclass->extends.size() == 1) {
+ *r_base_type = subclass->extends[0];
subclass = nullptr;
} else {
break;
@@ -2026,183 +2224,13 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b
}
}
}
- return c->name;
+ return c->identifier != nullptr ? String(c->identifier->name) : String();
}
return String();
}
-#ifdef DEBUG_ENABLED
-String GDScriptWarning::get_message() const {
-
-#define CHECK_SYMBOLS(m_amount) ERR_FAIL_COND_V(symbols.size() < m_amount, String());
-
- switch (code) {
- case UNASSIGNED_VARIABLE_OP_ASSIGN: {
- CHECK_SYMBOLS(1);
- return "Using assignment with operation but the variable '" + symbols[0] + "' was not previously assigned a value.";
- } break;
- case UNASSIGNED_VARIABLE: {
- CHECK_SYMBOLS(1);
- return "The variable '" + symbols[0] + "' was used but never assigned a value.";
- } break;
- case UNUSED_VARIABLE: {
- CHECK_SYMBOLS(1);
- return "The local variable '" + symbols[0] + "' is declared but never used in the block. If this is intended, prefix it with an underscore: '_" + symbols[0] + "'";
- } break;
- case SHADOWED_VARIABLE: {
- CHECK_SYMBOLS(2);
- return "The local variable '" + symbols[0] + "' is shadowing an already-defined variable at line " + symbols[1] + ".";
- } break;
- case UNUSED_CLASS_VARIABLE: {
- CHECK_SYMBOLS(1);
- return "The class variable '" + symbols[0] + "' is declared but never used in the script.";
- } break;
- case UNUSED_ARGUMENT: {
- CHECK_SYMBOLS(2);
- return "The argument '" + symbols[1] + "' is never used in the function '" + symbols[0] + "'. If this is intended, prefix it with an underscore: '_" + symbols[1] + "'";
- } break;
- case UNREACHABLE_CODE: {
- CHECK_SYMBOLS(1);
- return "Unreachable code (statement after return) in function '" + symbols[0] + "()'.";
- } break;
- case STANDALONE_EXPRESSION: {
- return "Standalone expression (the line has no effect).";
- } break;
- case VOID_ASSIGNMENT: {
- CHECK_SYMBOLS(1);
- return "Assignment operation, but the function '" + symbols[0] + "()' returns void.";
- } break;
- case NARROWING_CONVERSION: {
- return "Narrowing conversion (float is converted to int and loses precision).";
- } break;
- case FUNCTION_MAY_YIELD: {
- CHECK_SYMBOLS(1);
- return "Assigned variable is typed but the function '" + symbols[0] + "()' may yield and return a GDScriptFunctionState instead.";
- } break;
- case VARIABLE_CONFLICTS_FUNCTION: {
- CHECK_SYMBOLS(1);
- return "Variable declaration of '" + symbols[0] + "' conflicts with a function of the same name.";
- } break;
- case FUNCTION_CONFLICTS_VARIABLE: {
- CHECK_SYMBOLS(1);
- return "Function declaration of '" + symbols[0] + "()' conflicts with a variable of the same name.";
- } break;
- case FUNCTION_CONFLICTS_CONSTANT: {
- CHECK_SYMBOLS(1);
- return "Function declaration of '" + symbols[0] + "()' conflicts with a constant of the same name.";
- } break;
- case INCOMPATIBLE_TERNARY: {
- return "Values of the ternary conditional are not mutually compatible.";
- } break;
- case UNUSED_SIGNAL: {
- CHECK_SYMBOLS(1);
- return "The signal '" + symbols[0] + "' is declared but never emitted.";
- } break;
- case RETURN_VALUE_DISCARDED: {
- CHECK_SYMBOLS(1);
- return "The function '" + symbols[0] + "()' returns a value, but this value is never used.";
- } break;
- case PROPERTY_USED_AS_FUNCTION: {
- CHECK_SYMBOLS(2);
- return "The method '" + symbols[0] + "()' was not found in base '" + symbols[1] + "' but there's a property with the same name. Did you mean to access it?";
- } break;
- case CONSTANT_USED_AS_FUNCTION: {
- CHECK_SYMBOLS(2);
- return "The method '" + symbols[0] + "()' was not found in base '" + symbols[1] + "' but there's a constant with the same name. Did you mean to access it?";
- } break;
- case FUNCTION_USED_AS_PROPERTY: {
- CHECK_SYMBOLS(2);
- return "The property '" + symbols[0] + "' was not found in base '" + symbols[1] + "' but there's a method with the same name. Did you mean to call it?";
- } break;
- case INTEGER_DIVISION: {
- return "Integer division, decimal part will be discarded.";
- } break;
- case UNSAFE_PROPERTY_ACCESS: {
- CHECK_SYMBOLS(2);
- return "The property '" + symbols[0] + "' is not present on the inferred type '" + symbols[1] + "' (but may be present on a subtype).";
- } break;
- case UNSAFE_METHOD_ACCESS: {
- CHECK_SYMBOLS(2);
- return "The method '" + symbols[0] + "' is not present on the inferred type '" + symbols[1] + "' (but may be present on a subtype).";
- } break;
- case UNSAFE_CAST: {
- CHECK_SYMBOLS(1);
- return "The value is cast to '" + symbols[0] + "' but has an unknown type.";
- } break;
- case UNSAFE_CALL_ARGUMENT: {
- CHECK_SYMBOLS(4);
- return "The argument '" + symbols[0] + "' of the function '" + symbols[1] + "' requires a the subtype '" + symbols[2] + "' but the supertype '" + symbols[3] + "' was provided";
- } break;
- case DEPRECATED_KEYWORD: {
- CHECK_SYMBOLS(2);
- return "The '" + symbols[0] + "' keyword is deprecated and will be removed in a future release, please replace its uses by '" + symbols[1] + "'.";
- } break;
- case STANDALONE_TERNARY: {
- return "Standalone ternary conditional operator: the return value is being discarded.";
- }
- case WARNING_MAX: break; // Can't happen, but silences warning
- }
- ERR_FAIL_V_MSG(String(), "Invalid GDScript warning code: " + get_name_from_code(code) + ".");
-
-#undef CHECK_SYMBOLS
-}
-
-String GDScriptWarning::get_name() const {
- return get_name_from_code(code);
-}
-
-String GDScriptWarning::get_name_from_code(Code p_code) {
- ERR_FAIL_COND_V(p_code < 0 || p_code >= WARNING_MAX, String());
-
- static const char *names[] = {
- "UNASSIGNED_VARIABLE",
- "UNASSIGNED_VARIABLE_OP_ASSIGN",
- "UNUSED_VARIABLE",
- "SHADOWED_VARIABLE",
- "UNUSED_CLASS_VARIABLE",
- "UNUSED_ARGUMENT",
- "UNREACHABLE_CODE",
- "STANDALONE_EXPRESSION",
- "VOID_ASSIGNMENT",
- "NARROWING_CONVERSION",
- "FUNCTION_MAY_YIELD",
- "VARIABLE_CONFLICTS_FUNCTION",
- "FUNCTION_CONFLICTS_VARIABLE",
- "FUNCTION_CONFLICTS_CONSTANT",
- "INCOMPATIBLE_TERNARY",
- "UNUSED_SIGNAL",
- "RETURN_VALUE_DISCARDED",
- "PROPERTY_USED_AS_FUNCTION",
- "CONSTANT_USED_AS_FUNCTION",
- "FUNCTION_USED_AS_PROPERTY",
- "INTEGER_DIVISION",
- "UNSAFE_PROPERTY_ACCESS",
- "UNSAFE_METHOD_ACCESS",
- "UNSAFE_CAST",
- "UNSAFE_CALL_ARGUMENT",
- "DEPRECATED_KEYWORD",
- "STANDALONE_TERNARY",
- nullptr
- };
-
- return names[(int)p_code];
-}
-
-GDScriptWarning::Code GDScriptWarning::get_code_from_name(const String &p_name) {
- for (int i = 0; i < WARNING_MAX; i++) {
- if (get_name_from_code((Code)i) == p_name) {
- return (Code)i;
- }
- }
-
- ERR_FAIL_V_MSG(WARNING_MAX, "Invalid GDScript warning name: " + p_name);
-}
-
-#endif // DEBUG_ENABLED
-
GDScriptLanguage::GDScriptLanguage() {
-
calls = 0;
ERR_FAIL_COND(singleton);
singleton = this;
@@ -2240,18 +2268,43 @@ GDScriptLanguage::GDScriptLanguage() {
GLOBAL_DEF("debug/gdscript/completion/autocomplete_setters_and_getters", false);
for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower();
- bool default_enabled = !warning.begins_with("unsafe_") && i != GDScriptWarning::UNUSED_CLASS_VARIABLE;
+ bool default_enabled = !warning.begins_with("unsafe_");
GLOBAL_DEF("debug/gdscript/warnings/" + warning, default_enabled);
}
#endif // DEBUG_ENABLED
}
GDScriptLanguage::~GDScriptLanguage() {
-
if (_call_stack) {
memdelete_arr(_call_stack);
}
- singleton = nullptr;
+
+ // Clear dependencies between scripts, to ensure cyclic references are broken (to avoid leaks at exit).
+ SelfList<GDScript> *s = script_list.first();
+ while (s) {
+ GDScript *script = s->self();
+ // This ensures the current script is not released before we can check what's the next one
+ // in the list (we can't get the next upfront because we don't know if the reference breaking
+ // will cause it -or any other after it, for that matter- to be released so the next one
+ // is not the same as before).
+ script->reference();
+
+ for (Map<StringName, GDScriptFunction *>::Element *E = script->member_functions.front(); E; E = E->next()) {
+ GDScriptFunction *func = E->get();
+ for (int i = 0; i < func->argument_types.size(); i++) {
+ func->argument_types.write[i].script_type_ref = Ref<Script>();
+ }
+ func->return_type.script_type_ref = Ref<Script>();
+ }
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
+ E->get().data_type.script_type_ref = Ref<Script>();
+ }
+
+ s = s->next();
+ script->unreference();
+ }
+
+ singleton = NULL;
}
void GDScriptLanguage::add_orphan_subclass(const String &p_qualified_name, const ObjectID &p_subclass) {
@@ -2260,81 +2313,73 @@ void GDScriptLanguage::add_orphan_subclass(const String &p_qualified_name, const
Ref<GDScript> GDScriptLanguage::get_orphan_subclass(const String &p_qualified_name) {
Map<String, ObjectID>::Element *orphan_subclass_element = orphan_subclasses.find(p_qualified_name);
- if (!orphan_subclass_element)
+ if (!orphan_subclass_element) {
return Ref<GDScript>();
+ }
ObjectID orphan_subclass = orphan_subclass_element->get();
Object *obj = ObjectDB::get_instance(orphan_subclass);
orphan_subclasses.erase(orphan_subclass_element);
- if (!obj)
+ if (!obj) {
return Ref<GDScript>();
+ }
return Ref<GDScript>(Object::cast_to<GDScript>(obj));
}
/*************** RESOURCE ***************/
RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CANT_OPEN;
+ }
- GDScript *script = memnew(GDScript);
-
- Ref<GDScript> scriptres(script);
-
- if (p_path.ends_with(".gde") || p_path.ends_with(".gdc")) {
-
- script->set_script_path(p_original_path); // script needs this.
- script->set_path(p_original_path);
- Error err = script->load_byte_code(p_path);
- ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load byte code from file '" + p_path + "'.");
-
- } else {
- Error err = script->load_source_code(p_path);
- ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load source code from file '" + p_path + "'.");
+ Error err;
+ Ref<GDScript> script = GDScriptCache::get_full_script(p_path, err);
- script->set_script_path(p_original_path); // script needs this.
- script->set_path(p_original_path);
+ // TODO: Reintroduce binary and encrypted scripts.
- script->reload();
+ if (script.is_null()) {
+ // Don't fail loading because of parsing error.
+ script.instance();
}
- if (r_error)
+
+ if (r_error) {
*r_error = OK;
+ }
- return scriptres;
+ return script;
}
void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("gd");
- p_extensions->push_back("gdc");
- p_extensions->push_back("gde");
+ // TODO: Reintroduce binary and encrypted scripts.
+ // p_extensions->push_back("gdc");
+ // p_extensions->push_back("gde");
}
bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
-
return (p_type == "Script" || p_type == "GDScript");
}
String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const {
-
String el = p_path.get_extension().to_lower();
- if (el == "gd" || el == "gdc" || el == "gde")
+ // TODO: Reintroduce binary and encrypted scripts.
+ if (el == "gd" /*|| el == "gdc" || el == "gde"*/) {
return "GDScript";
+ }
return "";
}
void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
-
FileAccessRef file = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_path + "'.");
String source = file->get_as_utf8_string();
- if (source.empty()) {
+ if (source.is_empty()) {
return;
}
GDScriptParser parser;
- if (OK != parser.parse(source, p_path.get_base_dir(), true, p_path, false, nullptr, true)) {
+ if (OK != parser.parse(source, p_path, false)) {
return;
}
@@ -2344,7 +2389,6 @@ void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<S
}
Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
-
Ref<GDScript> sqscr = p_resource;
ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
@@ -2371,12 +2415,11 @@ Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resou
}
void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
-
if (Object::cast_to<GDScript>(*p_resource)) {
p_extensions->push_back("gd");
}
}
-bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
+bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
return Object::cast_to<GDScript>(*p_resource) != nullptr;
}
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index 5fdc25669f..37f01b2571 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,13 +33,13 @@
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
+#include "core/doc_data.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
-#include "core/script_language.h"
+#include "core/object/script_language.h"
#include "gdscript_function.h"
class GDScriptNativeClass : public Reference {
-
GDCLASS(GDScriptNativeClass, Reference);
StringName name;
@@ -56,7 +56,6 @@ public:
};
class GDScript : public Script {
-
GDCLASS(GDScript, Script);
bool tool;
bool valid;
@@ -71,9 +70,10 @@ class GDScript : public Script {
friend class GDScriptInstance;
friend class GDScriptFunction;
+ friend class GDScriptAnalyzer;
friend class GDScriptCompiler;
- friend class GDScriptFunctions;
friend class GDScriptLanguage;
+ friend struct GDScriptUtilityFunctionsDefinitions;
Ref<GDScriptNativeClass> native;
Ref<GDScript> base;
@@ -92,9 +92,7 @@ class GDScript : public Script {
#ifdef TOOLS_ENABLED
Map<StringName, int> member_lines;
-
Map<StringName, Variant> member_default_values;
-
List<PropertyInfo> members_cache;
Map<StringName, Variant> member_default_values_cache;
Ref<GDScript> base_cache;
@@ -103,10 +101,25 @@ class GDScript : public Script {
bool placeholder_fallback_enabled;
void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames);
+ DocData::ClassDoc doc;
+ Vector<DocData::ClassDoc> docs;
+ String doc_brief_description;
+ String doc_description;
+ Vector<DocData::TutorialDoc> doc_tutorials;
+ Map<String, String> doc_functions;
+ Map<String, String> doc_variables;
+ Map<String, String> doc_constants;
+ Map<String, String> doc_signals;
+ Map<String, DocData::EnumDoc> doc_enums;
+ void _clear_doc();
+ void _update_doc();
+ void _add_doc(const DocData::ClassDoc &p_inner_class);
+
#endif
Map<StringName, PropertyInfo> member_info;
- GDScriptFunction *initializer; //direct pointer to _init , faster to locate
+ GDScriptFunction *implicit_initializer = nullptr;
+ GDScriptFunction *initializer = nullptr; //direct pointer to new , faster to locate
int subclass_count;
Set<Object *> instances;
@@ -117,6 +130,9 @@ class GDScript : public Script {
String fully_qualified_name;
SelfList<GDScript> script_list;
+ SelfList<GDScriptFunctionState>::List pending_func_states;
+
+ void _super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error);
GDScriptInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error);
void _set_subclass_path(Ref<GDScript> &p_sc, const String &p_path);
@@ -124,7 +140,7 @@ class GDScript : public Script {
#ifdef TOOLS_ENABLED
Set<PlaceHolderScriptInstance *> placeholders;
//void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
+ virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
#endif
#ifdef DEBUG_ENABLED
@@ -133,25 +149,31 @@ class GDScript : public Script {
#endif
- bool _update_exports();
+ bool _update_exports(bool *r_err = nullptr, bool p_recursive_call = false);
void _save_orphaned_subclasses();
void _init_rpc_methods_properties();
+ void _get_script_property_list(List<PropertyInfo> *r_list, bool p_include_base) const;
+ void _get_script_method_list(List<MethodInfo> *r_list, bool p_include_base) const;
+ void _get_script_signal_list(List<MethodInfo> *r_list, bool p_include_base) const;
+
+ // This method will map the class name from "Reference" to "MyClass.InnerClass".
+ static String _get_gdscript_reference_class_name(const GDScript *p_gdscript);
+
protected:
bool _get(const StringName &p_name, Variant &r_ret) const;
bool _set(const StringName &p_name, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_properties) const;
- Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- //void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount);
+ Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
static void _bind_methods();
public:
- virtual bool is_valid() const { return valid; }
+ virtual bool is_valid() const override { return valid; }
- bool inherits_script(const Ref<Script> &p_script) const;
+ bool inherits_script(const Ref<Script> &p_script) const override;
const Map<StringName, Ref<GDScript>> &get_subclasses() const { return subclasses; }
const Map<StringName, Variant> &get_constants() const { return constants; }
@@ -164,10 +186,10 @@ public:
const Ref<GDScriptNativeClass> &get_native() const { return native; }
const String &get_script_class_name() const { return name; }
- virtual bool has_script_signal(const StringName &p_signal) const;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
+ virtual bool has_script_signal(const StringName &p_signal) const override;
+ virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override;
- bool is_tool() const { return tool; }
+ bool is_tool() const override { return tool; }
Ref<GDScript> get_base() const;
const Map<StringName, MemberInfo> &debug_get_member_indices() const { return member_indices; }
@@ -175,21 +197,27 @@ public:
StringName debug_get_member_by_index(int p_idx) const;
Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- virtual bool can_instance() const;
+ virtual bool can_instance() const override;
+
+ virtual Ref<Script> get_base_script() const override;
- virtual Ref<Script> get_base_script() const;
+ virtual StringName get_instance_base_type() const override; // this may not work in all scripts, will return empty if so
+ virtual ScriptInstance *instance_create(Object *p_this) override;
+ virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override;
+ virtual bool instance_has(const Object *p_this) const override;
- virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so
- virtual ScriptInstance *instance_create(Object *p_this);
- virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this);
- virtual bool instance_has(const Object *p_this) const;
+ virtual bool has_source_code() const override;
+ virtual String get_source_code() const override;
+ virtual void set_source_code(const String &p_code) override;
+ virtual void update_exports() override;
- virtual bool has_source_code() const;
- virtual String get_source_code() const;
- virtual void set_source_code(const String &p_code);
- virtual void update_exports();
+#ifdef TOOLS_ENABLED
+ virtual const Vector<DocData::ClassDoc> &get_documentation() const override {
+ return docs;
+ }
+#endif // TOOLS_ENABLED
- virtual Error reload(bool p_keep_state = false);
+ virtual Error reload(bool p_keep_state = false) override;
void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too...
Error load_source_code(const String &p_path);
@@ -197,42 +225,42 @@ public:
Vector<uint8_t> get_as_byte_code() const;
- bool get_property_default_value(const StringName &p_property, Variant &r_value) const;
+ bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
- virtual void get_script_method_list(List<MethodInfo> *p_list) const;
- virtual bool has_method(const StringName &p_method) const;
- virtual MethodInfo get_method_info(const StringName &p_method) const;
+ virtual void get_script_method_list(List<MethodInfo> *p_list) const override;
+ virtual bool has_method(const StringName &p_method) const override;
+ virtual MethodInfo get_method_info(const StringName &p_method) const override;
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
+ virtual void get_script_property_list(List<PropertyInfo> *p_list) const override;
- virtual ScriptLanguage *get_language() const;
+ virtual ScriptLanguage *get_language() const override;
- virtual int get_member_line(const StringName &p_member) const {
+ virtual int get_member_line(const StringName &p_member) const override {
#ifdef TOOLS_ENABLED
- if (member_lines.has(p_member))
+ if (member_lines.has(p_member)) {
return member_lines[p_member];
- else
+ }
#endif
- return -1;
+ return -1;
}
- virtual void get_constants(Map<StringName, Variant> *p_constants);
- virtual void get_members(Set<StringName> *p_members);
+ virtual void get_constants(Map<StringName, Variant> *p_constants) override;
+ virtual void get_members(Set<StringName> *p_members) override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual Vector<ScriptNetData> get_rpc_methods() const override;
+ virtual uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_variable) const;
- virtual StringName get_rset_property(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ virtual Vector<ScriptNetData> get_rset_properties() const override;
+ virtual uint16_t get_rset_property_id(const StringName &p_variable) const override;
+ virtual StringName get_rset_property(const uint16_t p_variable_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
#ifdef TOOLS_ENABLED
- virtual bool is_placeholder_fallback_enabled() const { return placeholder_fallback_enabled; }
+ virtual bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; }
#endif
GDScript();
@@ -242,8 +270,8 @@ public:
class GDScriptInstance : public ScriptInstance {
friend class GDScript;
friend class GDScriptFunction;
- friend class GDScriptFunctions;
friend class GDScriptCompiler;
+ friend struct GDScriptUtilityFunctionsDefinitions;
ObjectID owner_id;
Object *owner;
@@ -254,7 +282,7 @@ class GDScriptInstance : public ScriptInstance {
Vector<Variant> members;
bool base_ref;
- void _ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount);
+ SelfList<GDScriptFunctionState>::List pending_func_states;
public:
virtual Object *get_owner() { return owner; }
@@ -267,8 +295,6 @@ public:
virtual void get_method_list(List<MethodInfo> *p_list) const;
virtual bool has_method(const StringName &p_method) const;
virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount);
- virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount);
Variant debug_get_member_by_index(int p_idx) const { return members[p_idx]; }
@@ -299,53 +325,8 @@ public:
~GDScriptInstance();
};
-#ifdef DEBUG_ENABLED
-struct GDScriptWarning {
- enum Code {
- UNASSIGNED_VARIABLE, // Variable used but never assigned
- UNASSIGNED_VARIABLE_OP_ASSIGN, // Variable never assigned but used in an assignment operation (+=, *=, etc)
- UNUSED_VARIABLE, // Local variable is declared but never used
- SHADOWED_VARIABLE, // Variable name shadowed by other variable
- UNUSED_CLASS_VARIABLE, // Class variable is declared but never used in the file
- UNUSED_ARGUMENT, // Function argument is never used
- UNREACHABLE_CODE, // Code after a return statement
- STANDALONE_EXPRESSION, // Expression not assigned to a variable
- VOID_ASSIGNMENT, // Function returns void but it's assigned to a variable
- NARROWING_CONVERSION, // Float value into an integer slot, precision is lost
- FUNCTION_MAY_YIELD, // Typed assign of function call that yields (it may return a function state)
- VARIABLE_CONFLICTS_FUNCTION, // Variable has the same name of a function
- FUNCTION_CONFLICTS_VARIABLE, // Function has the same name of a variable
- FUNCTION_CONFLICTS_CONSTANT, // Function has the same name of a constant
- INCOMPATIBLE_TERNARY, // Possible values of a ternary if are not mutually compatible
- UNUSED_SIGNAL, // Signal is defined but never emitted
- RETURN_VALUE_DISCARDED, // Function call returns something but the value isn't used
- PROPERTY_USED_AS_FUNCTION, // Function not found, but there's a property with the same name
- CONSTANT_USED_AS_FUNCTION, // Function not found, but there's a constant with the same name
- FUNCTION_USED_AS_PROPERTY, // Property not found, but there's a function with the same name
- INTEGER_DIVISION, // Integer divide by integer, decimal part is discarded
- UNSAFE_PROPERTY_ACCESS, // Property not found in the detected type (but can be in subtypes)
- UNSAFE_METHOD_ACCESS, // Function not found in the detected type (but can be in subtypes)
- UNSAFE_CAST, // Cast used in an unknown type
- UNSAFE_CALL_ARGUMENT, // Function call argument is of a supertype of the require argument
- DEPRECATED_KEYWORD, // The keyword is deprecated and should be replaced
- STANDALONE_TERNARY, // Return value of ternary expression is discarded
- WARNING_MAX,
- } code;
- Vector<String> symbols;
- int line;
-
- String get_name() const;
- String get_message() const;
- static String get_name_from_code(Code p_code);
- static Code get_code_from_name(const String &p_name);
-
- GDScriptWarning() :
- code(WARNING_MAX),
- line(-1) {}
-};
-#endif // DEBUG_ENABLED
-
class GDScriptLanguage : public ScriptLanguage {
+ friend class GDScriptFunctionState;
static GDScriptLanguage *singleton;
@@ -355,7 +336,6 @@ class GDScriptLanguage : public ScriptLanguage {
Map<StringName, Variant> named_globals;
struct CallLevel {
-
Variant *stack;
GDScriptFunction *function;
GDScriptInstance *instance;
@@ -394,12 +374,13 @@ public:
bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
_FORCE_INLINE_ void enter_function(GDScriptInstance *p_instance, GDScriptFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) {
-
- if (Thread::get_main_id() != Thread::get_caller_id())
+ if (Thread::get_main_id() != Thread::get_caller_id()) {
return; //no support for other threads than main for now
+ }
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0)
+ if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() + 1);
+ }
if (_debug_call_stack_pos >= _debug_max_call_stack) {
//stack overflow
@@ -417,15 +398,15 @@ public:
}
_FORCE_INLINE_ void exit_function() {
-
- if (Thread::get_main_id() != Thread::get_caller_id())
+ if (Thread::get_main_id() != Thread::get_caller_id()) {
return; //no support for other threads than main for now
+ }
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0)
+ if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() - 1);
+ }
if (_debug_call_stack_pos == 0) {
-
_debug_error = "Stack Underflow (Engine Bug)";
EngineDebugger::get_script_debugger()->debug(this);
return;
@@ -435,8 +416,9 @@ public:
}
virtual Vector<StackInfo> debug_get_current_stack_info() {
- if (Thread::get_main_id() != Thread::get_caller_id())
+ if (Thread::get_main_id() != Thread::get_caller_id()) {
return Vector<StackInfo>();
+ }
Vector<StackInfo> csi;
csi.resize(_debug_call_stack_pos);
@@ -451,7 +433,6 @@ public:
}
struct {
-
StringName _init;
StringName _notification;
StringName _set;
@@ -489,7 +470,8 @@ public:
virtual Script *create_script() const;
virtual bool has_named_classes() const;
virtual bool supports_builtin_mode() const;
- virtual bool can_inherit_from_file() { return true; }
+ virtual bool supports_documentation() const;
+ virtual bool can_inherit_from_file() const { 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 PackedStringArray &p_args) const;
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);
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
new file mode 100644
index 0000000000..a6138cc564
--- /dev/null
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -0,0 +1,3446 @@
+/*************************************************************************/
+/* gdscript_analyzer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_analyzer.h"
+
+#include "core/config/project_settings.h"
+#include "core/io/resource_loader.h"
+#include "core/object/class_db.h"
+#include "core/object/script_language.h"
+#include "core/os/file_access.h"
+#include "core/templates/hash_map.h"
+#include "gdscript.h"
+#include "gdscript_utility_functions.h"
+
+// TODO: Move this to a central location (maybe core?).
+static HashMap<StringName, StringName> underscore_map;
+static const char *underscore_classes[] = {
+ "ClassDB",
+ "Directory",
+ "Engine",
+ "File",
+ "Geometry",
+ "GodotSharp",
+ "JSON",
+ "Marshalls",
+ "Mutex",
+ "OS",
+ "ResourceLoader",
+ "ResourceSaver",
+ "Semaphore",
+ "Thread",
+ "VisualScriptEditor",
+ nullptr,
+};
+static StringName get_real_class_name(const StringName &p_source) {
+ if (underscore_map.is_empty()) {
+ const char **class_name = underscore_classes;
+ while (*class_name != nullptr) {
+ underscore_map[*class_name] = String("_") + *class_name;
+ class_name++;
+ }
+ }
+ if (underscore_map.has(p_source)) {
+ return underscore_map[p_source];
+ }
+ return p_source;
+}
+
+static MethodInfo info_from_utility_func(const StringName &p_function) {
+ ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());
+
+ MethodInfo info(p_function);
+
+ if (Variant::has_utility_function_return_value(p_function)) {
+ info.return_val.type = Variant::get_utility_function_return_type(p_function);
+ if (info.return_val.type == Variant::NIL) {
+ info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
+ }
+
+ if (Variant::is_utility_function_vararg(p_function)) {
+ info.flags |= METHOD_FLAG_VARARG;
+ } else {
+ for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {
+ PropertyInfo pi;
+#ifdef DEBUG_METHODS_ENABLED
+ pi.name = Variant::get_utility_function_argument_name(p_function, i);
+#else
+ pi.name = "arg" + itos(i + 1);
+#endif
+ pi.type = Variant::get_utility_function_argument_type(p_function, i);
+ if (pi.type == Variant::NIL) {
+ pi.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
+ info.arguments.push_back(pi);
+ }
+ }
+
+ return info;
+}
+
+void GDScriptAnalyzer::cleanup() {
+ underscore_map.clear();
+}
+
+static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::BUILTIN;
+ type.builtin_type = Variant::CALLABLE;
+ type.is_constant = true;
+ type.method_info = p_info;
+ return type;
+}
+
+static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::BUILTIN;
+ type.builtin_type = Variant::SIGNAL;
+ type.is_constant = true;
+ type.method_info = p_info;
+ return type;
+}
+
+static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::NATIVE;
+ type.builtin_type = Variant::OBJECT;
+ type.is_constant = true;
+ type.native_type = p_class_name;
+ type.is_meta_type = true;
+ return type;
+}
+
+static GDScriptParser::DataType make_native_enum_type(const StringName &p_native_class, const StringName &p_enum_name) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::ENUM;
+ type.builtin_type = Variant::OBJECT;
+ type.is_constant = true;
+ type.is_meta_type = true;
+
+ List<StringName> enum_values;
+ StringName real_native_name = get_real_class_name(p_native_class);
+ ClassDB::get_enum_constants(real_native_name, p_enum_name, &enum_values);
+
+ for (const List<StringName>::Element *E = enum_values.front(); E != nullptr; E = E->next()) {
+ type.enum_values[E->get()] = ClassDB::get_integer_constant(real_native_name, E->get());
+ }
+
+ return type;
+}
+
+static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::BUILTIN;
+ type.builtin_type = p_type;
+ type.is_constant = true;
+ type.is_meta_type = true;
+ return type;
+}
+
+Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
+ if (p_class->base_type.is_set()) {
+ // Already resolved
+ return OK;
+ }
+
+ if (p_class == parser->head) {
+ if (p_class->identifier) {
+ p_class->fqcn = p_class->identifier->name;
+ } else {
+ p_class->fqcn = parser->script_path;
+ }
+ } else {
+ p_class->fqcn = p_class->outer->fqcn + "::" + String(p_class->identifier->name);
+ }
+
+ GDScriptParser::DataType result;
+
+ // Set datatype for class.
+ GDScriptParser::DataType class_type;
+ class_type.is_constant = true;
+ class_type.is_meta_type = true;
+ class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ class_type.kind = GDScriptParser::DataType::CLASS;
+ class_type.class_type = p_class;
+ class_type.script_path = parser->script_path;
+ p_class->set_datatype(class_type);
+
+ if (!p_class->extends_used) {
+ result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.native_type = "Reference";
+ } else {
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+
+ GDScriptParser::DataType base;
+
+ int extends_index = 0;
+
+ if (!p_class->extends_path.is_empty()) {
+ Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path);
+ if (parser.is_null()) {
+ push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+ if (err != OK) {
+ push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
+ return err;
+ }
+
+ base = parser->get_parser()->head->get_datatype();
+ } else {
+ if (p_class->extends.is_empty()) {
+ return ERR_PARSE_ERROR;
+ }
+ const StringName &name = p_class->extends[extends_index++];
+ base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+
+ if (ScriptServer::is_global_class(name)) {
+ String base_path = ScriptServer::get_global_class_path(name);
+
+ if (base_path == parser->script_path) {
+ base = parser->head->get_datatype();
+ } else {
+ Ref<GDScriptParserRef> parser = get_parser_for(base_path);
+ if (parser.is_null()) {
+ push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+ if (err != OK) {
+ push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
+ return err;
+ }
+ base = parser->get_parser()->head->get_datatype();
+ }
+ } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
+ const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
+ if (info.path.get_extension().to_lower() != ".gd") {
+ push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ Ref<GDScriptParserRef> parser = get_parser_for(info.path);
+ if (parser.is_null()) {
+ push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+ if (err != OK) {
+ push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
+ return err;
+ }
+ } else if (class_exists(name) && ClassDB::can_instance(get_real_class_name(name))) {
+ base.kind = GDScriptParser::DataType::NATIVE;
+ base.native_type = name;
+ } else {
+ // Look for other classes in script.
+ GDScriptParser::ClassNode *look_class = p_class;
+ bool found = false;
+ while (look_class != nullptr) {
+ if (look_class->identifier && look_class->identifier->name == name) {
+ if (!look_class->get_datatype().is_set()) {
+ Error err = resolve_inheritance(look_class, false);
+ if (err) {
+ return err;
+ }
+ }
+ base = look_class->get_datatype();
+ found = true;
+ break;
+ }
+ if (look_class->members_indices.has(name) && look_class->get_member(name).type == GDScriptParser::ClassNode::Member::CLASS) {
+ GDScriptParser::ClassNode::Member member = look_class->get_member(name);
+ if (!member.m_class->get_datatype().is_set()) {
+ Error err = resolve_inheritance(member.m_class, false);
+ if (err) {
+ return err;
+ }
+ }
+ base = member.m_class->get_datatype();
+ found = true;
+ break;
+ }
+ look_class = look_class->outer;
+ }
+
+ if (!found) {
+ push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
+ return ERR_PARSE_ERROR;
+ }
+ }
+ }
+
+ for (int index = extends_index; index < p_class->extends.size(); index++) {
+ if (base.kind != GDScriptParser::DataType::CLASS) {
+ push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
+ GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
+ id->name = p_class->extends[index];
+
+ reduce_identifier_from_base(id, &base);
+
+ GDScriptParser::DataType id_type = id->get_datatype();
+ if (!id_type.is_set()) {
+ push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
+ }
+
+ base = id_type;
+ }
+
+ result = base;
+ }
+
+ if (!result.is_set()) {
+ // TODO: More specific error messages.
+ push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
+ return ERR_PARSE_ERROR;
+ }
+
+ // Check for cyclic inheritance.
+ const GDScriptParser::ClassNode *base_class = result.class_type;
+ while (base_class) {
+ if (base_class->fqcn == p_class->fqcn) {
+ push_error("Cyclic inheritance.", p_class);
+ return ERR_PARSE_ERROR;
+ }
+ base_class = base_class->base_type.class_type;
+ }
+
+ p_class->base_type = result;
+ class_type.native_type = result.native_type;
+ p_class->set_datatype(class_type);
+
+ if (p_recursive) {
+ for (int i = 0; i < p_class->members.size(); i++) {
+ if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
+ Error err = resolve_inheritance(p_class->members[i].m_class, true);
+ if (err) {
+ return err;
+ }
+ }
+ }
+ }
+
+ return OK;
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
+ GDScriptParser::DataType result;
+
+ if (p_type == nullptr) {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ return result;
+ }
+
+ result.type_source = result.ANNOTATED_EXPLICIT;
+ result.builtin_type = Variant::OBJECT;
+
+ if (p_type->type_chain.is_empty()) {
+ // void.
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = Variant::NIL;
+ p_type->set_datatype(result);
+ return result;
+ }
+
+ StringName first = p_type->type_chain[0]->name;
+
+ if (first == "Variant") {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ if (p_type->type_chain.size() > 1) {
+ push_error(R"("Variant" type don't contain nested types.)", p_type->type_chain[1]);
+ return GDScriptParser::DataType();
+ }
+ return result;
+ }
+
+ if (first == "Object") {
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.native_type = "Object";
+ if (p_type->type_chain.size() > 1) {
+ push_error(R"("Object" type don't contain nested types.)", p_type->type_chain[1]);
+ return GDScriptParser::DataType();
+ }
+ return result;
+ }
+
+ if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
+ // Built-in types.
+ if (p_type->type_chain.size() > 1) {
+ push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
+ return GDScriptParser::DataType();
+ }
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = GDScriptParser::get_builtin_type(first);
+ } else if (class_exists(first)) {
+ // Native engine classes.
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.native_type = first;
+ } else if (ScriptServer::is_global_class(first)) {
+ if (parser->script_path == ScriptServer::get_global_class_path(first)) {
+ result = parser->head->get_datatype();
+ } else {
+ Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first));
+ if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
+ push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
+ return GDScriptParser::DataType();
+ }
+ result = ref->get_parser()->head->get_datatype();
+ }
+ } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
+ const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
+ Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
+ if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
+ push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
+ return GDScriptParser::DataType();
+ }
+ result = ref->get_parser()->head->get_datatype();
+ } else if (ClassDB::has_enum(get_real_class_name(parser->current_class->base_type.native_type), first)) {
+ // Native enum in current class.
+ result = make_native_enum_type(parser->current_class->base_type.native_type, first);
+ } else {
+ // Classes in current scope.
+ GDScriptParser::ClassNode *script_class = parser->current_class;
+ bool found = false;
+ while (!found && script_class != nullptr) {
+ if (script_class->identifier && script_class->identifier->name == first) {
+ result = script_class->get_datatype();
+ found = true;
+ break;
+ }
+ if (script_class->members_indices.has(first)) {
+ GDScriptParser::ClassNode::Member member = script_class->members[script_class->members_indices[first]];
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::CLASS:
+ result = member.m_class->get_datatype();
+ found = true;
+ break;
+ case GDScriptParser::ClassNode::Member::ENUM:
+ result = member.m_enum->get_datatype();
+ found = true;
+ break;
+ case GDScriptParser::ClassNode::Member::CONSTANT:
+ if (member.constant->get_datatype().is_meta_type) {
+ result = member.constant->get_datatype();
+ found = true;
+ break;
+ }
+ [[fallthrough]];
+ default:
+ push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
+ return GDScriptParser::DataType();
+ }
+ }
+ script_class = script_class->outer;
+ }
+ }
+ if (!result.is_set()) {
+ push_error(vformat(R"("%s" was not found in the current scope.)", first), p_type);
+ result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
+ return result;
+ }
+
+ if (p_type->type_chain.size() > 1) {
+ if (result.kind == GDScriptParser::DataType::CLASS) {
+ for (int i = 1; i < p_type->type_chain.size(); i++) {
+ GDScriptParser::DataType base = result;
+ reduce_identifier_from_base(p_type->type_chain[i], &base);
+ result = p_type->type_chain[i]->get_datatype();
+ if (!result.is_set()) {
+ push_error(vformat(R"(Could not find type "%s" under base "%s".)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
+ result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
+ return result;
+ } else if (!result.is_meta_type) {
+ push_error(vformat(R"(Member "%s" under base "%s" is not a valid type.)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
+ result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
+ return result;
+ }
+ }
+ } else if (result.kind == GDScriptParser::DataType::NATIVE) {
+ // Only enums allowed for native.
+ if (ClassDB::has_enum(get_real_class_name(result.native_type), p_type->type_chain[1]->name)) {
+ if (p_type->type_chain.size() > 2) {
+ push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
+ } else {
+ result = make_native_enum_type(result.native_type, p_type->type_chain[1]->name);
+ }
+ }
+ } else {
+ push_error(vformat(R"(Could not find nested type "%s" under base "%s".)", p_type->type_chain[1]->name, result.to_string()), p_type->type_chain[1]);
+ result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
+ return result;
+ }
+ }
+
+ p_type->set_datatype(result);
+ return result;
+}
+
+void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class) {
+ if (p_class->resolved_interface) {
+ return;
+ }
+ p_class->resolved_interface = true;
+
+ GDScriptParser::ClassNode *previous_class = parser->current_class;
+ parser->current_class = p_class;
+
+ for (int i = 0; i < p_class->members.size(); i++) {
+ GDScriptParser::ClassNode::Member member = p_class->members[i];
+
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::VARIABLE: {
+ GDScriptParser::DataType datatype;
+ datatype.kind = GDScriptParser::DataType::VARIANT;
+ datatype.type_source = GDScriptParser::DataType::UNDETECTED;
+
+ if (member.variable->initializer != nullptr) {
+ member.variable->set_datatype(datatype); // Allow recursive usage.
+ reduce_expression(member.variable->initializer);
+ datatype = member.variable->initializer->get_datatype();
+ if (datatype.type_source != GDScriptParser::DataType::UNDETECTED) {
+ datatype.type_source = GDScriptParser::DataType::INFERRED;
+ }
+ }
+
+ if (member.variable->datatype_specifier != nullptr) {
+ datatype = resolve_datatype(member.variable->datatype_specifier);
+ datatype.is_meta_type = false;
+
+ if (member.variable->initializer != nullptr) {
+ if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true)) {
+ // Try reverse test since it can be a masked subtype.
+ if (!is_type_compatible(member.variable->initializer->get_datatype(), datatype, true)) {
+ push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer);
+ } else {
+ // TODO: Add warning.
+ mark_node_unsafe(member.variable->initializer);
+ }
+ } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
+#ifdef DEBUG_ENABLED
+ parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
+#endif
+ }
+ if (member.variable->initializer->get_datatype().is_variant()) {
+ // TODO: Warn unsafe assign.
+ mark_node_unsafe(member.variable->initializer);
+ }
+ }
+ } else if (member.variable->infer_datatype) {
+ if (member.variable->initializer == nullptr) {
+ push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier);
+ } else if (!datatype.is_set() || datatype.has_no_type()) {
+ push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value doesn't have a set type.)", member.variable->identifier->name), member.variable->initializer);
+ } else if (datatype.is_variant()) {
+ push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is Variant. Use explicit "Variant" type if this is intended.)", member.variable->identifier->name), member.variable->initializer);
+ } else if (datatype.builtin_type == Variant::NIL) {
+ push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer);
+ }
+ datatype.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+ }
+
+ datatype.is_constant = false;
+ member.variable->set_datatype(datatype);
+ if (!datatype.has_no_type()) {
+ // TODO: Move this out into a routine specific to validate annotations.
+ if (member.variable->export_info.hint == PROPERTY_HINT_TYPE_STRING) {
+ // @export annotation.
+ switch (datatype.kind) {
+ case GDScriptParser::DataType::BUILTIN:
+ member.variable->export_info.hint_string = Variant::get_type_name(datatype.builtin_type);
+ break;
+ case GDScriptParser::DataType::NATIVE:
+ if (ClassDB::is_parent_class(get_real_class_name(datatype.native_type), "Resource")) {
+ member.variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ member.variable->export_info.hint_string = get_real_class_name(datatype.native_type);
+ } else {
+ push_error(R"(Export type can only be built-in or a resource.)", member.variable);
+ }
+ break;
+ default:
+ // TODO: Allow custom user resources.
+ push_error(R"(Export type can only be built-in or a resource.)", member.variable);
+ break;
+ }
+ }
+ }
+ } break;
+ case GDScriptParser::ClassNode::Member::CONSTANT: {
+ reduce_expression(member.constant->initializer);
+
+ GDScriptParser::DataType datatype = member.constant->get_datatype();
+ if (member.constant->initializer) {
+ if (member.constant->initializer->type == GDScriptParser::Node::ARRAY) {
+ const_fold_array(static_cast<GDScriptParser::ArrayNode *>(member.constant->initializer));
+ } else if (member.constant->initializer->type == GDScriptParser::Node::DICTIONARY) {
+ const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(member.constant->initializer));
+ }
+
+ if (!member.constant->initializer->is_constant) {
+ push_error(R"(Initializer for a constant must be a constant expression.)", member.constant->initializer);
+ }
+
+ if (member.constant->datatype_specifier != nullptr) {
+ datatype = resolve_datatype(member.constant->datatype_specifier);
+ datatype.is_meta_type = false;
+
+ if (!is_type_compatible(datatype, member.constant->initializer->get_datatype(), true)) {
+ push_error(vformat(R"(Value of type "%s" cannot be initialized to constant of type "%s".)", member.constant->initializer->get_datatype().to_string(), datatype.to_string()), member.constant->initializer);
+ } else if (datatype.builtin_type == Variant::INT && member.constant->initializer->get_datatype().builtin_type == Variant::FLOAT) {
+#ifdef DEBUG_ENABLED
+ parser->push_warning(member.constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
+#endif
+ }
+ }
+ }
+ datatype.is_constant = true;
+
+ member.constant->set_datatype(datatype);
+ } break;
+ case GDScriptParser::ClassNode::Member::SIGNAL: {
+ for (int j = 0; j < member.signal->parameters.size(); j++) {
+ GDScriptParser::DataType signal_type = resolve_datatype(member.signal->parameters[j]->datatype_specifier);
+ signal_type.is_meta_type = false;
+ member.signal->parameters[j]->set_datatype(signal_type);
+ }
+ // TODO: Make MethodInfo from signal.
+ GDScriptParser::DataType signal_type;
+ signal_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ signal_type.kind = GDScriptParser::DataType::BUILTIN;
+ signal_type.builtin_type = Variant::SIGNAL;
+
+ member.signal->set_datatype(signal_type);
+ } break;
+ case GDScriptParser::ClassNode::Member::ENUM: {
+ GDScriptParser::DataType enum_type;
+ enum_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ enum_type.kind = GDScriptParser::DataType::ENUM;
+ enum_type.builtin_type = Variant::DICTIONARY;
+ enum_type.enum_type = member.m_enum->identifier->name;
+ enum_type.native_type = p_class->fqcn + "." + member.m_enum->identifier->name;
+ enum_type.is_meta_type = true;
+ enum_type.is_constant = true;
+
+ // Enums can't be nested, so we can safely override this.
+ current_enum = member.m_enum;
+
+ for (int j = 0; j < member.m_enum->values.size(); j++) {
+ GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
+
+ if (element.custom_value) {
+ reduce_expression(element.custom_value);
+ if (!element.custom_value->is_constant) {
+ push_error(R"(Enum values must be constant.)", element.custom_value);
+ } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
+ push_error(R"(Enum values must be integers.)", element.custom_value);
+ } else {
+ element.value = element.custom_value->reduced_value;
+ element.resolved = true;
+ }
+ } else {
+ if (element.index > 0) {
+ element.value = element.parent_enum->values[element.index - 1].value + 1;
+ } else {
+ element.value = 0;
+ }
+ element.resolved = true;
+ }
+
+ enum_type.enum_values[element.identifier->name] = element.value;
+ }
+
+ current_enum = nullptr;
+
+ member.m_enum->set_datatype(enum_type);
+ } break;
+ case GDScriptParser::ClassNode::Member::FUNCTION:
+ resolve_function_signature(member.function);
+ break;
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
+ if (member.enum_value.custom_value) {
+ current_enum = member.enum_value.parent_enum;
+ reduce_expression(member.enum_value.custom_value);
+ current_enum = nullptr;
+
+ if (!member.enum_value.custom_value->is_constant) {
+ push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
+ } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
+ push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
+ } else {
+ member.enum_value.value = member.enum_value.custom_value->reduced_value;
+ member.enum_value.resolved = true;
+ }
+ } else {
+ if (member.enum_value.index > 0) {
+ member.enum_value.value = member.enum_value.parent_enum->values[member.enum_value.index - 1].value + 1;
+ } else {
+ member.enum_value.value = 0;
+ }
+ member.enum_value.resolved = true;
+ }
+ // Also update the original references.
+ member.enum_value.parent_enum->values.write[member.enum_value.index] = member.enum_value;
+ p_class->members.write[i].enum_value = member.enum_value;
+ } break;
+ case GDScriptParser::ClassNode::Member::CLASS:
+ break; // Done later.
+ case GDScriptParser::ClassNode::Member::UNDEFINED:
+ ERR_PRINT("Trying to resolve undefined member.");
+ break;
+ }
+ }
+
+ // Recurse nested classes.
+ for (int i = 0; i < p_class->members.size(); i++) {
+ GDScriptParser::ClassNode::Member member = p_class->members[i];
+ if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
+ continue;
+ }
+
+ resolve_class_interface(member.m_class);
+ }
+
+ parser->current_class = previous_class;
+}
+
+void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) {
+ if (p_class->resolved_body) {
+ return;
+ }
+ p_class->resolved_body = true;
+
+ GDScriptParser::ClassNode *previous_class = parser->current_class;
+ parser->current_class = p_class;
+
+ // Do functions now.
+ for (int i = 0; i < p_class->members.size(); i++) {
+ GDScriptParser::ClassNode::Member member = p_class->members[i];
+ if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
+ continue;
+ }
+
+ resolve_function_body(member.function);
+ }
+
+ parser->current_class = previous_class;
+
+ // Recurse nested classes.
+ for (int i = 0; i < p_class->members.size(); i++) {
+ GDScriptParser::ClassNode::Member member = p_class->members[i];
+ if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
+ continue;
+ }
+
+ resolve_class_body(member.m_class);
+ }
+
+ // Check unused variables.
+ for (int i = 0; i < p_class->members.size(); i++) {
+ GDScriptParser::ClassNode::Member member = p_class->members[i];
+ if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {
+ continue;
+ }
+#ifdef DEBUG_ENABLED
+ if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
+ parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
+ }
+#endif
+ }
+}
+
+void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
+ ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
+
+ switch (p_node->type) {
+ case GDScriptParser::Node::NONE:
+ break; // Unreachable.
+ case GDScriptParser::Node::CLASS:
+ resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node));
+ resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node));
+ break;
+ case GDScriptParser::Node::CONSTANT:
+ resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node));
+ break;
+ case GDScriptParser::Node::FOR:
+ resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
+ break;
+ case GDScriptParser::Node::FUNCTION:
+ resolve_function_signature(static_cast<GDScriptParser::FunctionNode *>(p_node));
+ resolve_function_body(static_cast<GDScriptParser::FunctionNode *>(p_node));
+ break;
+ case GDScriptParser::Node::IF:
+ resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
+ break;
+ case GDScriptParser::Node::SUITE:
+ resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
+ break;
+ case GDScriptParser::Node::VARIABLE:
+ resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node));
+ break;
+ case GDScriptParser::Node::WHILE:
+ resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
+ break;
+ case GDScriptParser::Node::ANNOTATION:
+ resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
+ break;
+ case GDScriptParser::Node::ASSERT:
+ resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
+ break;
+ case GDScriptParser::Node::MATCH:
+ resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
+ break;
+ case GDScriptParser::Node::MATCH_BRANCH:
+ resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
+ break;
+ case GDScriptParser::Node::PARAMETER:
+ resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
+ break;
+ case GDScriptParser::Node::PATTERN:
+ resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
+ break;
+ case GDScriptParser::Node::RETURN:
+ resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
+ break;
+ case GDScriptParser::Node::TYPE:
+ resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
+ break;
+ // Resolving expression is the same as reducing them.
+ case GDScriptParser::Node::ARRAY:
+ case GDScriptParser::Node::ASSIGNMENT:
+ case GDScriptParser::Node::AWAIT:
+ case GDScriptParser::Node::BINARY_OPERATOR:
+ case GDScriptParser::Node::CALL:
+ case GDScriptParser::Node::CAST:
+ case GDScriptParser::Node::DICTIONARY:
+ case GDScriptParser::Node::GET_NODE:
+ case GDScriptParser::Node::IDENTIFIER:
+ case GDScriptParser::Node::LITERAL:
+ case GDScriptParser::Node::PRELOAD:
+ case GDScriptParser::Node::SELF:
+ case GDScriptParser::Node::SUBSCRIPT:
+ case GDScriptParser::Node::TERNARY_OPERATOR:
+ case GDScriptParser::Node::UNARY_OPERATOR:
+ reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node));
+ break;
+ case GDScriptParser::Node::BREAK:
+ case GDScriptParser::Node::BREAKPOINT:
+ case GDScriptParser::Node::CONTINUE:
+ case GDScriptParser::Node::ENUM:
+ case GDScriptParser::Node::PASS:
+ case GDScriptParser::Node::SIGNAL:
+ // Nothing to do.
+ break;
+ }
+}
+
+void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
+ // TODO: Add second validation function for annotations, so they can use checked types.
+}
+
+void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function) {
+ if (p_function->resolved_signature) {
+ return;
+ }
+ p_function->resolved_signature = true;
+
+ GDScriptParser::FunctionNode *previous_function = parser->current_function;
+ parser->current_function = p_function;
+
+ for (int i = 0; i < p_function->parameters.size(); i++) {
+ resolve_parameter(p_function->parameters[i]);
+#ifdef DEBUG_ENABLED
+ if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
+ parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, p_function->identifier->name, p_function->parameters[i]->identifier->name);
+ }
+ is_shadowing(p_function->parameters[i]->identifier, "function parameter");
+#endif // DEBUG_ENABLED
+#ifdef TOOLS_ENABLED
+ if (p_function->parameters[i]->default_value && p_function->parameters[i]->default_value->is_constant) {
+ p_function->default_arg_values.push_back(p_function->parameters[i]->default_value->reduced_value);
+ }
+#endif // TOOLS_ENABLED
+ }
+
+ if (p_function->identifier->name == "_init") {
+ // Constructor.
+ GDScriptParser::DataType return_type = parser->current_class->get_datatype();
+ return_type.is_meta_type = false;
+ p_function->set_datatype(return_type);
+ if (p_function->return_type) {
+ push_error("Constructor cannot have an explicit return type.", p_function->return_type);
+ }
+ } else {
+ GDScriptParser::DataType return_type = resolve_datatype(p_function->return_type);
+ p_function->set_datatype(return_type);
+ }
+
+ parser->current_function = previous_function;
+}
+
+void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function) {
+ if (p_function->resolved_body) {
+ return;
+ }
+ p_function->resolved_body = true;
+
+ GDScriptParser::FunctionNode *previous_function = parser->current_function;
+ parser->current_function = p_function;
+
+ resolve_suite(p_function->body);
+
+ GDScriptParser::DataType return_type = p_function->body->get_datatype();
+
+ if (p_function->get_datatype().has_no_type() && return_type.is_set()) {
+ // Use the suite inferred type if return isn't explicitly set.
+ return_type.type_source = GDScriptParser::DataType::INFERRED;
+ p_function->set_datatype(p_function->body->get_datatype());
+ } else if (p_function->get_datatype().is_hard_type() && (p_function->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_function->get_datatype().builtin_type != Variant::NIL)) {
+ if (!p_function->body->has_return && p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init) {
+ push_error(R"(Not all code paths return a value.)", p_function);
+ }
+ }
+
+ parser->current_function = previous_function;
+}
+
+void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
+ if (p_statement == nullptr) {
+ return;
+ }
+ switch (p_statement->type) {
+ case GDScriptParser::Node::IF:
+ case GDScriptParser::Node::FOR:
+ case GDScriptParser::Node::MATCH:
+ case GDScriptParser::Node::PATTERN:
+ case GDScriptParser::Node::RETURN:
+ case GDScriptParser::Node::WHILE:
+ // Use return or nested suite type as this suite type.
+ if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
+ // Mixed types.
+ // TODO: This could use the common supertype instead.
+ p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
+ p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
+ } else {
+ p_suite->set_datatype(p_statement->get_datatype());
+ p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
+ for (int i = 0; i < p_suite->statements.size(); i++) {
+ GDScriptParser::Node *stmt = p_suite->statements[i];
+ resolve_node(stmt);
+ decide_suite_type(p_suite, stmt);
+ }
+}
+
+void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
+ reduce_expression(p_if->condition);
+
+ resolve_suite(p_if->true_block);
+ p_if->set_datatype(p_if->true_block->get_datatype());
+
+ if (p_if->false_block != nullptr) {
+ resolve_suite(p_if->false_block);
+ decide_suite_type(p_if, p_if->false_block);
+ }
+}
+
+void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
+ bool list_resolved = false;
+
+ // Optimize constant range() call to not allocate an array.
+ // Use int, Vector2, Vector3 instead, which also can be used as range iterators.
+ if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
+ GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
+ GDScriptParser::Node::Type callee_type = call->get_callee_type();
+ if (callee_type == GDScriptParser::Node::IDENTIFIER) {
+ GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
+ if (callee->name == "range") {
+ list_resolved = true;
+ if (call->arguments.size() < 1) {
+ push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
+ } else if (call->arguments.size() > 3) {
+ push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
+ } else {
+ // Now we can optimize it.
+ bool all_is_constant = true;
+ Vector<Variant> args;
+ args.resize(call->arguments.size());
+ for (int i = 0; i < call->arguments.size(); i++) {
+ reduce_expression(call->arguments[i]);
+
+ if (!call->arguments[i]->is_constant) {
+ all_is_constant = false;
+ } else if (all_is_constant) {
+ args.write[i] = call->arguments[i]->reduced_value;
+ }
+
+ GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
+ if (!arg_type.is_variant()) {
+ if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
+ all_is_constant = false;
+ push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
+ } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
+ all_is_constant = false;
+ push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
+ }
+ }
+ }
+
+ Variant reduced;
+
+ if (all_is_constant) {
+ switch (args.size()) {
+ case 1:
+ reduced = args[0];
+ break;
+ case 2:
+ reduced = Vector2i(args[0], args[1]);
+ break;
+ case 3:
+ reduced = Vector3i(args[0], args[1], args[2]);
+ break;
+ }
+ p_for->list->is_constant = true;
+ p_for->list->reduced_value = reduced;
+ }
+ }
+
+ if (p_for->list->is_constant) {
+ p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
+ } else {
+ GDScriptParser::DataType list_type;
+ list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ list_type.kind = GDScriptParser::DataType::BUILTIN;
+ list_type.builtin_type = Variant::ARRAY;
+ p_for->list->set_datatype(list_type);
+ }
+ }
+ }
+ }
+
+ if (!list_resolved) {
+ resolve_node(p_for->list);
+ }
+
+ // TODO: If list is a typed array, the variable should be an element.
+ // Also applicable for constant range() (so variable is int or float).
+
+ resolve_suite(p_for->loop);
+ p_for->set_datatype(p_for->loop->get_datatype());
+#ifdef DEBUG_ENABLED
+ if (p_for->variable) {
+ is_shadowing(p_for->variable, R"("for" iterator variable)");
+ }
+#endif
+}
+
+void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
+ resolve_node(p_while->condition);
+
+ resolve_suite(p_while->loop);
+ p_while->set_datatype(p_while->loop->get_datatype());
+}
+
+void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable) {
+ GDScriptParser::DataType type;
+ type.kind = GDScriptParser::DataType::VARIANT; // By default.
+
+ if (p_variable->initializer != nullptr) {
+ reduce_expression(p_variable->initializer);
+ type = p_variable->initializer->get_datatype();
+
+ if (p_variable->infer_datatype) {
+ type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+
+ if (type.has_no_type()) {
+ push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value does not have a set type.)", p_variable->identifier->name), p_variable->initializer);
+ } else if (type.is_variant()) {
+ push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value is a variant. Use explicit "Variant" type if this is intended.)", p_variable->identifier->name), p_variable->initializer);
+ } else if (type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
+ push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value is "null".)", p_variable->identifier->name), p_variable->initializer);
+ }
+ } else {
+ type.type_source = GDScriptParser::DataType::INFERRED;
+ }
+#ifdef DEBUG_ENABLED
+ if (p_variable->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
+ parser->push_warning(p_variable->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_variable->initializer)->function_name);
+ }
+#endif
+ }
+
+ if (p_variable->datatype_specifier != nullptr) {
+ type = resolve_datatype(p_variable->datatype_specifier);
+ type.is_meta_type = false;
+
+ if (p_variable->initializer != nullptr) {
+ if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true)) {
+ // Try reverse test since it can be a masked subtype.
+ if (!is_type_compatible(p_variable->initializer->get_datatype(), type, true)) {
+ push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer);
+ } else {
+ // TODO: Add warning.
+ mark_node_unsafe(p_variable->initializer);
+ }
+#ifdef DEBUG_ENABLED
+ } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
+#endif
+ }
+ if (p_variable->initializer->get_datatype().is_variant()) {
+ // TODO: Warn unsafe assign.
+ mark_node_unsafe(p_variable->initializer);
+ }
+ }
+ } else if (p_variable->infer_datatype) {
+ if (type.has_no_type()) {
+ push_error(vformat(R"(Cannot infer the type of variable "%s" because the initial value doesn't have a set type.)", p_variable->identifier->name), p_variable->identifier);
+ }
+ type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+ }
+
+ type.is_constant = false;
+ p_variable->set_datatype(type);
+
+#ifdef DEBUG_ENABLED
+ if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
+ parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
+ } else if (p_variable->assignments == 0) {
+ parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
+ }
+
+ is_shadowing(p_variable->identifier, "variable");
+#endif
+}
+
+void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant) {
+ GDScriptParser::DataType type;
+
+ if (p_constant->initializer != nullptr) {
+ reduce_expression(p_constant->initializer);
+ if (p_constant->initializer->type == GDScriptParser::Node::ARRAY) {
+ const_fold_array(static_cast<GDScriptParser::ArrayNode *>(p_constant->initializer));
+ } else if (p_constant->initializer->type == GDScriptParser::Node::DICTIONARY) {
+ const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_constant->initializer));
+ }
+
+ if (!p_constant->initializer->is_constant) {
+ push_error(vformat(R"(Assigned value for constant "%s" isn't a constant expression.)", p_constant->identifier->name), p_constant->initializer);
+ }
+
+ type = p_constant->initializer->get_datatype();
+
+#ifdef DEBUG_ENABLED
+ if (p_constant->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
+ parser->push_warning(p_constant->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_constant->initializer)->function_name);
+ }
+#endif
+ }
+
+ if (p_constant->datatype_specifier != nullptr) {
+ GDScriptParser::DataType explicit_type = resolve_datatype(p_constant->datatype_specifier);
+ explicit_type.is_meta_type = false;
+ if (!is_type_compatible(explicit_type, type)) {
+ push_error(vformat(R"(Assigned value for constant "%s" has type %s which is not compatible with defined type %s.)", p_constant->identifier->name, type.to_string(), explicit_type.to_string()), p_constant->initializer);
+#ifdef DEBUG_ENABLED
+ } else if (explicit_type.builtin_type == Variant::INT && type.builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
+#endif
+ }
+ type = explicit_type;
+ } else if (p_constant->infer_datatype) {
+ if (type.has_no_type()) {
+ push_error(vformat(R"(Cannot infer the type of constant "%s" because the initial value doesn't have a set type.)", p_constant->identifier->name), p_constant->identifier);
+ }
+ type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+ }
+
+ type.is_constant = true;
+ p_constant->set_datatype(type);
+
+#ifdef DEBUG_ENABLED
+ if (p_constant->usages == 0) {
+ parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
+ }
+
+ is_shadowing(p_constant->identifier, "constant");
+#endif
+}
+
+void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
+ reduce_expression(p_assert->condition);
+ if (p_assert->message != nullptr) {
+ reduce_expression(p_assert->message);
+ if (!p_assert->message->is_constant || p_assert->message->reduced_value.get_type() != Variant::STRING) {
+ push_error(R"(Expected constant string for assert error message.)", p_assert->message);
+ }
+ }
+
+ p_assert->set_datatype(p_assert->condition->get_datatype());
+
+#ifdef DEBUG_ENABLED
+ if (p_assert->condition->is_constant) {
+ if (p_assert->condition->reduced_value.booleanize()) {
+ parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
+ } else {
+ parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
+ }
+ }
+#endif
+}
+
+void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
+ reduce_expression(p_match->test);
+
+ for (int i = 0; i < p_match->branches.size(); i++) {
+ resolve_match_branch(p_match->branches[i], p_match->test);
+
+ decide_suite_type(p_match, p_match->branches[i]);
+ }
+}
+
+void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
+ for (int i = 0; i < p_match_branch->patterns.size(); i++) {
+ resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
+ }
+
+ resolve_suite(p_match_branch->block);
+
+ decide_suite_type(p_match_branch, p_match_branch->block);
+}
+
+void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
+ if (p_match_pattern == nullptr) {
+ return;
+ }
+
+ GDScriptParser::DataType result;
+
+ switch (p_match_pattern->pattern_type) {
+ case GDScriptParser::PatternNode::PT_LITERAL:
+ if (p_match_pattern->literal) {
+ reduce_literal(p_match_pattern->literal);
+ result = p_match_pattern->literal->get_datatype();
+ }
+ break;
+ case GDScriptParser::PatternNode::PT_EXPRESSION:
+ if (p_match_pattern->expression) {
+ reduce_expression(p_match_pattern->expression);
+ if (!p_match_pattern->expression->is_constant) {
+ push_error(R"(Expression in match pattern must be a constant.)", p_match_pattern->expression);
+ }
+ result = p_match_pattern->expression->get_datatype();
+ }
+ break;
+ case GDScriptParser::PatternNode::PT_BIND:
+ if (p_match_test != nullptr) {
+ result = p_match_test->get_datatype();
+ } else {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ }
+ p_match_pattern->bind->set_datatype(result);
+#ifdef DEBUG_ENABLED
+ is_shadowing(p_match_pattern->bind, "pattern bind");
+ if (p_match_pattern->bind->usages == 0) {
+ parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNASSIGNED_VARIABLE, p_match_pattern->bind->name);
+ }
+#endif
+ break;
+ case GDScriptParser::PatternNode::PT_ARRAY:
+ for (int i = 0; i < p_match_pattern->array.size(); i++) {
+ resolve_match_pattern(p_match_pattern->array[i], nullptr);
+ decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
+ }
+ result = p_match_pattern->get_datatype();
+ break;
+ case GDScriptParser::PatternNode::PT_DICTIONARY:
+ for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
+ if (p_match_pattern->dictionary[i].key) {
+ reduce_expression(p_match_pattern->dictionary[i].key);
+ if (!p_match_pattern->dictionary[i].key->is_constant) {
+ push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->expression);
+ }
+ }
+
+ if (p_match_pattern->dictionary[i].value_pattern) {
+ resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
+ decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
+ }
+ }
+ result = p_match_pattern->get_datatype();
+ break;
+ case GDScriptParser::PatternNode::PT_WILDCARD:
+ case GDScriptParser::PatternNode::PT_REST:
+ result.kind = GDScriptParser::DataType::VARIANT;
+ break;
+ }
+
+ p_match_pattern->set_datatype(result);
+}
+
+void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
+ GDScriptParser::DataType result;
+ result.kind = GDScriptParser::DataType::VARIANT;
+
+ if (p_parameter->default_value != nullptr) {
+ reduce_expression(p_parameter->default_value);
+ result = p_parameter->default_value->get_datatype();
+ if (p_parameter->infer_datatype) {
+ result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
+ } else {
+ result.type_source = GDScriptParser::DataType::INFERRED;
+ }
+ result.is_constant = false;
+ }
+
+ if (p_parameter->datatype_specifier != nullptr) {
+ resolve_datatype(p_parameter->datatype_specifier);
+ result = p_parameter->datatype_specifier->get_datatype();
+ result.is_meta_type = false;
+
+ if (p_parameter->default_value != nullptr) {
+ if (!is_type_compatible(result, p_parameter->default_value->get_datatype())) {
+ push_error(vformat(R"(Type of default value for parameter "%s" (%s) is not compatible with parameter type (%s).)", p_parameter->identifier->name, p_parameter->default_value->get_datatype().to_string(), p_parameter->datatype_specifier->get_datatype().to_string()), p_parameter->default_value);
+ } else if (p_parameter->default_value->get_datatype().is_variant()) {
+ mark_node_unsafe(p_parameter);
+ }
+ }
+ }
+
+ p_parameter->set_datatype(result);
+}
+
+void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
+ GDScriptParser::DataType result;
+
+ if (p_return->return_value != nullptr) {
+ reduce_expression(p_return->return_value);
+ result = p_return->return_value->get_datatype();
+ } else {
+ // Return type is null by default.
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = Variant::NIL;
+ result.is_constant = true;
+ }
+
+ GDScriptParser::DataType function_type = parser->current_function->get_datatype();
+ function_type.is_meta_type = false;
+ if (function_type.is_hard_type()) {
+ if (!is_type_compatible(function_type, result)) {
+ // Try other way. Okay but not safe.
+ if (!is_type_compatible(result, function_type)) {
+ push_error(vformat(R"(Cannot return value of type "%s" because the function return type is "%s".)", result.to_string(), function_type.to_string()), p_return);
+ } else {
+ // TODO: Add warning.
+ mark_node_unsafe(p_return);
+ }
+#ifdef DEBUG_ENABLED
+ } else if (function_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
+ } else if (result.is_variant()) {
+ mark_node_unsafe(p_return);
+#endif
+ }
+ }
+
+ p_return->set_datatype(result);
+}
+
+void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression) {
+ // This one makes some magic happen.
+
+ if (p_expression == nullptr) {
+ return;
+ }
+
+ if (p_expression->reduced) {
+ // Don't do this more than once.
+ return;
+ }
+
+ p_expression->reduced = true;
+
+ switch (p_expression->type) {
+ case GDScriptParser::Node::ARRAY:
+ reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::ASSIGNMENT:
+ reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::AWAIT:
+ reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::BINARY_OPERATOR:
+ reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::CALL:
+ reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::CAST:
+ reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::DICTIONARY:
+ reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::GET_NODE:
+ reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::IDENTIFIER:
+ reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::LITERAL:
+ reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::PRELOAD:
+ reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::SELF:
+ reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::SUBSCRIPT:
+ reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::TERNARY_OPERATOR:
+ reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
+ break;
+ case GDScriptParser::Node::UNARY_OPERATOR:
+ reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
+ break;
+ // Non-expressions. Here only to make sure new nodes aren't forgotten.
+ case GDScriptParser::Node::NONE:
+ case GDScriptParser::Node::ANNOTATION:
+ case GDScriptParser::Node::ASSERT:
+ case GDScriptParser::Node::BREAK:
+ case GDScriptParser::Node::BREAKPOINT:
+ case GDScriptParser::Node::CLASS:
+ case GDScriptParser::Node::CONSTANT:
+ case GDScriptParser::Node::CONTINUE:
+ case GDScriptParser::Node::ENUM:
+ case GDScriptParser::Node::FOR:
+ case GDScriptParser::Node::FUNCTION:
+ case GDScriptParser::Node::IF:
+ case GDScriptParser::Node::MATCH:
+ case GDScriptParser::Node::MATCH_BRANCH:
+ case GDScriptParser::Node::PARAMETER:
+ case GDScriptParser::Node::PASS:
+ case GDScriptParser::Node::PATTERN:
+ case GDScriptParser::Node::RETURN:
+ case GDScriptParser::Node::SIGNAL:
+ case GDScriptParser::Node::SUITE:
+ case GDScriptParser::Node::TYPE:
+ case GDScriptParser::Node::VARIABLE:
+ case GDScriptParser::Node::WHILE:
+ ERR_FAIL_MSG("Reaching unreachable case");
+ }
+}
+
+void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
+ for (int i = 0; i < p_array->elements.size(); i++) {
+ GDScriptParser::ExpressionNode *element = p_array->elements[i];
+ reduce_expression(element);
+ }
+
+ // It's array in any case.
+ GDScriptParser::DataType arr_type;
+ arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ arr_type.kind = GDScriptParser::DataType::BUILTIN;
+ arr_type.builtin_type = Variant::ARRAY;
+ arr_type.is_constant = true;
+
+ p_array->set_datatype(arr_type);
+}
+
+void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
+ reduce_expression(p_assignment->assignee);
+ reduce_expression(p_assignment->assigned_value);
+
+ if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
+ return;
+ }
+
+ if (p_assignment->assignee->get_datatype().is_constant) {
+ push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
+ }
+
+ if (!p_assignment->assignee->get_datatype().is_variant() && !p_assignment->assigned_value->get_datatype().is_variant()) {
+ bool compatible = true;
+ GDScriptParser::DataType op_type = p_assignment->assigned_value->get_datatype();
+ if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
+ op_type = get_operation_type(p_assignment->variant_op, p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype(), compatible, p_assignment->assigned_value);
+ }
+
+ if (compatible) {
+ compatible = is_type_compatible(p_assignment->assignee->get_datatype(), op_type, true);
+ if (!compatible) {
+ if (p_assignment->assignee->get_datatype().is_hard_type()) {
+ // Try reverse test since it can be a masked subtype.
+ if (!is_type_compatible(op_type, p_assignment->assignee->get_datatype(), true)) {
+ push_error(vformat(R"(Cannot assign a value of type "%s" to a target of type "%s".)", p_assignment->assigned_value->get_datatype().to_string(), p_assignment->assignee->get_datatype().to_string()), p_assignment->assigned_value);
+ } else {
+ // TODO: Add warning.
+ mark_node_unsafe(p_assignment);
+ }
+ } else {
+ // TODO: Warning in this case.
+ mark_node_unsafe(p_assignment);
+ }
+ }
+ } else {
+ push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", p_assignment->assignee->get_datatype().to_string(), p_assignment->assigned_value->get_datatype().to_string()), p_assignment);
+ }
+ }
+
+ if (p_assignment->assignee->get_datatype().has_no_type() || p_assignment->assigned_value->get_datatype().is_variant()) {
+ mark_node_unsafe(p_assignment);
+ }
+
+ if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
+ // Change source type so it's not wrongly detected later.
+ GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
+
+ switch (identifier->source) {
+ case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
+ GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
+ if (!id_type.is_hard_type()) {
+ id_type.kind = GDScriptParser::DataType::VARIANT;
+ id_type.type_source = GDScriptParser::DataType::UNDETECTED;
+ identifier->variable_source->set_datatype(id_type);
+ }
+ } break;
+ case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
+ GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
+ if (!id_type.is_hard_type()) {
+ id_type = p_assignment->assigned_value->get_datatype();
+ id_type.type_source = GDScriptParser::DataType::INFERRED;
+ id_type.is_constant = false;
+ identifier->variable_source->set_datatype(id_type);
+ }
+ } break;
+ case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
+ GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
+ if (!id_type.is_hard_type()) {
+ id_type = p_assignment->assigned_value->get_datatype();
+ id_type.type_source = GDScriptParser::DataType::INFERRED;
+ id_type.is_constant = false;
+ identifier->variable_source->set_datatype(id_type);
+ }
+ } break;
+ default:
+ // Nothing to do.
+ break;
+ }
+ }
+
+ GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
+ GDScriptParser::DataType assigned_type = p_assignment->assigned_value->get_datatype();
+#ifdef DEBUG_ENABLED
+ if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_type.kind == GDScriptParser::DataType::BUILTIN && assigned_type.builtin_type == Variant::NIL) {
+ parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
+ } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_type.builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
+ }
+#endif
+}
+
+void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
+ if (p_await->to_await == nullptr) {
+ GDScriptParser::DataType await_type;
+ await_type.kind = GDScriptParser::DataType::VARIANT;
+ p_await->set_datatype(await_type);
+ return;
+ }
+ if (p_await->to_await->type == GDScriptParser::Node::CALL) {
+ reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
+ } else {
+ reduce_expression(p_await->to_await);
+ }
+
+ p_await->is_constant = p_await->to_await->is_constant;
+ p_await->reduced_value = p_await->to_await->reduced_value;
+
+ GDScriptParser::DataType awaiting_type = p_await->to_await->get_datatype();
+
+ p_await->set_datatype(awaiting_type);
+
+#ifdef DEBUG_ENABLED
+ if (!awaiting_type.is_coroutine && awaiting_type.builtin_type != Variant::SIGNAL) {
+ parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
+ }
+#endif
+}
+
+void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
+ reduce_expression(p_binary_op->left_operand);
+
+ if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
+ reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
+ } else {
+ reduce_expression(p_binary_op->right_operand);
+ }
+ // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
+
+ GDScriptParser::DataType left_type;
+ if (p_binary_op->left_operand) {
+ left_type = p_binary_op->left_operand->get_datatype();
+ }
+ GDScriptParser::DataType right_type;
+ if (p_binary_op->right_operand) {
+ right_type = p_binary_op->right_operand->get_datatype();
+ }
+
+ if (!left_type.is_set() || !right_type.is_set()) {
+ return;
+ }
+
+#ifdef DEBUG_ENABLED
+ if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
+ parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
+ }
+#endif
+
+ if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
+ p_binary_op->is_constant = true;
+ if (p_binary_op->variant_op < Variant::OP_MAX) {
+ bool valid = false;
+ Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid);
+ if (!valid) {
+ if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
+ push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
+ } else {
+ push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
+ Variant::get_operator_name(p_binary_op->variant_op),
+ Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
+ Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
+ p_binary_op);
+ }
+ }
+ } else {
+ if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
+ GDScriptParser::DataType test_type = right_type;
+ test_type.is_meta_type = false;
+
+ if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
+ push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
+ p_binary_op->reduced_value = false;
+ } else {
+ p_binary_op->reduced_value = true;
+ }
+ } else {
+ ERR_PRINT("Parser bug: unknown binary operation.");
+ }
+ }
+ p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
+
+ return;
+ }
+
+ GDScriptParser::DataType result;
+
+ if (left_type.is_variant() || right_type.is_variant()) {
+ // Cannot infer type because one operand can be anything.
+ result.kind = GDScriptParser::DataType::VARIANT;
+ mark_node_unsafe(p_binary_op);
+ } else {
+ if (p_binary_op->variant_op < Variant::OP_MAX) {
+ bool valid = false;
+ result = get_operation_type(p_binary_op->variant_op, p_binary_op->left_operand->get_datatype(), right_type, valid, p_binary_op);
+
+ if (!valid) {
+ push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", p_binary_op->left_operand->get_datatype().to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
+ }
+ } else {
+ if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
+ GDScriptParser::DataType test_type = right_type;
+ test_type.is_meta_type = false;
+
+ if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
+ // Test reverse as well to consider for subtypes.
+ if (!is_type_compatible(p_binary_op->left_operand->get_datatype(), test_type, false)) {
+ if (p_binary_op->left_operand->get_datatype().is_hard_type()) {
+ push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", p_binary_op->left_operand->get_datatype().to_string(), test_type.to_string()), p_binary_op->left_operand);
+ } else {
+ // TODO: Warning.
+ mark_node_unsafe(p_binary_op);
+ }
+ }
+ }
+
+ // "is" operator is always a boolean anyway.
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = Variant::BOOL;
+ } else {
+ ERR_PRINT("Parser bug: unknown binary operation.");
+ }
+ }
+ }
+
+ p_binary_op->set_datatype(result);
+}
+
+void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_await) {
+ bool all_is_constant = true;
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ reduce_expression(p_call->arguments[i]);
+ all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
+ }
+
+ GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
+ GDScriptParser::DataType call_type;
+
+ if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
+ // Call to name directly.
+ StringName function_name = p_call->function_name;
+ Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
+
+ if (builtin_type < Variant::VARIANT_MAX) {
+ // Is a builtin constructor.
+ call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ call_type.kind = GDScriptParser::DataType::BUILTIN;
+ call_type.builtin_type = builtin_type;
+
+ if (builtin_type == Variant::OBJECT) {
+ call_type.kind = GDScriptParser::DataType::NATIVE;
+ call_type.native_type = function_name; // "Object".
+ }
+
+ bool safe_to_fold = true;
+ switch (builtin_type) {
+ // Those are stored by reference so not suited for compile-time construction.
+ // Because in this case they would be the same reference in all constructed values.
+ case Variant::OBJECT:
+ case Variant::DICTIONARY:
+ case Variant::ARRAY:
+ case Variant::PACKED_BYTE_ARRAY:
+ case Variant::PACKED_INT32_ARRAY:
+ case Variant::PACKED_INT64_ARRAY:
+ case Variant::PACKED_FLOAT32_ARRAY:
+ case Variant::PACKED_FLOAT64_ARRAY:
+ case Variant::PACKED_STRING_ARRAY:
+ case Variant::PACKED_VECTOR2_ARRAY:
+ case Variant::PACKED_VECTOR3_ARRAY:
+ case Variant::PACKED_COLOR_ARRAY:
+ safe_to_fold = false;
+ break;
+ default:
+ break;
+ }
+
+ if (all_is_constant && safe_to_fold) {
+ // Construct here.
+ Vector<const Variant *> args;
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ args.push_back(&(p_call->arguments[i]->reduced_value));
+ }
+
+ Callable::CallError err;
+ Variant value;
+ Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
+
+ switch (err.error) {
+ case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
+ push_error(vformat(R"(Invalid argument for %s constructor: argument %d should be %s but is %s.)", Variant::get_type_name(builtin_type), err.argument + 1,
+ Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
+ p_call->arguments[err.argument]);
+ break;
+ case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
+ String signature = Variant::get_type_name(builtin_type) + "(";
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ if (i > 0) {
+ signature += ", ";
+ }
+ signature += p_call->arguments[i]->get_datatype().to_string();
+ }
+ signature += ")";
+ push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
+ } break;
+ case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
+ push_error(vformat(R"(Too many arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
+ push_error(vformat(R"(Too few arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
+ break; // Can't happen in a builtin constructor.
+ case Callable::CallError::CALL_OK:
+ p_call->is_constant = true;
+ p_call->reduced_value = value;
+ break;
+ }
+ } else {
+ // TODO: Check constructors without constants.
+
+ // If there's one argument, try to use copy constructor (those aren't explicitly defined).
+ if (p_call->arguments.size() == 1) {
+ GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
+ if (arg_type.is_variant()) {
+ mark_node_unsafe(p_call->arguments[0]);
+ } else {
+ if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
+ // Okay.
+ p_call->set_datatype(call_type);
+ return;
+ }
+ }
+ }
+ List<MethodInfo> constructors;
+ Variant::get_constructor_list(builtin_type, &constructors);
+ bool match = false;
+
+ for (const List<MethodInfo>::Element *E = constructors.front(); E != nullptr; E = E->next()) {
+ const MethodInfo &info = E->get();
+
+ if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
+ continue;
+ }
+ if (p_call->arguments.size() > info.arguments.size()) {
+ continue;
+ }
+
+ bool types_match = true;
+
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
+
+ if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) {
+ types_match = false;
+ break;
+#ifdef DEBUG_ENABLED
+ } else {
+ if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
+ }
+#endif
+ }
+ }
+
+ if (types_match) {
+ match = true;
+ call_type = type_from_property(info.return_val);
+ break;
+ }
+ }
+
+ if (!match) {
+ String signature = Variant::get_type_name(builtin_type) + "(";
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ if (i > 0) {
+ signature += ", ";
+ }
+ signature += p_call->arguments[i]->get_datatype().to_string();
+ }
+ signature += ")";
+ push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
+ }
+ }
+ p_call->set_datatype(call_type);
+ return;
+ } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
+ MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
+
+ if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
+ // Can call on compilation.
+ Vector<const Variant *> args;
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ args.push_back(&(p_call->arguments[i]->reduced_value));
+ }
+
+ Variant value;
+ Callable::CallError err;
+ GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
+
+ switch (err.error) {
+ case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
+ PropertyInfo wrong_arg = function_info.arguments[err.argument];
+ push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
+ type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
+ p_call->arguments[err.argument]);
+ } break;
+ case Callable::CallError::CALL_ERROR_INVALID_METHOD:
+ push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
+ push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
+ push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
+ break; // Can't happen in a builtin constructor.
+ case Callable::CallError::CALL_OK:
+ p_call->is_constant = true;
+ p_call->reduced_value = value;
+ break;
+ }
+ } else {
+ validate_call_arg(function_info, p_call);
+ }
+ p_call->set_datatype(type_from_property(function_info.return_val));
+ return;
+ } else if (Variant::has_utility_function(function_name)) {
+ MethodInfo function_info = info_from_utility_func(function_name);
+
+ if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
+ // Can call on compilation.
+ Vector<const Variant *> args;
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ args.push_back(&(p_call->arguments[i]->reduced_value));
+ }
+
+ Variant value;
+ Callable::CallError err;
+ Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
+
+ switch (err.error) {
+ case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
+ PropertyInfo wrong_arg = function_info.arguments[err.argument];
+ push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
+ type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
+ p_call->arguments[err.argument]);
+ } break;
+ case Callable::CallError::CALL_ERROR_INVALID_METHOD:
+ push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
+ push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
+ push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
+ break;
+ case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
+ break; // Can't happen in a builtin constructor.
+ case Callable::CallError::CALL_OK:
+ p_call->is_constant = true;
+ p_call->reduced_value = value;
+ break;
+ }
+ } else {
+ validate_call_arg(function_info, p_call);
+ }
+ p_call->set_datatype(type_from_property(function_info.return_val));
+ return;
+ }
+ }
+
+ GDScriptParser::DataType base_type;
+ call_type.kind = GDScriptParser::DataType::VARIANT;
+ bool is_self = false;
+
+ if (p_call->is_super) {
+ base_type = parser->current_class->base_type;
+ is_self = true;
+ } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
+ base_type = parser->current_class->get_datatype();
+ is_self = true;
+ } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
+ GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
+ if (!subscript->is_attribute) {
+ // Invalid call. Error already sent in parser.
+ // TODO: Could check if Callable here.
+ p_call->set_datatype(call_type);
+ mark_node_unsafe(p_call);
+ return;
+ }
+ reduce_expression(subscript->base);
+
+ base_type = subscript->base->get_datatype();
+ } else {
+ // Invalid call. Error already sent in parser.
+ // TODO: Could check if Callable here too.
+ p_call->set_datatype(call_type);
+ mark_node_unsafe(p_call);
+ return;
+ }
+
+ bool is_static = false;
+ bool is_vararg = false;
+ int default_arg_count = 0;
+ GDScriptParser::DataType return_type;
+ List<GDScriptParser::DataType> par_types;
+
+ if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
+ validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
+
+ if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
+ push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parser->current_function->identifier->name), p_call->callee);
+ }
+
+ call_type = return_type;
+ } else {
+ // Check if the name exists as something else.
+ bool found = false;
+ if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) {
+ GDScriptParser::IdentifierNode *callee_id;
+ if (callee_type == GDScriptParser::Node::IDENTIFIER) {
+ callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
+ } else {
+ // Can only be attribute.
+ callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
+ }
+ if (callee_id) {
+ reduce_identifier_from_base(callee_id, &base_type);
+ GDScriptParser::DataType callee_datatype = callee_id->get_datatype();
+ if (callee_datatype.is_set() && !callee_datatype.is_variant()) {
+ found = true;
+ if (callee_datatype.builtin_type == Variant::CALLABLE) {
+ push_error(vformat(R"*(Name "%s" is a Callable. You can call it with "%s.call()" instead.)*", p_call->function_name, p_call->function_name), p_call->callee);
+ } else {
+ push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);
+ }
+#ifdef DEBUG_ENABLED
+ } else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {
+ parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
+ mark_node_unsafe(p_call);
+#endif
+ }
+ }
+ }
+ if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {
+ String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
+ push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);
+ }
+ }
+
+ if (call_type.is_coroutine && !is_await) {
+ push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call->callee);
+ }
+
+ p_call->set_datatype(call_type);
+}
+
+void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
+ reduce_expression(p_cast->operand);
+
+ GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type);
+
+ if (!cast_type.is_set()) {
+ return;
+ }
+
+ cast_type.is_meta_type = false; // The casted value won't be a type name.
+ p_cast->set_datatype(cast_type);
+
+ if (!cast_type.is_variant()) {
+ GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
+ if (!op_type.is_variant()) {
+ bool valid = false;
+ if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
+ valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
+ } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
+ valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
+ }
+
+ if (!valid) {
+ push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
+ }
+ }
+ } else {
+ mark_node_unsafe(p_cast);
+ }
+#ifdef DEBUG_ENABLED
+ if (p_cast->operand->get_datatype().is_variant()) {
+ parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
+ mark_node_unsafe(p_cast);
+ }
+#endif
+
+ // TODO: Perform cast on constants.
+}
+
+void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
+ HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, VariantComparator> elements;
+
+ for (int i = 0; i < p_dictionary->elements.size(); i++) {
+ const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
+ if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {
+ reduce_expression(element.key);
+ }
+ reduce_expression(element.value);
+
+ if (element.key->is_constant) {
+ if (elements.has(element.key->reduced_value)) {
+ push_error(vformat(R"(Key "%s" was already used in this dictionary (at line %d).)", element.key->reduced_value, elements[element.key->reduced_value]->start_line), element.key);
+ } else {
+ elements[element.key->reduced_value] = element.value;
+ }
+ }
+ }
+
+ // It's dictionary in any case.
+ GDScriptParser::DataType dict_type;
+ dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ dict_type.kind = GDScriptParser::DataType::BUILTIN;
+ dict_type.builtin_type = Variant::DICTIONARY;
+ dict_type.is_constant = true;
+
+ p_dictionary->set_datatype(dict_type);
+}
+
+void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
+ GDScriptParser::DataType result;
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.native_type = "Node";
+ result.builtin_type = Variant::OBJECT;
+
+ if (!ClassDB::is_parent_class(get_real_class_name(parser->current_class->base_type.native_type), result.native_type)) {
+ push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
+ }
+
+ p_get_node->set_datatype(result);
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {
+ Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name));
+ Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+
+ if (err) {
+ push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::UNDETECTED;
+ type.kind = GDScriptParser::DataType::VARIANT;
+ return type;
+ }
+
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = GDScriptParser::DataType::CLASS;
+ type.builtin_type = Variant::OBJECT;
+ type.native_type = ScriptServer::get_global_class_native_base(p_class_name);
+ type.class_type = ref->get_parser()->head;
+ type.script_path = ref->get_parser()->script_path;
+ type.is_constant = true;
+ type.is_meta_type = true;
+ return type;
+}
+
+void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
+ GDScriptParser::DataType base;
+ if (p_base == nullptr) {
+ base = type_from_metatype(parser->current_class->get_datatype());
+ } else {
+ base = *p_base;
+ }
+
+ const StringName &name = p_identifier->name;
+
+ if (base.kind == GDScriptParser::DataType::BUILTIN) {
+ if (base.is_meta_type) {
+ bool valid = true;
+ Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
+ if (valid) {
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = result;
+ p_identifier->set_datatype(type_from_variant(result, p_identifier));
+ } else {
+ push_error(vformat(R"(Cannot find constant "%s" on type "%s".)", name, base.to_string()), p_identifier);
+ }
+ } else {
+ switch (base.builtin_type) {
+ case Variant::NIL: {
+ push_error(vformat(R"(Invalid get index "%s" on base Nil)", name), p_identifier);
+ return;
+ }
+ case Variant::DICTIONARY: {
+ GDScriptParser::DataType dummy;
+ dummy.kind = GDScriptParser::DataType::VARIANT;
+ p_identifier->set_datatype(dummy);
+ return;
+ }
+ default: {
+ Callable::CallError temp;
+ Variant dummy;
+ Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);
+ List<PropertyInfo> properties;
+ dummy.get_property_list(&properties);
+ for (const List<PropertyInfo>::Element *E = properties.front(); E != nullptr; E = E->next()) {
+ const PropertyInfo &prop = E->get();
+ if (prop.name == name) {
+ p_identifier->set_datatype(type_from_property(prop));
+ return;
+ }
+ }
+ push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
+ }
+ }
+ }
+ return;
+ }
+
+ if (base.kind == GDScriptParser::DataType::ENUM) {
+ if (base.is_meta_type) {
+ if (base.enum_values.has(name)) {
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = base.enum_values[name];
+
+ GDScriptParser::DataType result;
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ result.kind = GDScriptParser::DataType::ENUM_VALUE;
+ result.native_type = base.native_type;
+ result.enum_type = name;
+ p_identifier->set_datatype(result);
+ } else {
+ push_error(vformat(R"(Cannot find value "%s" in "%s".)", name, base.to_string()), p_identifier);
+ }
+ } else {
+ push_error(R"(Cannot get property from enum value.)", p_identifier);
+ }
+ return;
+ }
+
+ GDScriptParser::ClassNode *base_class = base.class_type;
+
+ // TODO: Switch current class/function/suite here to avoid misrepresenting identifiers (in recursive reduce calls).
+ while (base_class != nullptr) {
+ if (base_class->identifier && base_class->identifier->name == name) {
+ p_identifier->set_datatype(base_class->get_datatype());
+ return;
+ }
+ if (base_class->has_member(name)) {
+ const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
+ p_identifier->set_datatype(member.get_datatype());
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::CONSTANT:
+ // For out-of-order resolution:
+ reduce_expression(member.constant->initializer);
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = member.constant->initializer->reduced_value;
+ p_identifier->set_datatype(member.constant->initializer->get_datatype());
+ p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
+ p_identifier->constant_source = member.constant;
+ break;
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE:
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = member.enum_value.value;
+ break;
+ case GDScriptParser::ClassNode::Member::VARIABLE:
+ p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
+ p_identifier->variable_source = member.variable;
+ break;
+ case GDScriptParser::ClassNode::Member::FUNCTION:
+ resolve_function_signature(member.function);
+ p_identifier->set_datatype(make_callable_type(member.function->info));
+ break;
+ default:
+ break; // Type already set.
+ }
+ return;
+ }
+ // Check outer constants.
+ // TODO: Allow outer static functions.
+ GDScriptParser::ClassNode *outer = base_class->outer;
+ while (outer != nullptr) {
+ if (outer->has_member(name)) {
+ const GDScriptParser::ClassNode::Member &member = outer->get_member(name);
+ if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) {
+ // TODO: Make sure loops won't cause problem. And make special error message for those.
+ // For out-of-order resolution:
+ reduce_expression(member.constant->initializer);
+ p_identifier->set_datatype(member.get_datatype());
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = member.constant->initializer->reduced_value;
+ return;
+ }
+ }
+ outer = outer->outer;
+ }
+
+ base_class = base_class->base_type.class_type;
+ }
+
+ // Check native members.
+ const StringName &native = get_real_class_name(base.native_type);
+
+ if (class_exists(native)) {
+ PropertyInfo prop_info;
+ MethodInfo method_info;
+ if (ClassDB::get_property_info(native, name, &prop_info)) {
+ p_identifier->set_datatype(type_from_property(prop_info));
+ return;
+ }
+ if (ClassDB::get_method_info(native, name, &method_info)) {
+ // Method is callable.
+ p_identifier->set_datatype(make_callable_type(method_info));
+ return;
+ }
+ if (ClassDB::get_signal(native, name, &method_info)) {
+ // Signal is a type too.
+ p_identifier->set_datatype(make_signal_type(method_info));
+ return;
+ }
+ if (ClassDB::has_enum(native, name)) {
+ p_identifier->set_datatype(make_native_enum_type(native, name));
+ return;
+ }
+ bool valid = false;
+ int int_constant = ClassDB::get_integer_constant(native, name, &valid);
+ if (valid) {
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = int_constant;
+ p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
+ return;
+ }
+ }
+}
+
+void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
+ // TODO: This is opportunity to further infer types.
+
+ // Check if we are inside and enum. This allows enum values to access other elements of the same enum.
+ if (current_enum) {
+ for (int i = 0; i < current_enum->values.size(); i++) {
+ const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
+ if (element.identifier->name == p_identifier->name) {
+ GDScriptParser::DataType type;
+ type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ type.kind = element.parent_enum->identifier ? GDScriptParser::DataType::ENUM_VALUE : GDScriptParser::DataType::BUILTIN;
+ type.builtin_type = Variant::INT;
+ type.is_constant = true;
+ if (element.parent_enum->identifier) {
+ type.enum_type = element.parent_enum->identifier->name;
+ }
+ p_identifier->set_datatype(type);
+
+ if (element.resolved) {
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = element.value;
+ } else {
+ push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
+ }
+ return; // Found anyway.
+ }
+ }
+ }
+
+ // Check if identifier is local.
+ // If that's the case, the declaration already was solved before.
+ switch (p_identifier->source) {
+ case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
+ p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
+ return;
+ case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
+ case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
+ p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
+ p_identifier->is_constant = true;
+ // TODO: Constant should have a value on the node itself.
+ p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
+ return;
+ case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
+ p_identifier->variable_source->usages++;
+ [[fallthrough]];
+ case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
+ p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
+ return;
+ case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
+ p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
+ return;
+ case GDScriptParser::IdentifierNode::LOCAL_BIND: {
+ GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
+ result.is_constant = true;
+ p_identifier->set_datatype(result);
+ return;
+ }
+ case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
+ break;
+ }
+
+ // Not a local, so check members.
+ reduce_identifier_from_base(p_identifier);
+ if (p_identifier->get_datatype().is_set()) {
+ // Found.
+ return;
+ }
+
+ StringName name = p_identifier->name;
+ p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
+
+ // Check globals. We make an exception for Variant::OBJECT because it's the base class for
+ // non-builtin types so we allow doing e.g. Object.new()
+ Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
+ if (builtin_type != Variant::OBJECT && builtin_type < Variant::VARIANT_MAX) {
+ if (can_be_builtin) {
+ p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
+ return;
+ } else {
+ push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
+ }
+ }
+
+ if (class_exists(name)) {
+ p_identifier->set_datatype(make_native_meta_type(name));
+ return;
+ }
+
+ if (ScriptServer::is_global_class(name)) {
+ p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
+ return;
+ }
+
+ // Try singletons.
+ // Do this before globals because this might be a singleton loading another one before it's compiled.
+ if (ProjectSettings::get_singleton()->has_autoload(name)) {
+ const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
+ if (autoload.is_singleton) {
+ // Singleton exists, so it's at least a Node.
+ GDScriptParser::DataType result;
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ if (autoload.path.to_lower().ends_with(GDScriptLanguage::get_singleton()->get_extension())) {
+ Ref<GDScriptParserRef> parser = get_parser_for(autoload.path);
+ if (parser.is_valid()) {
+ Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+ if (err == OK) {
+ result = type_from_metatype(parser->get_parser()->head->get_datatype());
+ }
+ }
+ }
+ result.is_constant = true;
+ p_identifier->set_datatype(result);
+ return;
+ }
+ }
+
+ if (GDScriptLanguage::get_singleton()->get_global_map().has(name)) {
+ int idx = GDScriptLanguage::get_singleton()->get_global_map()[name];
+ Variant constant = GDScriptLanguage::get_singleton()->get_global_array()[idx];
+ p_identifier->set_datatype(type_from_variant(constant, p_identifier));
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = constant;
+ return;
+ }
+
+ if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(name)) {
+ Variant constant = GDScriptLanguage::get_singleton()->get_named_globals_map()[name];
+ p_identifier->set_datatype(type_from_variant(constant, p_identifier));
+ p_identifier->is_constant = true;
+ p_identifier->reduced_value = constant;
+ return;
+ }
+
+ // Not found.
+ // Check if it's a builtin function.
+ if (GDScriptUtilityFunctions::function_exists(name)) {
+ push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
+ } else {
+ push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
+ }
+ GDScriptParser::DataType dummy;
+ dummy.kind = GDScriptParser::DataType::VARIANT;
+ p_identifier->set_datatype(dummy); // Just so type is set to something.
+}
+
+void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
+ p_literal->reduced_value = p_literal->value;
+ p_literal->is_constant = true;
+
+ p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
+}
+
+void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
+ if (!p_preload->path) {
+ return;
+ }
+
+ reduce_expression(p_preload->path);
+
+ if (!p_preload->path->is_constant) {
+ push_error("Preloaded path must be a constant string.", p_preload->path);
+ return;
+ }
+
+ if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
+ push_error("Preloaded path must be a constant string.", p_preload->path);
+ } else {
+ p_preload->resolved_path = p_preload->path->reduced_value;
+ // TODO: Save this as script dependency.
+ if (p_preload->resolved_path.is_rel_path()) {
+ p_preload->resolved_path = parser->script_path.get_base_dir().plus_file(p_preload->resolved_path);
+ }
+ p_preload->resolved_path = p_preload->resolved_path.simplify_path();
+ if (!FileAccess::exists(p_preload->resolved_path)) {
+ push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
+ } else {
+ // TODO: Don't load if validating: use completion cache.
+ p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
+ if (p_preload->resource.is_null()) {
+ push_error(vformat(R"(Could not p_preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
+ }
+ }
+ }
+
+ p_preload->is_constant = true;
+ p_preload->reduced_value = p_preload->resource;
+ p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
+}
+
+void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
+ p_self->is_constant = false;
+ p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
+}
+
+void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
+ if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
+ reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
+ } else {
+ reduce_expression(p_subscript->base);
+ }
+
+ GDScriptParser::DataType result_type;
+
+ // Reduce index first. If it's a constant StringName, use attribute instead.
+ if (!p_subscript->is_attribute) {
+ if (p_subscript->index == nullptr) {
+ return;
+ }
+ reduce_expression(p_subscript->index);
+
+ if (p_subscript->index->is_constant && p_subscript->index->reduced_value.get_type() == Variant::STRING_NAME) {
+ GDScriptParser::IdentifierNode *attribute = parser->alloc_node<GDScriptParser::IdentifierNode>();
+ // Copy location for better error message.
+ attribute->start_line = p_subscript->index->start_line;
+ attribute->end_line = p_subscript->index->end_line;
+ attribute->leftmost_column = p_subscript->index->leftmost_column;
+ attribute->rightmost_column = p_subscript->index->rightmost_column;
+ p_subscript->is_attribute = true;
+ p_subscript->attribute = attribute;
+ }
+ }
+
+ if (p_subscript->is_attribute) {
+ if (p_subscript->attribute == nullptr) {
+ return;
+ }
+ if (p_subscript->base->is_constant) {
+ // Just try to get it.
+ bool valid = false;
+ Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
+ if (!valid) {
+ push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index);
+ } else {
+ p_subscript->is_constant = true;
+ p_subscript->reduced_value = value;
+ result_type = type_from_variant(value, p_subscript);
+ }
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ } else {
+ GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
+
+ if (base_type.is_variant()) {
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ mark_node_unsafe(p_subscript);
+ } else {
+ reduce_identifier_from_base(p_subscript->attribute, &base_type);
+ GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
+ if (attr_type.is_set()) {
+ result_type = attr_type;
+ p_subscript->is_constant = p_subscript->attribute->is_constant;
+ p_subscript->reduced_value = p_subscript->attribute->reduced_value;
+ } else {
+ if (base_type.kind == GDScriptParser::DataType::BUILTIN) {
+ push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, base_type.to_string()), p_subscript->attribute);
+#ifdef DEBUG_ENABLED
+ } else {
+ parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
+#endif
+ }
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ }
+ }
+ }
+ } else {
+ // Index was already reduced before.
+
+ if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
+ // Just try to get it.
+ bool valid = false;
+ Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
+ if (!valid) {
+ push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
+ } else {
+ p_subscript->is_constant = true;
+ p_subscript->reduced_value = value;
+ result_type = type_from_variant(value, p_subscript);
+ }
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ } else {
+ GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
+ GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
+
+ if (base_type.is_variant()) {
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ mark_node_unsafe(p_subscript);
+ } else {
+ if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
+ // Check if indexing is valid.
+ bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
+ if (!error) {
+ switch (base_type.builtin_type) {
+ // Expect int or real as index.
+ case Variant::PACKED_BYTE_ARRAY:
+ case Variant::PACKED_COLOR_ARRAY:
+ case Variant::PACKED_FLOAT32_ARRAY:
+ case Variant::PACKED_FLOAT64_ARRAY:
+ case Variant::PACKED_INT32_ARRAY:
+ case Variant::PACKED_INT64_ARRAY:
+ case Variant::PACKED_STRING_ARRAY:
+ case Variant::PACKED_VECTOR2_ARRAY:
+ case Variant::PACKED_VECTOR3_ARRAY:
+ case Variant::ARRAY:
+ case Variant::STRING:
+ error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
+ break;
+ // Expect String only.
+ case Variant::RECT2:
+ case Variant::RECT2I:
+ case Variant::PLANE:
+ case Variant::QUAT:
+ case Variant::AABB:
+ case Variant::OBJECT:
+ error = index_type.builtin_type != Variant::STRING;
+ break;
+ // Expect String or number.
+ case Variant::BASIS:
+ case Variant::VECTOR2:
+ case Variant::VECTOR2I:
+ case Variant::VECTOR3:
+ case Variant::VECTOR3I:
+ case Variant::TRANSFORM:
+ case Variant::TRANSFORM2D:
+ error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
+ index_type.builtin_type != Variant::STRING;
+ break;
+ // Expect String or int.
+ case Variant::COLOR:
+ error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
+ break;
+ // Don't support indexing, but we will check it later.
+ case Variant::RID:
+ case Variant::BOOL:
+ case Variant::CALLABLE:
+ case Variant::FLOAT:
+ case Variant::INT:
+ case Variant::NIL:
+ case Variant::NODE_PATH:
+ case Variant::SIGNAL:
+ case Variant::STRING_NAME:
+ break;
+ // Here for completeness.
+ case Variant::DICTIONARY:
+ case Variant::VARIANT_MAX:
+ break;
+ }
+
+ if (error) {
+ push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);
+ }
+ }
+ } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
+ if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
+ push_error(vformat(R"(Only String or StringName can be used as index for type "%s", but received a "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);
+ }
+ }
+
+ // Check resulting type if possible.
+ result_type.builtin_type = Variant::NIL;
+ result_type.kind = GDScriptParser::DataType::BUILTIN;
+ result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
+
+ switch (base_type.builtin_type) {
+ // Can't index at all.
+ case Variant::RID:
+ case Variant::BOOL:
+ case Variant::CALLABLE:
+ case Variant::FLOAT:
+ case Variant::INT:
+ case Variant::NIL:
+ case Variant::NODE_PATH:
+ case Variant::SIGNAL:
+ case Variant::STRING_NAME:
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
+ break;
+ // Return int.
+ case Variant::PACKED_BYTE_ARRAY:
+ case Variant::PACKED_INT32_ARRAY:
+ case Variant::PACKED_INT64_ARRAY:
+ case Variant::VECTOR2I:
+ case Variant::VECTOR3I:
+ result_type.builtin_type = Variant::INT;
+ break;
+ // Return float.
+ case Variant::PACKED_FLOAT32_ARRAY:
+ case Variant::PACKED_FLOAT64_ARRAY:
+ case Variant::VECTOR2:
+ case Variant::VECTOR3:
+ case Variant::QUAT:
+ result_type.builtin_type = Variant::FLOAT;
+ break;
+ // Return Color.
+ case Variant::PACKED_COLOR_ARRAY:
+ result_type.builtin_type = Variant::COLOR;
+ break;
+ // Return String.
+ case Variant::PACKED_STRING_ARRAY:
+ case Variant::STRING:
+ result_type.builtin_type = Variant::STRING;
+ break;
+ // Return Vector2.
+ case Variant::PACKED_VECTOR2_ARRAY:
+ case Variant::TRANSFORM2D:
+ case Variant::RECT2:
+ result_type.builtin_type = Variant::VECTOR2;
+ break;
+ // Return Vector2I.
+ case Variant::RECT2I:
+ result_type.builtin_type = Variant::VECTOR2I;
+ break;
+ // Return Vector3.
+ case Variant::PACKED_VECTOR3_ARRAY:
+ case Variant::AABB:
+ case Variant::BASIS:
+ result_type.builtin_type = Variant::VECTOR3;
+ break;
+ // Depends on the index.
+ case Variant::TRANSFORM:
+ case Variant::PLANE:
+ case Variant::COLOR:
+ case Variant::ARRAY:
+ case Variant::DICTIONARY:
+ result_type.kind = GDScriptParser::DataType::VARIANT;
+ result_type.type_source = GDScriptParser::DataType::UNDETECTED;
+ break;
+ // Here for completeness.
+ case Variant::OBJECT:
+ case Variant::VARIANT_MAX:
+ break;
+ }
+ }
+ }
+ }
+
+ p_subscript->set_datatype(result_type);
+}
+
+void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
+ reduce_expression(p_ternary_op->condition);
+ reduce_expression(p_ternary_op->true_expr);
+ reduce_expression(p_ternary_op->false_expr);
+
+ GDScriptParser::DataType result;
+
+ if (p_ternary_op->condition && p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr && p_ternary_op->false_expr->is_constant) {
+ p_ternary_op->is_constant = true;
+ if (p_ternary_op->condition->reduced_value.booleanize()) {
+ p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
+ } else {
+ p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
+ }
+ }
+
+ GDScriptParser::DataType true_type;
+ if (p_ternary_op->true_expr) {
+ true_type = p_ternary_op->true_expr->get_datatype();
+ } else {
+ true_type.kind = GDScriptParser::DataType::VARIANT;
+ }
+ GDScriptParser::DataType false_type;
+ if (p_ternary_op->false_expr) {
+ false_type = p_ternary_op->false_expr->get_datatype();
+ } else {
+ false_type.kind = GDScriptParser::DataType::VARIANT;
+ }
+
+ if (true_type.is_variant() || false_type.is_variant()) {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ } else {
+ result = true_type;
+ if (!is_type_compatible(true_type, false_type)) {
+ result = false_type;
+ if (!is_type_compatible(false_type, true_type)) {
+ result.type_source = GDScriptParser::DataType::UNDETECTED;
+ result.kind = GDScriptParser::DataType::VARIANT;
+#ifdef DEBUG_ENABLED
+ parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
+#endif
+ }
+ }
+ }
+
+ p_ternary_op->set_datatype(result);
+}
+
+void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
+ reduce_expression(p_unary_op->operand);
+
+ GDScriptParser::DataType result;
+
+ if (p_unary_op->operand == nullptr) {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ p_unary_op->set_datatype(result);
+ return;
+ }
+
+ if (p_unary_op->operand->is_constant) {
+ p_unary_op->is_constant = true;
+ p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
+ result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
+ } else if (p_unary_op->operand->get_datatype().is_variant()) {
+ result.kind = GDScriptParser::DataType::VARIANT;
+ mark_node_unsafe(p_unary_op);
+ } else {
+ bool valid = false;
+ result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), valid, p_unary_op);
+
+ if (!valid) {
+ push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", p_unary_op->operand->get_datatype().to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op->operand);
+ }
+ }
+
+ p_unary_op->set_datatype(result);
+}
+
+void GDScriptAnalyzer::const_fold_array(GDScriptParser::ArrayNode *p_array) {
+ bool all_is_constant = true;
+
+ for (int i = 0; i < p_array->elements.size(); i++) {
+ GDScriptParser::ExpressionNode *element = p_array->elements[i];
+ all_is_constant = all_is_constant && element->is_constant;
+ if (!all_is_constant) {
+ return;
+ }
+ }
+
+ Array array;
+ array.resize(p_array->elements.size());
+ for (int i = 0; i < p_array->elements.size(); i++) {
+ array[i] = p_array->elements[i]->reduced_value;
+ }
+ p_array->is_constant = true;
+ p_array->reduced_value = array;
+}
+
+void GDScriptAnalyzer::const_fold_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
+ bool all_is_constant = true;
+
+ for (int i = 0; i < p_dictionary->elements.size(); i++) {
+ const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
+ all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
+ if (!all_is_constant) {
+ return;
+ }
+ }
+
+ Dictionary dict;
+ for (int i = 0; i < p_dictionary->elements.size(); i++) {
+ const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
+ dict[element.key->reduced_value] = element.value->reduced_value;
+ }
+ p_dictionary->is_constant = true;
+ p_dictionary->reduced_value = dict;
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
+ GDScriptParser::DataType result;
+ result.is_constant = true;
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = p_value.get_type();
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
+
+ if (p_value.get_type() == Variant::OBJECT) {
+ Object *obj = p_value;
+ if (!obj) {
+ return GDScriptParser::DataType();
+ }
+ result.native_type = obj->get_class_name();
+
+ Ref<Script> scr = p_value; // Check if value is a script itself.
+ if (scr.is_valid()) {
+ result.is_meta_type = true;
+ } else {
+ result.is_meta_type = false;
+ scr = obj->get_script();
+ }
+ if (scr.is_valid()) {
+ if (scr->is_valid()) {
+ result.script_type = scr;
+ result.script_path = scr->get_path();
+ Ref<GDScript> gds = scr;
+ if (gds.is_valid()) {
+ result.kind = GDScriptParser::DataType::CLASS;
+ // This might be an inner class, so we want to get the parser for the root.
+ // But still get the inner class from that tree.
+ GDScript *current = gds.ptr();
+ List<StringName> class_chain;
+ while (current->_owner) {
+ // Push to front so it's in reverse.
+ class_chain.push_front(current->name);
+ current = current->_owner;
+ }
+
+ Ref<GDScriptParserRef> ref = get_parser_for(current->path);
+ ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
+
+ GDScriptParser::ClassNode *found = ref->get_parser()->head;
+
+ // It should be okay to assume this exists, since we have a complete script already.
+ for (const List<StringName>::Element *E = class_chain.front(); E; E = E->next()) {
+ found = found->get_member(E->get()).m_class;
+ }
+
+ result.class_type = found;
+ result.script_path = ref->get_parser()->script_path;
+ } else {
+ result.kind = GDScriptParser::DataType::SCRIPT;
+ }
+ result.native_type = scr->get_instance_base_type();
+ } else {
+ push_error(vformat(R"(Constant value uses script from "%s" which is loaded but not compiled.)", scr->get_path()), p_source);
+ result.kind = GDScriptParser::DataType::VARIANT;
+ result.type_source = GDScriptParser::DataType::UNDETECTED;
+ result.is_meta_type = false;
+ }
+ } else {
+ result.kind = GDScriptParser::DataType::NATIVE;
+ if (result.native_type == GDScriptNativeClass::get_class_static()) {
+ result.is_meta_type = true;
+ }
+ }
+ }
+
+ return result;
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
+ GDScriptParser::DataType result = p_meta_type;
+ result.is_meta_type = false;
+ result.is_constant = false;
+ return result;
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
+ GDScriptParser::DataType result;
+ result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
+ // Variant
+ result.kind = GDScriptParser::DataType::VARIANT;
+ return result;
+ }
+ result.builtin_type = p_property.type;
+ if (p_property.type == Variant::OBJECT) {
+ result.kind = GDScriptParser::DataType::NATIVE;
+ result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
+ } else {
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ }
+ return result;
+}
+
+bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
+ r_static = false;
+ r_vararg = false;
+ r_default_arg_count = 0;
+ StringName function_name = p_function;
+
+ if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
+ // Construct a base type to get methods.
+ Callable::CallError err;
+ Variant dummy;
+ Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
+ if (err.error != Callable::CallError::CALL_OK) {
+ ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
+ }
+ List<MethodInfo> methods;
+ dummy.get_method_list(&methods);
+
+ for (const List<MethodInfo>::Element *E = methods.front(); E != nullptr; E = E->next()) {
+ if (E->get().name == p_function) {
+ return function_signature_from_info(E->get(), r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
+ }
+ }
+
+ return false;
+ }
+
+ bool is_constructor = p_base_type.is_meta_type && p_function == "new";
+ if (is_constructor) {
+ function_name = "_init";
+ r_static = true;
+ }
+
+ GDScriptParser::ClassNode *base_class = p_base_type.class_type;
+ GDScriptParser::FunctionNode *found_function = nullptr;
+
+ while (found_function == nullptr && base_class != nullptr) {
+ if (base_class->has_member(function_name)) {
+ if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
+ // TODO: If this is Callable it can have a better error message.
+ push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
+ return false;
+ }
+ found_function = base_class->get_member(function_name).function;
+ }
+ base_class = base_class->base_type.class_type;
+ }
+
+ if (found_function != nullptr) {
+ r_static = is_constructor || found_function->is_static;
+ for (int i = 0; i < found_function->parameters.size(); i++) {
+ r_par_types.push_back(found_function->parameters[i]->get_datatype());
+ if (found_function->parameters[i]->default_value != nullptr) {
+ r_default_arg_count++;
+ }
+ }
+ r_return_type = found_function->get_datatype();
+ r_return_type.is_coroutine = found_function->is_coroutine;
+
+ return true;
+ }
+
+ Ref<Script> base_script = p_base_type.script_type;
+
+ while (base_script.is_valid() && base_script->is_valid()) {
+ MethodInfo info = base_script->get_method_info(function_name);
+
+ if (!(info == MethodInfo())) {
+ return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
+ }
+ base_script = base_script->get_base_script();
+ }
+
+ // If the base is a script, it might be trying to access members of the Script class itself.
+ if (p_base_type.is_meta_type && !is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
+ MethodInfo info;
+ StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
+
+ if (ClassDB::get_method_info(script_class, function_name, &info)) {
+ return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
+ }
+ }
+
+ StringName base_native = p_base_type.native_type;
+#ifdef DEBUG_ENABLED
+ if (base_native != StringName()) {
+ // Empty native class might happen in some Script implementations.
+ // Just ignore it.
+ if (!class_exists(base_native)) {
+ ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
+ }
+ }
+#endif
+
+ if (is_constructor) {
+ // Native types always have a default constructor.
+ r_return_type = p_base_type;
+ r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_return_type.is_meta_type = false;
+ return true;
+ }
+
+ StringName real_native = get_real_class_name(base_native);
+
+ MethodInfo info;
+ if (ClassDB::get_method_info(real_native, function_name, &info)) {
+ return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
+ }
+
+ return false;
+}
+
+bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
+ r_return_type = type_from_property(p_info.return_val);
+ r_default_arg_count = p_info.default_arguments.size();
+ r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
+
+ for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E != nullptr; E = E->next()) {
+ r_par_types.push_back(type_from_property(E->get()));
+ }
+ return true;
+}
+
+bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
+ List<GDScriptParser::DataType> arg_types;
+
+ for (const List<PropertyInfo>::Element *E = p_method.arguments.front(); E != nullptr; E = E->next()) {
+ arg_types.push_back(type_from_property(E->get()));
+ }
+
+ return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
+}
+
+bool GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {
+ bool valid = true;
+
+ if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
+ push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", p_call->function_name, p_par_types.size() - p_default_args_count, p_call->arguments.size()), p_call);
+ valid = false;
+ }
+ if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
+ push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", p_call->function_name, p_par_types.size(), p_call->arguments.size()), p_call->arguments[p_par_types.size()]);
+ valid = false;
+ }
+
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ if (i >= p_par_types.size()) {
+ // Already on vararg place.
+ break;
+ }
+ GDScriptParser::DataType par_type = p_par_types[i];
+ GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
+
+ if (arg_type.is_variant()) {
+ // Argument can be anything, so this is unsafe.
+ mark_node_unsafe(p_call->arguments[i]);
+ } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
+ // Supertypes are acceptable for dynamic compliance, but it's unsafe.
+ mark_node_unsafe(p_call);
+ if (!is_type_compatible(arg_type, par_type)) {
+ push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
+ p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
+ p_call->arguments[i]);
+ valid = false;
+ }
+#ifdef DEBUG_ENABLED
+ } else {
+ if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {
+ parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
+ }
+#endif
+ }
+ }
+ return valid;
+}
+
+#ifdef DEBUG_ENABLED
+bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
+ const StringName &name = p_local->name;
+ GDScriptParser::DataType base = parser->current_class->get_datatype();
+
+ GDScriptParser::ClassNode *base_class = base.class_type;
+
+ while (base_class != nullptr) {
+ if (base_class->has_member(name)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_local->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
+ return true;
+ }
+ base_class = base_class->base_type.class_type;
+ }
+
+ StringName base_native = base.native_type;
+
+ ERR_FAIL_COND_V_MSG(!class_exists(base_native), false, "Non-existent native base class.");
+
+ StringName parent = base_native;
+ while (parent != StringName()) {
+ StringName real_class_name = get_real_class_name(parent);
+ if (ClassDB::has_method(real_class_name, name, true)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
+ return true;
+ } else if (ClassDB::has_signal(real_class_name, name, true)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
+ return true;
+ } else if (ClassDB::has_property(real_class_name, name, true)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
+ return true;
+ } else if (ClassDB::has_integer_constant(real_class_name, name, true)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
+ return true;
+ } else if (ClassDB::has_enum(real_class_name, name, true)) {
+ parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
+ return true;
+ }
+ parent = ClassDB::get_parent_class(real_class_name);
+ }
+
+ return false;
+}
+#endif
+
+GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
+ // Unary version.
+ GDScriptParser::DataType nil_type;
+ nil_type.builtin_type = Variant::NIL;
+ return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
+}
+
+GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) {
+ GDScriptParser::DataType result;
+ result.kind = GDScriptParser::DataType::VARIANT;
+
+ Variant::Type a_type = p_a.builtin_type;
+ Variant::Type b_type = p_b.builtin_type;
+
+ Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
+
+ if (op_eval == nullptr) {
+ r_valid = false;
+ return result;
+ }
+
+ r_valid = true;
+
+ result.kind = GDScriptParser::DataType::BUILTIN;
+ result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
+
+ return result;
+}
+
+// TODO: Add safe/unsafe return variable (for variant cases)
+bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion) const {
+ // These return "true" so it doesn't affect users negatively.
+ ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
+ ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
+
+ if (p_target.kind == GDScriptParser::DataType::VARIANT) {
+ // Variant can receive anything.
+ return true;
+ }
+
+ if (p_source.kind == GDScriptParser::DataType::VARIANT) {
+ // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
+ return true;
+ }
+
+ if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
+ bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
+ if (!valid && p_allow_implicit_conversion) {
+ valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
+ }
+ if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
+ // Enum value is also integer.
+ valid = true;
+ }
+ return valid;
+ }
+
+ if (p_target.kind == GDScriptParser::DataType::ENUM) {
+ if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
+ return true;
+ }
+ if (p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
+ if (p_source.native_type == p_target.native_type && p_target.enum_values.has(p_source.enum_type)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // From here on the target type is an object, so we have to test polymorphism.
+
+ if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
+ // null is acceptable in object.
+ return true;
+ }
+
+ StringName src_native;
+ Ref<Script> src_script;
+ const GDScriptParser::ClassNode *src_class = nullptr;
+
+ switch (p_source.kind) {
+ case GDScriptParser::DataType::NATIVE:
+ if (p_target.kind != GDScriptParser::DataType::NATIVE) {
+ // Non-native class cannot be supertype of native.
+ return false;
+ }
+ if (p_source.is_meta_type) {
+ src_native = GDScriptNativeClass::get_class_static();
+ } else {
+ src_native = p_source.native_type;
+ }
+ break;
+ case GDScriptParser::DataType::SCRIPT:
+ if (p_target.kind == GDScriptParser::DataType::CLASS) {
+ // A script type cannot be a subtype of a GDScript class.
+ return false;
+ }
+ if (p_source.is_meta_type) {
+ src_native = p_source.script_type->get_class_name();
+ } else {
+ src_script = p_source.script_type;
+ src_native = src_script->get_instance_base_type();
+ }
+ break;
+ case GDScriptParser::DataType::CLASS:
+ if (p_source.is_meta_type) {
+ src_native = GDScript::get_class_static();
+ } else {
+ src_class = p_source.class_type;
+ const GDScriptParser::ClassNode *base = src_class;
+ while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
+ base = base->base_type.class_type;
+ }
+ src_native = base->base_type.native_type;
+ src_script = base->base_type.script_type;
+ }
+ break;
+ case GDScriptParser::DataType::VARIANT:
+ case GDScriptParser::DataType::BUILTIN:
+ case GDScriptParser::DataType::ENUM:
+ case GDScriptParser::DataType::ENUM_VALUE:
+ case GDScriptParser::DataType::UNRESOLVED:
+ break; // Already solved before.
+ }
+
+ // Get underscore-prefixed version for some classes.
+ src_native = get_real_class_name(src_native);
+
+ switch (p_target.kind) {
+ case GDScriptParser::DataType::NATIVE: {
+ if (p_target.is_meta_type) {
+ return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
+ }
+ StringName tgt_native = get_real_class_name(p_target.native_type);
+ return ClassDB::is_parent_class(src_native, tgt_native);
+ }
+ case GDScriptParser::DataType::SCRIPT:
+ if (p_target.is_meta_type) {
+ return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
+ }
+ while (src_script.is_valid()) {
+ if (src_script == p_target.script_type) {
+ return true;
+ }
+ src_script = src_script->get_base_script();
+ }
+ return false;
+ case GDScriptParser::DataType::CLASS:
+ if (p_target.is_meta_type) {
+ return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
+ }
+ while (src_class != nullptr) {
+ if (src_class->fqcn == p_target.class_type->fqcn) {
+ return true;
+ }
+ src_class = src_class->base_type.class_type;
+ }
+ return false;
+ case GDScriptParser::DataType::VARIANT:
+ case GDScriptParser::DataType::BUILTIN:
+ case GDScriptParser::DataType::ENUM:
+ case GDScriptParser::DataType::ENUM_VALUE:
+ case GDScriptParser::DataType::UNRESOLVED:
+ break; // Already solved before.
+ }
+
+ return false;
+}
+
+void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
+ mark_node_unsafe(p_origin);
+ parser->push_error(p_message, p_origin);
+}
+
+void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
+#ifdef DEBUG_ENABLED
+ for (int i = p_node->start_line; i <= p_node->end_line; i++) {
+ parser->unsafe_lines.insert(i);
+ }
+#endif
+}
+
+bool GDScriptAnalyzer::class_exists(const StringName &p_class) {
+ StringName real_name = get_real_class_name(p_class);
+ return ClassDB::class_exists(real_name) && ClassDB::is_class_exposed(real_name);
+}
+
+Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
+ Ref<GDScriptParserRef> ref;
+ if (depended_parsers.has(p_path)) {
+ ref = depended_parsers[p_path];
+ } else {
+ Error err = OK;
+ ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, parser->script_path);
+ depended_parsers[p_path] = ref;
+ }
+
+ return ref;
+}
+
+Error GDScriptAnalyzer::resolve_inheritance() {
+ return resolve_inheritance(parser->head);
+}
+
+Error GDScriptAnalyzer::resolve_interface() {
+ resolve_class_interface(parser->head);
+ return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
+}
+
+Error GDScriptAnalyzer::resolve_body() {
+ resolve_class_body(parser->head);
+ return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
+}
+
+Error GDScriptAnalyzer::resolve_program() {
+ resolve_class_interface(parser->head);
+ resolve_class_body(parser->head);
+
+ List<String> parser_keys;
+ depended_parsers.get_key_list(&parser_keys);
+ for (const List<String>::Element *E = parser_keys.front(); E != nullptr; E = E->next()) {
+ if (depended_parsers[E->get()].is_null()) {
+ return ERR_PARSE_ERROR;
+ }
+ depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED);
+ }
+ return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
+}
+
+Error GDScriptAnalyzer::analyze() {
+ parser->errors.clear();
+ Error err = resolve_inheritance(parser->head);
+ if (err) {
+ return err;
+ }
+ return resolve_program();
+}
+
+GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
+ parser = p_parser;
+}
diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h
new file mode 100644
index 0000000000..dab5b032a3
--- /dev/null
+++ b/modules/gdscript/gdscript_analyzer.h
@@ -0,0 +1,126 @@
+/*************************************************************************/
+/* gdscript_analyzer.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_ANALYZER_H
+#define GDSCRIPT_ANALYZER_H
+
+#include "core/object/object.h"
+#include "core/object/reference.h"
+#include "core/templates/set.h"
+#include "gdscript_cache.h"
+#include "gdscript_parser.h"
+
+class GDScriptAnalyzer {
+ GDScriptParser *parser = nullptr;
+ HashMap<String, Ref<GDScriptParserRef>> depended_parsers;
+
+ const GDScriptParser::EnumNode *current_enum = nullptr;
+
+ Error resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive = true);
+ GDScriptParser::DataType resolve_datatype(GDScriptParser::TypeNode *p_type);
+
+ void decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement);
+
+ // This traverses the tree to resolve all TypeNodes.
+ Error resolve_program();
+
+ void resolve_annotation(GDScriptParser::AnnotationNode *p_annotation);
+ void resolve_class_interface(GDScriptParser::ClassNode *p_class);
+ void resolve_class_body(GDScriptParser::ClassNode *p_class);
+ void resolve_function_signature(GDScriptParser::FunctionNode *p_function);
+ void resolve_function_body(GDScriptParser::FunctionNode *p_function);
+ void resolve_node(GDScriptParser::Node *p_node);
+ void resolve_suite(GDScriptParser::SuiteNode *p_suite);
+ void resolve_if(GDScriptParser::IfNode *p_if);
+ void resolve_for(GDScriptParser::ForNode *p_for);
+ void resolve_while(GDScriptParser::WhileNode *p_while);
+ void resolve_variable(GDScriptParser::VariableNode *p_variable);
+ void resolve_constant(GDScriptParser::ConstantNode *p_constant);
+ void resolve_assert(GDScriptParser::AssertNode *p_assert);
+ void resolve_match(GDScriptParser::MatchNode *p_match);
+ void resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test);
+ void resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test);
+ void resolve_parameter(GDScriptParser::ParameterNode *p_parameter);
+ void resolve_return(GDScriptParser::ReturnNode *p_return);
+
+ // Reduction functions.
+ void reduce_expression(GDScriptParser::ExpressionNode *p_expression);
+ void reduce_array(GDScriptParser::ArrayNode *p_array);
+ void reduce_assignment(GDScriptParser::AssignmentNode *p_assignment);
+ void reduce_await(GDScriptParser::AwaitNode *p_await);
+ void reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op);
+ void reduce_call(GDScriptParser::CallNode *p_call, bool is_await = false);
+ void reduce_cast(GDScriptParser::CastNode *p_cast);
+ void reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary);
+ void reduce_get_node(GDScriptParser::GetNodeNode *p_get_node);
+ void reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin = false);
+ void reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base = nullptr);
+ void reduce_literal(GDScriptParser::LiteralNode *p_literal);
+ void reduce_preload(GDScriptParser::PreloadNode *p_preload);
+ void reduce_self(GDScriptParser::SelfNode *p_self);
+ void reduce_subscript(GDScriptParser::SubscriptNode *p_subscript);
+ void reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op);
+ void reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op);
+
+ void const_fold_array(GDScriptParser::ArrayNode *p_array);
+ void const_fold_dictionary(GDScriptParser::DictionaryNode *p_dictionary);
+
+ // Helpers.
+ GDScriptParser::DataType type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source);
+ GDScriptParser::DataType type_from_metatype(const GDScriptParser::DataType &p_meta_type) const;
+ GDScriptParser::DataType type_from_property(const PropertyInfo &p_property) const;
+ GDScriptParser::DataType make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source);
+ bool get_function_signature(GDScriptParser::Node *p_source, GDScriptParser::DataType base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg);
+ bool function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg);
+ bool validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call);
+ bool validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call);
+ GDScriptParser::DataType get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source);
+ GDScriptParser::DataType get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source);
+ bool is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion = false) const;
+ void push_error(const String &p_message, const GDScriptParser::Node *p_origin);
+ void mark_node_unsafe(const GDScriptParser::Node *p_node);
+ bool class_exists(const StringName &p_class);
+ Ref<GDScriptParserRef> get_parser_for(const String &p_path);
+#ifdef DEBUG_ENABLED
+ bool is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context);
+#endif
+
+public:
+ Error resolve_inheritance();
+ Error resolve_interface();
+ Error resolve_body();
+ Error analyze();
+
+ GDScriptAnalyzer(GDScriptParser *p_parser);
+
+ static void cleanup();
+};
+
+#endif // GDSCRIPT_ANALYZER_H
diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp
new file mode 100644
index 0000000000..58c6b31a77
--- /dev/null
+++ b/modules/gdscript/gdscript_byte_codegen.cpp
@@ -0,0 +1,1282 @@
+/*************************************************************************/
+/* gdscript_byte_codegen.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_byte_codegen.h"
+
+#include "core/debugger/engine_debugger.h"
+#include "gdscript.h"
+
+uint32_t GDScriptByteCodeGenerator::add_parameter(const StringName &p_name, bool p_is_optional, const GDScriptDataType &p_type) {
+#ifdef TOOLS_ENABLED
+ function->arg_names.push_back(p_name);
+#endif
+ function->_argument_count++;
+ function->argument_types.push_back(p_type);
+ if (p_is_optional) {
+ function->_default_arg_count++;
+ }
+
+ return add_local(p_name, p_type);
+}
+
+uint32_t GDScriptByteCodeGenerator::add_local(const StringName &p_name, const GDScriptDataType &p_type) {
+ int stack_pos = increase_stack();
+ add_stack_identifier(p_name, stack_pos);
+ return stack_pos;
+}
+
+uint32_t GDScriptByteCodeGenerator::add_local_constant(const StringName &p_name, const Variant &p_constant) {
+ int index = add_or_get_constant(p_constant);
+ local_constants[p_name] = index;
+ return index;
+}
+
+uint32_t GDScriptByteCodeGenerator::add_or_get_constant(const Variant &p_constant) {
+ if (constant_map.has(p_constant)) {
+ return constant_map[p_constant];
+ }
+ int index = constant_map.size();
+ constant_map[p_constant] = index;
+ return index;
+}
+
+uint32_t GDScriptByteCodeGenerator::add_or_get_name(const StringName &p_name) {
+ return get_name_map_pos(p_name);
+}
+
+uint32_t GDScriptByteCodeGenerator::add_temporary() {
+ current_temporaries++;
+ int idx = increase_stack();
+#ifdef DEBUG_ENABLED
+ temp_stack.push_back(idx);
+#endif
+ return idx;
+}
+
+void GDScriptByteCodeGenerator::pop_temporary() {
+ ERR_FAIL_COND(current_temporaries == 0);
+ current_stack_size--;
+#ifdef DEBUG_ENABLED
+ if (temp_stack.back()->get() != current_stack_size) {
+ ERR_PRINT("Mismatched popping of temporary value");
+ }
+ temp_stack.pop_back();
+#endif
+ current_temporaries--;
+}
+
+void GDScriptByteCodeGenerator::start_parameters() {
+ if (function->_default_arg_count > 0) {
+ append(GDScriptFunction::OPCODE_JUMP_TO_DEF_ARGUMENT);
+ function->default_arguments.push_back(opcodes.size());
+ }
+}
+
+void GDScriptByteCodeGenerator::end_parameters() {
+ function->default_arguments.invert();
+}
+
+void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) {
+ function = memnew(GDScriptFunction);
+ debug_stack = EngineDebugger::is_active();
+
+ function->name = p_function_name;
+ function->_script = p_script;
+ function->source = p_script->get_path();
+
+#ifdef DEBUG_ENABLED
+ function->func_cname = (String(function->source) + " - " + String(p_function_name)).utf8();
+ function->_func_cname = function->func_cname.get_data();
+#endif
+
+ function->_static = p_static;
+ function->return_type = p_return_type;
+ function->rpc_mode = p_rpc_mode;
+ function->_argument_count = 0;
+}
+
+GDScriptFunction *GDScriptByteCodeGenerator::write_end() {
+#ifdef DEBUG_ENABLED
+ if (current_temporaries != 0) {
+ ERR_PRINT("Non-zero temporary variables at end of function: " + itos(current_temporaries));
+ }
+#endif
+ append(GDScriptFunction::OPCODE_END, 0);
+
+ if (constant_map.size()) {
+ function->_constant_count = constant_map.size();
+ function->constants.resize(constant_map.size());
+ function->_constants_ptr = function->constants.ptrw();
+ const Variant *K = nullptr;
+ while ((K = constant_map.next(K))) {
+ int idx = constant_map[*K];
+ function->constants.write[idx] = *K;
+ }
+ } else {
+ function->_constants_ptr = nullptr;
+ function->_constant_count = 0;
+ }
+
+ if (name_map.size()) {
+ function->global_names.resize(name_map.size());
+ function->_global_names_ptr = &function->global_names[0];
+ for (Map<StringName, int>::Element *E = name_map.front(); E; E = E->next()) {
+ function->global_names.write[E->get()] = E->key();
+ }
+ function->_global_names_count = function->global_names.size();
+
+ } else {
+ function->_global_names_ptr = nullptr;
+ function->_global_names_count = 0;
+ }
+
+ if (opcodes.size()) {
+ function->code = opcodes;
+ function->_code_ptr = &function->code[0];
+ function->_code_size = opcodes.size();
+
+ } else {
+ function->_code_ptr = nullptr;
+ function->_code_size = 0;
+ }
+
+ if (function->default_arguments.size()) {
+ function->_default_arg_count = function->default_arguments.size() - 1;
+ function->_default_arg_ptr = &function->default_arguments[0];
+ } else {
+ function->_default_arg_count = 0;
+ function->_default_arg_ptr = nullptr;
+ }
+
+ if (operator_func_map.size()) {
+ function->operator_funcs.resize(operator_func_map.size());
+ function->_operator_funcs_count = function->operator_funcs.size();
+ function->_operator_funcs_ptr = function->operator_funcs.ptr();
+ for (const Map<Variant::ValidatedOperatorEvaluator, int>::Element *E = operator_func_map.front(); E; E = E->next()) {
+ function->operator_funcs.write[E->get()] = E->key();
+ }
+ } else {
+ function->_operator_funcs_count = 0;
+ function->_operator_funcs_ptr = nullptr;
+ }
+
+ if (setters_map.size()) {
+ function->setters.resize(setters_map.size());
+ function->_setters_count = function->setters.size();
+ function->_setters_ptr = function->setters.ptr();
+ for (const Map<Variant::ValidatedSetter, int>::Element *E = setters_map.front(); E; E = E->next()) {
+ function->setters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_setters_count = 0;
+ function->_setters_ptr = nullptr;
+ }
+
+ if (getters_map.size()) {
+ function->getters.resize(getters_map.size());
+ function->_getters_count = function->getters.size();
+ function->_getters_ptr = function->getters.ptr();
+ for (const Map<Variant::ValidatedGetter, int>::Element *E = getters_map.front(); E; E = E->next()) {
+ function->getters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_getters_count = 0;
+ function->_getters_ptr = nullptr;
+ }
+
+ if (keyed_setters_map.size()) {
+ function->keyed_setters.resize(keyed_setters_map.size());
+ function->_keyed_setters_count = function->keyed_setters.size();
+ function->_keyed_setters_ptr = function->keyed_setters.ptr();
+ for (const Map<Variant::ValidatedKeyedSetter, int>::Element *E = keyed_setters_map.front(); E; E = E->next()) {
+ function->keyed_setters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_keyed_setters_count = 0;
+ function->_keyed_setters_ptr = nullptr;
+ }
+
+ if (keyed_getters_map.size()) {
+ function->keyed_getters.resize(keyed_getters_map.size());
+ function->_keyed_getters_count = function->keyed_getters.size();
+ function->_keyed_getters_ptr = function->keyed_getters.ptr();
+ for (const Map<Variant::ValidatedKeyedGetter, int>::Element *E = keyed_getters_map.front(); E; E = E->next()) {
+ function->keyed_getters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_keyed_getters_count = 0;
+ function->_keyed_getters_ptr = nullptr;
+ }
+
+ if (indexed_setters_map.size()) {
+ function->indexed_setters.resize(indexed_setters_map.size());
+ function->_indexed_setters_count = function->indexed_setters.size();
+ function->_indexed_setters_ptr = function->indexed_setters.ptr();
+ for (const Map<Variant::ValidatedIndexedSetter, int>::Element *E = indexed_setters_map.front(); E; E = E->next()) {
+ function->indexed_setters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_indexed_setters_count = 0;
+ function->_indexed_setters_ptr = nullptr;
+ }
+
+ if (indexed_getters_map.size()) {
+ function->indexed_getters.resize(indexed_getters_map.size());
+ function->_indexed_getters_count = function->indexed_getters.size();
+ function->_indexed_getters_ptr = function->indexed_getters.ptr();
+ for (const Map<Variant::ValidatedIndexedGetter, int>::Element *E = indexed_getters_map.front(); E; E = E->next()) {
+ function->indexed_getters.write[E->get()] = E->key();
+ }
+ } else {
+ function->_indexed_getters_count = 0;
+ function->_indexed_getters_ptr = nullptr;
+ }
+
+ if (builtin_method_map.size()) {
+ function->builtin_methods.resize(builtin_method_map.size());
+ function->_builtin_methods_ptr = function->builtin_methods.ptr();
+ function->_builtin_methods_count = builtin_method_map.size();
+ for (const Map<Variant::ValidatedBuiltInMethod, int>::Element *E = builtin_method_map.front(); E; E = E->next()) {
+ function->builtin_methods.write[E->get()] = E->key();
+ }
+ } else {
+ function->_builtin_methods_ptr = nullptr;
+ function->_builtin_methods_count = 0;
+ }
+
+ if (constructors_map.size()) {
+ function->constructors.resize(constructors_map.size());
+ function->_constructors_ptr = function->constructors.ptr();
+ function->_constructors_count = constructors_map.size();
+ for (const Map<Variant::ValidatedConstructor, int>::Element *E = constructors_map.front(); E; E = E->next()) {
+ function->constructors.write[E->get()] = E->key();
+ }
+ } else {
+ function->_constructors_ptr = nullptr;
+ function->_constructors_count = 0;
+ }
+
+ if (utilities_map.size()) {
+ function->utilities.resize(utilities_map.size());
+ function->_utilities_ptr = function->utilities.ptr();
+ function->_utilities_count = utilities_map.size();
+ for (const Map<Variant::ValidatedUtilityFunction, int>::Element *E = utilities_map.front(); E; E = E->next()) {
+ function->utilities.write[E->get()] = E->key();
+ }
+ } else {
+ function->_utilities_ptr = nullptr;
+ function->_utilities_count = 0;
+ }
+
+ if (gds_utilities_map.size()) {
+ function->gds_utilities.resize(gds_utilities_map.size());
+ function->_gds_utilities_ptr = function->gds_utilities.ptr();
+ function->_gds_utilities_count = gds_utilities_map.size();
+ for (const Map<GDScriptUtilityFunctions::FunctionPtr, int>::Element *E = gds_utilities_map.front(); E; E = E->next()) {
+ function->gds_utilities.write[E->get()] = E->key();
+ }
+ } else {
+ function->_gds_utilities_ptr = nullptr;
+ function->_gds_utilities_count = 0;
+ }
+
+ if (method_bind_map.size()) {
+ function->methods.resize(method_bind_map.size());
+ function->_methods_ptr = function->methods.ptrw();
+ function->_methods_count = method_bind_map.size();
+ for (const Map<MethodBind *, int>::Element *E = method_bind_map.front(); E; E = E->next()) {
+ function->methods.write[E->get()] = E->key();
+ }
+ } else {
+ function->_methods_ptr = nullptr;
+ function->_methods_count = 0;
+ }
+
+ if (debug_stack) {
+ function->stack_debug = stack_debug;
+ }
+ function->_stack_size = stack_max;
+ function->_instruction_args_size = instr_args_max;
+ function->_ptrcall_args_size = ptrcall_max;
+
+ ended = true;
+ return function;
+}
+
+#ifdef DEBUG_ENABLED
+void GDScriptByteCodeGenerator::set_signature(const String &p_signature) {
+ function->profile.signature = p_signature;
+}
+#endif
+
+void GDScriptByteCodeGenerator::set_initial_line(int p_line) {
+ function->_initial_line = p_line;
+}
+
+#define HAS_BUILTIN_TYPE(m_var) \
+ (m_var.type.has_type && m_var.type.kind == GDScriptDataType::BUILTIN)
+
+#define IS_BUILTIN_TYPE(m_var, m_type) \
+ (m_var.type.has_type && m_var.type.kind == GDScriptDataType::BUILTIN && m_var.type.builtin_type == m_type)
+
+void GDScriptByteCodeGenerator::write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) {
+ if (HAS_BUILTIN_TYPE(p_left_operand)) {
+ // Gather specific operator.
+ Variant::ValidatedOperatorEvaluator op_func = Variant::get_validated_operator_evaluator(p_operator, p_left_operand.type.builtin_type, Variant::NIL);
+
+ append(GDScriptFunction::OPCODE_OPERATOR_VALIDATED, 3);
+ append(p_left_operand);
+ append(Address());
+ append(p_target);
+ append(op_func);
+ return;
+ }
+
+ // No specific types, perform variant evaluation.
+ append(GDScriptFunction::OPCODE_OPERATOR, 3);
+ append(p_left_operand);
+ append(Address());
+ append(p_target);
+ append(p_operator);
+}
+
+void GDScriptByteCodeGenerator::write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) {
+ if (HAS_BUILTIN_TYPE(p_left_operand) && HAS_BUILTIN_TYPE(p_right_operand)) {
+ // Gather specific operator.
+ Variant::ValidatedOperatorEvaluator op_func = Variant::get_validated_operator_evaluator(p_operator, p_left_operand.type.builtin_type, p_right_operand.type.builtin_type);
+
+ append(GDScriptFunction::OPCODE_OPERATOR_VALIDATED, 3);
+ append(p_left_operand);
+ append(p_right_operand);
+ append(p_target);
+ append(op_func);
+ return;
+ }
+
+ // No specific types, perform variant evaluation.
+ append(GDScriptFunction::OPCODE_OPERATOR, 3);
+ append(p_left_operand);
+ append(p_right_operand);
+ append(p_target);
+ append(p_operator);
+}
+
+void GDScriptByteCodeGenerator::write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) {
+ append(GDScriptFunction::OPCODE_EXTENDS_TEST, 3);
+ append(p_source);
+ append(p_type);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) {
+ append(GDScriptFunction::OPCODE_IS_BUILTIN, 3);
+ append(p_source);
+ append(p_target);
+ append(p_type);
+}
+
+void GDScriptByteCodeGenerator::write_and_left_operand(const Address &p_left_operand) {
+ append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1);
+ append(p_left_operand);
+ logic_op_jump_pos1.push_back(opcodes.size());
+ append(0); // Jump target, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_and_right_operand(const Address &p_right_operand) {
+ append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1);
+ append(p_right_operand);
+ logic_op_jump_pos2.push_back(opcodes.size());
+ append(0); // Jump target, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_end_and(const Address &p_target) {
+ // If here means both operands are true.
+ append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1);
+ append(p_target);
+ // Jump away from the fail condition.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(opcodes.size() + 3);
+ // Here it means one of operands is false.
+ patch_jump(logic_op_jump_pos1.back()->get());
+ patch_jump(logic_op_jump_pos2.back()->get());
+ logic_op_jump_pos1.pop_back();
+ logic_op_jump_pos2.pop_back();
+ append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 1);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_or_left_operand(const Address &p_left_operand) {
+ append(GDScriptFunction::OPCODE_JUMP_IF, 1);
+ append(p_left_operand);
+ logic_op_jump_pos1.push_back(opcodes.size());
+ append(0); // Jump target, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_or_right_operand(const Address &p_right_operand) {
+ append(GDScriptFunction::OPCODE_JUMP_IF, 1);
+ append(p_right_operand);
+ logic_op_jump_pos2.push_back(opcodes.size());
+ append(0); // Jump target, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_end_or(const Address &p_target) {
+ // If here means both operands are false.
+ append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 1);
+ append(p_target);
+ // Jump away from the success condition.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(opcodes.size() + 3);
+ // Here it means one of operands is true.
+ patch_jump(logic_op_jump_pos1.back()->get());
+ patch_jump(logic_op_jump_pos2.back()->get());
+ logic_op_jump_pos1.pop_back();
+ logic_op_jump_pos2.pop_back();
+ append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_start_ternary(const Address &p_target) {
+ ternary_result.push_back(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_ternary_condition(const Address &p_condition) {
+ append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1);
+ append(p_condition);
+ ternary_jump_fail_pos.push_back(opcodes.size());
+ append(0); // Jump target, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_ternary_true_expr(const Address &p_expr) {
+ append(GDScriptFunction::OPCODE_ASSIGN, 2);
+ append(ternary_result.back()->get());
+ append(p_expr);
+ // Jump away from the false path.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ ternary_jump_skip_pos.push_back(opcodes.size());
+ append(0);
+ // Fail must jump here.
+ patch_jump(ternary_jump_fail_pos.back()->get());
+ ternary_jump_fail_pos.pop_back();
+}
+
+void GDScriptByteCodeGenerator::write_ternary_false_expr(const Address &p_expr) {
+ append(GDScriptFunction::OPCODE_ASSIGN, 2);
+ append(ternary_result.back()->get());
+ append(p_expr);
+}
+
+void GDScriptByteCodeGenerator::write_end_ternary() {
+ patch_jump(ternary_jump_skip_pos.back()->get());
+ ternary_jump_skip_pos.pop_back();
+}
+
+void GDScriptByteCodeGenerator::write_set(const Address &p_target, const Address &p_index, const Address &p_source) {
+ if (HAS_BUILTIN_TYPE(p_target)) {
+ if (IS_BUILTIN_TYPE(p_index, Variant::INT) && Variant::get_member_validated_indexed_setter(p_target.type.builtin_type)) {
+ // Use indexed setter instead.
+ Variant::ValidatedIndexedSetter setter = Variant::get_member_validated_indexed_setter(p_target.type.builtin_type);
+ append(GDScriptFunction::OPCODE_SET_INDEXED_VALIDATED, 3);
+ append(p_target);
+ append(p_index);
+ append(p_source);
+ append(setter);
+ return;
+ } else if (Variant::get_member_validated_keyed_setter(p_target.type.builtin_type)) {
+ Variant::ValidatedKeyedSetter setter = Variant::get_member_validated_keyed_setter(p_target.type.builtin_type);
+ append(GDScriptFunction::OPCODE_SET_KEYED_VALIDATED, 3);
+ append(p_target);
+ append(p_index);
+ append(p_source);
+ append(setter);
+ return;
+ }
+ }
+
+ append(GDScriptFunction::OPCODE_SET_KEYED, 3);
+ append(p_target);
+ append(p_index);
+ append(p_source);
+}
+
+void GDScriptByteCodeGenerator::write_get(const Address &p_target, const Address &p_index, const Address &p_source) {
+ if (HAS_BUILTIN_TYPE(p_source)) {
+ if (IS_BUILTIN_TYPE(p_index, Variant::INT) && Variant::get_member_validated_indexed_getter(p_source.type.builtin_type)) {
+ // Use indexed getter instead.
+ Variant::ValidatedIndexedGetter getter = Variant::get_member_validated_indexed_getter(p_source.type.builtin_type);
+ append(GDScriptFunction::OPCODE_GET_INDEXED_VALIDATED, 3);
+ append(p_source);
+ append(p_index);
+ append(p_target);
+ append(getter);
+ return;
+ } else if (Variant::get_member_validated_keyed_getter(p_source.type.builtin_type)) {
+ Variant::ValidatedKeyedGetter getter = Variant::get_member_validated_keyed_getter(p_source.type.builtin_type);
+ append(GDScriptFunction::OPCODE_GET_KEYED_VALIDATED, 3);
+ append(p_source);
+ append(p_index);
+ append(p_target);
+ append(getter);
+ return;
+ }
+ }
+ append(GDScriptFunction::OPCODE_GET_KEYED, 3);
+ append(p_source);
+ append(p_index);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_set_named(const Address &p_target, const StringName &p_name, const Address &p_source) {
+ if (HAS_BUILTIN_TYPE(p_target) && Variant::get_member_validated_setter(p_target.type.builtin_type, p_name)) {
+ Variant::ValidatedSetter setter = Variant::get_member_validated_setter(p_target.type.builtin_type, p_name);
+ append(GDScriptFunction::OPCODE_SET_NAMED_VALIDATED, 2);
+ append(p_target);
+ append(p_source);
+ append(setter);
+ return;
+ }
+ append(GDScriptFunction::OPCODE_SET_NAMED, 2);
+ append(p_target);
+ append(p_source);
+ append(p_name);
+}
+
+void GDScriptByteCodeGenerator::write_get_named(const Address &p_target, const StringName &p_name, const Address &p_source) {
+ if (HAS_BUILTIN_TYPE(p_source) && Variant::get_member_validated_getter(p_source.type.builtin_type, p_name)) {
+ Variant::ValidatedGetter getter = Variant::get_member_validated_getter(p_source.type.builtin_type, p_name);
+ append(GDScriptFunction::OPCODE_GET_NAMED_VALIDATED, 2);
+ append(p_source);
+ append(p_target);
+ append(getter);
+ return;
+ }
+ append(GDScriptFunction::OPCODE_GET_NAMED, 2);
+ append(p_source);
+ append(p_target);
+ append(p_name);
+}
+
+void GDScriptByteCodeGenerator::write_set_member(const Address &p_value, const StringName &p_name) {
+ append(GDScriptFunction::OPCODE_SET_MEMBER, 1);
+ append(p_value);
+ append(p_name);
+}
+
+void GDScriptByteCodeGenerator::write_get_member(const Address &p_target, const StringName &p_name) {
+ append(GDScriptFunction::OPCODE_GET_MEMBER, 1);
+ append(p_target);
+ append(p_name);
+}
+
+void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Address &p_source) {
+ if (p_target.type.has_type && !p_source.type.has_type) {
+ // Typed assignment.
+ switch (p_target.type.kind) {
+ case GDScriptDataType::BUILTIN: {
+ append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2);
+ append(p_target);
+ append(p_source);
+ append(p_target.type.builtin_type);
+ } break;
+ case GDScriptDataType::NATIVE: {
+ int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_target.type.native_type];
+ class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS);
+ append(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE, 3);
+ append(p_target);
+ append(p_source);
+ append(class_idx);
+ } break;
+ case GDScriptDataType::SCRIPT:
+ case GDScriptDataType::GDSCRIPT: {
+ Variant script = p_target.type.script_type;
+ int idx = get_constant_pos(script);
+ idx |= (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS);
+
+ append(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT, 3);
+ append(p_target);
+ append(p_source);
+ append(idx);
+ } break;
+ default: {
+ ERR_PRINT("Compiler bug: unresolved assign.");
+
+ // Shouldn't get here, but fail-safe to a regular assignment
+ append(GDScriptFunction::OPCODE_ASSIGN, 2);
+ append(p_target);
+ append(p_source);
+ }
+ }
+ } else {
+ if (p_target.type.kind == GDScriptDataType::BUILTIN && p_source.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type != p_source.type.builtin_type) {
+ // Need conversion..
+ append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2);
+ append(p_target);
+ append(p_source);
+ append(p_target.type.builtin_type);
+ } else {
+ // Either untyped assignment or already type-checked by the parser
+ append(GDScriptFunction::OPCODE_ASSIGN, 2);
+ append(p_target);
+ append(p_source);
+ }
+ }
+}
+
+void GDScriptByteCodeGenerator::write_assign_true(const Address &p_target) {
+ append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_assign_false(const Address &p_target) {
+ append(GDScriptFunction::OPCODE_ASSIGN_FALSE, 1);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_assign_default_parameter(const Address &p_dst, const Address &p_src) {
+ write_assign(p_dst, p_src);
+ function->default_arguments.push_back(opcodes.size());
+}
+
+void GDScriptByteCodeGenerator::write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) {
+ int index = 0;
+
+ switch (p_type.kind) {
+ case GDScriptDataType::BUILTIN: {
+ append(GDScriptFunction::OPCODE_CAST_TO_BUILTIN, 2);
+ index = p_type.builtin_type;
+ } break;
+ case GDScriptDataType::NATIVE: {
+ int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_type.native_type];
+ class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS);
+ append(GDScriptFunction::OPCODE_CAST_TO_NATIVE, 3);
+ index = class_idx;
+ } break;
+ case GDScriptDataType::SCRIPT:
+ case GDScriptDataType::GDSCRIPT: {
+ Variant script = p_type.script_type;
+ int idx = get_constant_pos(script);
+ idx |= (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS);
+
+ append(GDScriptFunction::OPCODE_CAST_TO_SCRIPT, 3);
+ index = idx;
+ } break;
+ default: {
+ return;
+ }
+ }
+
+ append(p_source);
+ append(p_target);
+ append(index);
+}
+
+void GDScriptByteCodeGenerator::write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CALL_SELF_BASE, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CALL_ASYNC, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CALL_GDSCRIPT_UTILITY, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function);
+}
+
+void GDScriptByteCodeGenerator::write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) {
+ bool is_validated = true;
+ if (Variant::is_utility_function_vararg(p_function)) {
+ is_validated = true; // Vararg works fine with any argument, since they can be any type.
+ } else if (p_arguments.size() == Variant::get_utility_function_argument_count(p_function)) {
+ bool all_types_exact = true;
+ for (int i = 0; i < p_arguments.size(); i++) {
+ if (!IS_BUILTIN_TYPE(p_arguments[i], Variant::get_utility_function_argument_type(p_function, i))) {
+ all_types_exact = false;
+ break;
+ }
+ }
+
+ is_validated = all_types_exact;
+ }
+
+ if (is_validated) {
+ append(GDScriptFunction::OPCODE_CALL_UTILITY_VALIDATED, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(Variant::get_validated_utility_function(p_function));
+ } else {
+ append(GDScriptFunction::OPCODE_CALL_UTILITY, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function);
+ }
+}
+
+void GDScriptByteCodeGenerator::write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) {
+ bool is_validated = false;
+
+ // Check if all types are correct.
+ if (Variant::is_builtin_method_vararg(p_type, p_method)) {
+ is_validated = true; // Vararg works fine with any argument, since they can be any type.
+ } else if (p_arguments.size() == Variant::get_builtin_method_argument_count(p_type, p_method)) {
+ bool all_types_exact = true;
+ for (int i = 0; i < p_arguments.size(); i++) {
+ if (!IS_BUILTIN_TYPE(p_arguments[i], Variant::get_builtin_method_argument_type(p_type, p_method, i))) {
+ all_types_exact = false;
+ break;
+ }
+ }
+
+ is_validated = all_types_exact;
+ }
+
+ if (!is_validated) {
+ // Perform regular call.
+ write_call(p_target, p_base, p_method, p_arguments);
+ return;
+ }
+
+ append(GDScriptFunction::OPCODE_CALL_BUILTIN_TYPE_VALIDATED, 2 + p_arguments.size());
+
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(Variant::get_validated_builtin_method(p_type, p_method));
+}
+
+void GDScriptByteCodeGenerator::write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) {
+ append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_method);
+}
+
+void GDScriptByteCodeGenerator::write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) {
+#define CASE_TYPE(m_type) \
+ case Variant::m_type: \
+ append(GDScriptFunction::OPCODE_CALL_PTRCALL_##m_type, 2 + p_arguments.size()); \
+ break
+
+ bool is_ptrcall = true;
+
+ if (p_method->has_return()) {
+ MethodInfo info;
+ ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info);
+ switch (info.return_val.type) {
+ CASE_TYPE(BOOL);
+ CASE_TYPE(INT);
+ CASE_TYPE(FLOAT);
+ CASE_TYPE(STRING);
+ CASE_TYPE(VECTOR2);
+ CASE_TYPE(VECTOR2I);
+ CASE_TYPE(RECT2);
+ CASE_TYPE(RECT2I);
+ CASE_TYPE(VECTOR3);
+ CASE_TYPE(VECTOR3I);
+ CASE_TYPE(TRANSFORM2D);
+ CASE_TYPE(PLANE);
+ CASE_TYPE(AABB);
+ CASE_TYPE(BASIS);
+ CASE_TYPE(TRANSFORM);
+ CASE_TYPE(COLOR);
+ CASE_TYPE(STRING_NAME);
+ CASE_TYPE(NODE_PATH);
+ CASE_TYPE(RID);
+ CASE_TYPE(QUAT);
+ CASE_TYPE(OBJECT);
+ CASE_TYPE(CALLABLE);
+ CASE_TYPE(SIGNAL);
+ CASE_TYPE(DICTIONARY);
+ CASE_TYPE(ARRAY);
+ CASE_TYPE(PACKED_BYTE_ARRAY);
+ CASE_TYPE(PACKED_INT32_ARRAY);
+ CASE_TYPE(PACKED_INT64_ARRAY);
+ CASE_TYPE(PACKED_FLOAT32_ARRAY);
+ CASE_TYPE(PACKED_FLOAT64_ARRAY);
+ CASE_TYPE(PACKED_STRING_ARRAY);
+ CASE_TYPE(PACKED_VECTOR2_ARRAY);
+ CASE_TYPE(PACKED_VECTOR3_ARRAY);
+ CASE_TYPE(PACKED_COLOR_ARRAY);
+ default:
+ append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size());
+ is_ptrcall = false;
+ break;
+ }
+ } else {
+ append(GDScriptFunction::OPCODE_CALL_PTRCALL_NO_RETURN, 2 + p_arguments.size());
+ }
+
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_method);
+ if (is_ptrcall) {
+ alloc_ptrcall(p_arguments.size());
+ }
+
+#undef CASE_TYPE
+}
+
+void GDScriptByteCodeGenerator::write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CALL_ASYNC, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) {
+ append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN, 2 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_base);
+ append(p_target);
+ append(p_arguments.size());
+ append(p_function_name);
+}
+
+void GDScriptByteCodeGenerator::write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) {
+ // Try to find an appropriate constructor.
+ bool all_have_type = true;
+ Vector<Variant::Type> arg_types;
+ for (int i = 0; i < p_arguments.size(); i++) {
+ if (!HAS_BUILTIN_TYPE(p_arguments[i])) {
+ all_have_type = false;
+ break;
+ }
+ arg_types.push_back(p_arguments[i].type.builtin_type);
+ }
+ if (all_have_type) {
+ int valid_constructor = -1;
+ for (int i = 0; i < Variant::get_constructor_count(p_type); i++) {
+ if (Variant::get_constructor_argument_count(p_type, i) != p_arguments.size()) {
+ continue;
+ }
+ int types_correct = true;
+ for (int j = 0; j < arg_types.size(); j++) {
+ if (arg_types[j] != Variant::get_constructor_argument_type(p_type, i, j)) {
+ types_correct = false;
+ break;
+ }
+ }
+ if (types_correct) {
+ valid_constructor = i;
+ break;
+ }
+ }
+ if (valid_constructor >= 0) {
+ append(GDScriptFunction::OPCODE_CONSTRUCT_VALIDATED, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(Variant::get_validated_constructor(p_type, valid_constructor));
+ return;
+ }
+ }
+
+ append(GDScriptFunction::OPCODE_CONSTRUCT, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+ append(p_type);
+}
+
+void GDScriptByteCodeGenerator::write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CONSTRUCT_ARRAY, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size());
+}
+
+void GDScriptByteCodeGenerator::write_construct_dictionary(const Address &p_target, const Vector<Address> &p_arguments) {
+ append(GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY, 1 + p_arguments.size());
+ for (int i = 0; i < p_arguments.size(); i++) {
+ append(p_arguments[i]);
+ }
+ append(p_target);
+ append(p_arguments.size() / 2); // This is number of key-value pairs, so only half of actual arguments.
+}
+
+void GDScriptByteCodeGenerator::write_await(const Address &p_target, const Address &p_operand) {
+ append(GDScriptFunction::OPCODE_AWAIT, 1);
+ append(p_operand);
+ append(GDScriptFunction::OPCODE_AWAIT_RESUME, 1);
+ append(p_target);
+}
+
+void GDScriptByteCodeGenerator::write_if(const Address &p_condition) {
+ append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1);
+ append(p_condition);
+ if_jmp_addrs.push_back(opcodes.size());
+ append(0); // Jump destination, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_else() {
+ append(GDScriptFunction::OPCODE_JUMP, 0); // Jump from true if block;
+ int else_jmp_addr = opcodes.size();
+ append(0); // Jump destination, will be patched.
+
+ patch_jump(if_jmp_addrs.back()->get());
+ if_jmp_addrs.pop_back();
+ if_jmp_addrs.push_back(else_jmp_addr);
+}
+
+void GDScriptByteCodeGenerator::write_endif() {
+ patch_jump(if_jmp_addrs.back()->get());
+ if_jmp_addrs.pop_back();
+}
+
+void GDScriptByteCodeGenerator::start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) {
+ Address counter(Address::LOCAL_VARIABLE, add_local("@counter_pos", p_iterator_type), p_iterator_type);
+ Address container(Address::LOCAL_VARIABLE, add_local("@container_pos", p_list_type), p_list_type);
+
+ // Store state.
+ for_counter_variables.push_back(counter);
+ for_container_variables.push_back(container);
+}
+
+void GDScriptByteCodeGenerator::write_for_assignment(const Address &p_variable, const Address &p_list) {
+ const Address &container = for_container_variables.back()->get();
+
+ // Assign container.
+ append(GDScriptFunction::OPCODE_ASSIGN, 2);
+ append(container);
+ append(p_list);
+
+ for_iterator_variables.push_back(p_variable);
+}
+
+void GDScriptByteCodeGenerator::write_for() {
+ const Address &iterator = for_iterator_variables.back()->get();
+ const Address &counter = for_counter_variables.back()->get();
+ const Address &container = for_container_variables.back()->get();
+
+ current_breaks_to_patch.push_back(List<int>());
+
+ GDScriptFunction::Opcode begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN;
+ GDScriptFunction::Opcode iterate_opcode = GDScriptFunction::OPCODE_ITERATE;
+
+ if (container.type.has_type) {
+ if (container.type.kind == GDScriptDataType::BUILTIN) {
+ switch (container.type.builtin_type) {
+ case Variant::INT:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_INT;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_INT;
+ break;
+ case Variant::FLOAT:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_FLOAT;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_FLOAT;
+ break;
+ case Variant::VECTOR2:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR2;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR2;
+ break;
+ case Variant::VECTOR2I:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR2I;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR2I;
+ break;
+ case Variant::VECTOR3:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR3;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR3;
+ break;
+ case Variant::VECTOR3I:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_VECTOR3I;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_VECTOR3I;
+ break;
+ case Variant::STRING:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_STRING;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_STRING;
+ break;
+ case Variant::DICTIONARY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_DICTIONARY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_DICTIONARY;
+ break;
+ case Variant::ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_ARRAY;
+ break;
+ case Variant::PACKED_BYTE_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_BYTE_ARRAY;
+ break;
+ case Variant::PACKED_INT32_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_INT32_ARRAY;
+ break;
+ case Variant::PACKED_INT64_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_INT64_ARRAY;
+ break;
+ case Variant::PACKED_FLOAT32_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_FLOAT32_ARRAY;
+ break;
+ case Variant::PACKED_FLOAT64_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_FLOAT64_ARRAY;
+ break;
+ case Variant::PACKED_STRING_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_STRING_ARRAY;
+ break;
+ case Variant::PACKED_VECTOR2_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_VECTOR2_ARRAY;
+ break;
+ case Variant::PACKED_VECTOR3_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_VECTOR3_ARRAY;
+ break;
+ case Variant::PACKED_COLOR_ARRAY:
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_PACKED_COLOR_ARRAY;
+ break;
+ default:
+ break;
+ }
+ } else {
+ begin_opcode = GDScriptFunction::OPCODE_ITERATE_BEGIN_OBJECT;
+ iterate_opcode = GDScriptFunction::OPCODE_ITERATE_OBJECT;
+ }
+ }
+
+ // Begin loop.
+ append(begin_opcode, 3);
+ append(counter);
+ append(container);
+ append(iterator);
+ for_jmp_addrs.push_back(opcodes.size());
+ append(0); // End of loop address, will be patched.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(opcodes.size() + 6); // Skip over 'continue' code.
+
+ // Next iteration.
+ int continue_addr = opcodes.size();
+ continue_addrs.push_back(continue_addr);
+ append(iterate_opcode, 3);
+ append(counter);
+ append(container);
+ append(iterator);
+ for_jmp_addrs.push_back(opcodes.size());
+ append(0); // Jump destination, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_endfor() {
+ // Jump back to loop check.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(continue_addrs.back()->get());
+ continue_addrs.pop_back();
+
+ // Patch end jumps (two of them).
+ for (int i = 0; i < 2; i++) {
+ patch_jump(for_jmp_addrs.back()->get());
+ for_jmp_addrs.pop_back();
+ }
+
+ // Patch break statements.
+ for (const List<int>::Element *E = current_breaks_to_patch.back()->get().front(); E; E = E->next()) {
+ patch_jump(E->get());
+ }
+ current_breaks_to_patch.pop_back();
+
+ // Pop state.
+ for_iterator_variables.pop_back();
+ for_counter_variables.pop_back();
+ for_container_variables.pop_back();
+}
+
+void GDScriptByteCodeGenerator::start_while_condition() {
+ current_breaks_to_patch.push_back(List<int>());
+ continue_addrs.push_back(opcodes.size());
+}
+
+void GDScriptByteCodeGenerator::write_while(const Address &p_condition) {
+ // Condition check.
+ append(GDScriptFunction::OPCODE_JUMP_IF_NOT, 1);
+ append(p_condition);
+ while_jmp_addrs.push_back(opcodes.size());
+ append(0); // End of loop address, will be patched.
+}
+
+void GDScriptByteCodeGenerator::write_endwhile() {
+ // Jump back to loop check.
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(continue_addrs.back()->get());
+ continue_addrs.pop_back();
+
+ // Patch end jump.
+ patch_jump(while_jmp_addrs.back()->get());
+ while_jmp_addrs.pop_back();
+
+ // Patch break statements.
+ for (const List<int>::Element *E = current_breaks_to_patch.back()->get().front(); E; E = E->next()) {
+ patch_jump(E->get());
+ }
+ current_breaks_to_patch.pop_back();
+}
+
+void GDScriptByteCodeGenerator::start_match() {
+ match_continues_to_patch.push_back(List<int>());
+}
+
+void GDScriptByteCodeGenerator::start_match_branch() {
+ // Patch continue statements.
+ for (const List<int>::Element *E = match_continues_to_patch.back()->get().front(); E; E = E->next()) {
+ patch_jump(E->get());
+ }
+ match_continues_to_patch.pop_back();
+ // Start a new list for next branch.
+ match_continues_to_patch.push_back(List<int>());
+}
+
+void GDScriptByteCodeGenerator::end_match() {
+ // Patch continue statements.
+ for (const List<int>::Element *E = match_continues_to_patch.back()->get().front(); E; E = E->next()) {
+ patch_jump(E->get());
+ }
+ match_continues_to_patch.pop_back();
+}
+
+void GDScriptByteCodeGenerator::write_break() {
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ current_breaks_to_patch.back()->get().push_back(opcodes.size());
+ append(0);
+}
+
+void GDScriptByteCodeGenerator::write_continue() {
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ append(continue_addrs.back()->get());
+}
+
+void GDScriptByteCodeGenerator::write_continue_match() {
+ append(GDScriptFunction::OPCODE_JUMP, 0);
+ match_continues_to_patch.back()->get().push_back(opcodes.size());
+ append(0);
+}
+
+void GDScriptByteCodeGenerator::write_breakpoint() {
+ append(GDScriptFunction::OPCODE_BREAKPOINT, 0);
+}
+
+void GDScriptByteCodeGenerator::write_newline(int p_line) {
+ append(GDScriptFunction::OPCODE_LINE, 0);
+ append(p_line);
+ current_line = p_line;
+}
+
+void GDScriptByteCodeGenerator::write_return(const Address &p_return_value) {
+ append(GDScriptFunction::OPCODE_RETURN, 1);
+ append(p_return_value);
+}
+
+void GDScriptByteCodeGenerator::write_assert(const Address &p_test, const Address &p_message) {
+ append(GDScriptFunction::OPCODE_ASSERT, 2);
+ append(p_test);
+ append(p_message);
+}
+
+void GDScriptByteCodeGenerator::start_block() {
+ push_stack_identifiers();
+}
+
+void GDScriptByteCodeGenerator::end_block() {
+ pop_stack_identifiers();
+}
+
+GDScriptByteCodeGenerator::~GDScriptByteCodeGenerator() {
+ if (!ended && function != nullptr) {
+ memdelete(function);
+ }
+}
diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h
new file mode 100644
index 0000000000..1e66af269a
--- /dev/null
+++ b/modules/gdscript/gdscript_byte_codegen.h
@@ -0,0 +1,474 @@
+/*************************************************************************/
+/* gdscript_byte_codegen.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_BYTE_CODEGEN
+#define GDSCRIPT_BYTE_CODEGEN
+
+#include "gdscript_codegen.h"
+
+#include "gdscript_function.h"
+#include "gdscript_utility_functions.h"
+
+class GDScriptByteCodeGenerator : public GDScriptCodeGenerator {
+ bool ended = false;
+ GDScriptFunction *function = nullptr;
+ bool debug_stack = false;
+
+ Vector<int> opcodes;
+ List<Map<StringName, int>> stack_id_stack;
+ Map<StringName, int> stack_identifiers;
+ List<int> stack_identifiers_counts;
+ Map<StringName, int> local_constants;
+
+ List<GDScriptFunction::StackDebug> stack_debug;
+ List<Map<StringName, int>> block_identifier_stack;
+ Map<StringName, int> block_identifiers;
+
+ int current_stack_size = 0;
+ int current_temporaries = 0;
+ int current_locals = 0;
+ int current_line = 0;
+ int stack_max = 0;
+ int instr_args_max = 0;
+ int ptrcall_max = 0;
+
+#ifdef DEBUG_ENABLED
+ List<int> temp_stack;
+#endif
+
+ HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
+ Map<StringName, int> name_map;
+#ifdef TOOLS_ENABLED
+ Vector<StringName> named_globals;
+#endif
+ Map<Variant::ValidatedOperatorEvaluator, int> operator_func_map;
+ Map<Variant::ValidatedSetter, int> setters_map;
+ Map<Variant::ValidatedGetter, int> getters_map;
+ Map<Variant::ValidatedKeyedSetter, int> keyed_setters_map;
+ Map<Variant::ValidatedKeyedGetter, int> keyed_getters_map;
+ Map<Variant::ValidatedIndexedSetter, int> indexed_setters_map;
+ Map<Variant::ValidatedIndexedGetter, int> indexed_getters_map;
+ Map<Variant::ValidatedBuiltInMethod, int> builtin_method_map;
+ Map<Variant::ValidatedConstructor, int> constructors_map;
+ Map<Variant::ValidatedUtilityFunction, int> utilities_map;
+ Map<GDScriptUtilityFunctions::FunctionPtr, int> gds_utilities_map;
+ Map<MethodBind *, int> method_bind_map;
+
+ // Lists since these can be nested.
+ List<int> if_jmp_addrs;
+ List<int> for_jmp_addrs;
+ List<Address> for_iterator_variables;
+ List<Address> for_counter_variables;
+ List<Address> for_container_variables;
+ List<int> while_jmp_addrs;
+ List<int> continue_addrs;
+
+ // Used to patch jumps with `and` and `or` operators with short-circuit.
+ List<int> logic_op_jump_pos1;
+ List<int> logic_op_jump_pos2;
+
+ List<Address> ternary_result;
+ List<int> ternary_jump_fail_pos;
+ List<int> ternary_jump_skip_pos;
+
+ List<List<int>> current_breaks_to_patch;
+ List<List<int>> match_continues_to_patch;
+
+ void add_stack_identifier(const StringName &p_id, int p_stackpos) {
+ current_locals++;
+ stack_identifiers[p_id] = p_stackpos;
+ if (debug_stack) {
+ block_identifiers[p_id] = p_stackpos;
+ GDScriptFunction::StackDebug sd;
+ sd.added = true;
+ sd.line = current_line;
+ sd.identifier = p_id;
+ sd.pos = p_stackpos;
+ stack_debug.push_back(sd);
+ }
+ }
+
+ void push_stack_identifiers() {
+ stack_identifiers_counts.push_back(current_locals);
+ stack_id_stack.push_back(stack_identifiers);
+ if (debug_stack) {
+ Map<StringName, int> block_ids(block_identifiers);
+ block_identifier_stack.push_back(block_ids);
+ block_identifiers.clear();
+ }
+ }
+
+ void pop_stack_identifiers() {
+ current_locals = stack_identifiers_counts.back()->get();
+ stack_identifiers_counts.pop_back();
+ stack_identifiers = stack_id_stack.back()->get();
+ stack_id_stack.pop_back();
+#ifdef DEBUG_ENABLED
+ if (current_temporaries != 0) {
+ ERR_PRINT("Leaving block with non-zero temporary variables: " + itos(current_temporaries));
+ }
+#endif
+ current_stack_size = current_locals;
+
+ if (debug_stack) {
+ for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) {
+ GDScriptFunction::StackDebug sd;
+ sd.added = false;
+ sd.identifier = E->key();
+ sd.line = current_line;
+ sd.pos = E->get();
+ stack_debug.push_back(sd);
+ }
+ block_identifiers = block_identifier_stack.back()->get();
+ block_identifier_stack.pop_back();
+ }
+ }
+
+ int get_name_map_pos(const StringName &p_identifier) {
+ int ret;
+ if (!name_map.has(p_identifier)) {
+ ret = name_map.size();
+ name_map[p_identifier] = ret;
+ } else {
+ ret = name_map[p_identifier];
+ }
+ return ret;
+ }
+
+ int get_constant_pos(const Variant &p_constant) {
+ if (constant_map.has(p_constant))
+ return constant_map[p_constant];
+ int pos = constant_map.size();
+ constant_map[p_constant] = pos;
+ return pos;
+ }
+
+ int get_operation_pos(const Variant::ValidatedOperatorEvaluator p_operation) {
+ if (operator_func_map.has(p_operation))
+ return operator_func_map[p_operation];
+ int pos = operator_func_map.size();
+ operator_func_map[p_operation] = pos;
+ return pos;
+ }
+
+ int get_setter_pos(const Variant::ValidatedSetter p_setter) {
+ if (setters_map.has(p_setter))
+ return setters_map[p_setter];
+ int pos = setters_map.size();
+ setters_map[p_setter] = pos;
+ return pos;
+ }
+
+ int get_getter_pos(const Variant::ValidatedGetter p_getter) {
+ if (getters_map.has(p_getter))
+ return getters_map[p_getter];
+ int pos = getters_map.size();
+ getters_map[p_getter] = pos;
+ return pos;
+ }
+
+ int get_keyed_setter_pos(const Variant::ValidatedKeyedSetter p_keyed_setter) {
+ if (keyed_setters_map.has(p_keyed_setter))
+ return keyed_setters_map[p_keyed_setter];
+ int pos = keyed_setters_map.size();
+ keyed_setters_map[p_keyed_setter] = pos;
+ return pos;
+ }
+
+ int get_keyed_getter_pos(const Variant::ValidatedKeyedGetter p_keyed_getter) {
+ if (keyed_getters_map.has(p_keyed_getter))
+ return keyed_getters_map[p_keyed_getter];
+ int pos = keyed_getters_map.size();
+ keyed_getters_map[p_keyed_getter] = pos;
+ return pos;
+ }
+
+ int get_indexed_setter_pos(const Variant::ValidatedIndexedSetter p_indexed_setter) {
+ if (indexed_setters_map.has(p_indexed_setter))
+ return indexed_setters_map[p_indexed_setter];
+ int pos = indexed_setters_map.size();
+ indexed_setters_map[p_indexed_setter] = pos;
+ return pos;
+ }
+
+ int get_indexed_getter_pos(const Variant::ValidatedIndexedGetter p_indexed_getter) {
+ if (indexed_getters_map.has(p_indexed_getter))
+ return indexed_getters_map[p_indexed_getter];
+ int pos = indexed_getters_map.size();
+ indexed_getters_map[p_indexed_getter] = pos;
+ return pos;
+ }
+
+ int get_builtin_method_pos(const Variant::ValidatedBuiltInMethod p_method) {
+ if (builtin_method_map.has(p_method)) {
+ return builtin_method_map[p_method];
+ }
+ int pos = builtin_method_map.size();
+ builtin_method_map[p_method] = pos;
+ return pos;
+ }
+
+ int get_constructor_pos(const Variant::ValidatedConstructor p_constructor) {
+ if (constructors_map.has(p_constructor)) {
+ return constructors_map[p_constructor];
+ }
+ int pos = constructors_map.size();
+ constructors_map[p_constructor] = pos;
+ return pos;
+ }
+
+ int get_utility_pos(const Variant::ValidatedUtilityFunction p_utility) {
+ if (utilities_map.has(p_utility)) {
+ return utilities_map[p_utility];
+ }
+ int pos = utilities_map.size();
+ utilities_map[p_utility] = pos;
+ return pos;
+ }
+
+ int get_gds_utility_pos(const GDScriptUtilityFunctions::FunctionPtr p_gds_utility) {
+ if (gds_utilities_map.has(p_gds_utility)) {
+ return gds_utilities_map[p_gds_utility];
+ }
+ int pos = gds_utilities_map.size();
+ gds_utilities_map[p_gds_utility] = pos;
+ return pos;
+ }
+
+ int get_method_bind_pos(MethodBind *p_method) {
+ if (method_bind_map.has(p_method)) {
+ return method_bind_map[p_method];
+ }
+ int pos = method_bind_map.size();
+ method_bind_map[p_method] = pos;
+ return pos;
+ }
+
+ void alloc_stack(int p_level) {
+ if (p_level >= stack_max)
+ stack_max = p_level + 1;
+ }
+
+ int increase_stack() {
+ int top = current_stack_size++;
+ alloc_stack(current_stack_size);
+ return top;
+ }
+
+ void alloc_ptrcall(int p_params) {
+ if (p_params >= ptrcall_max)
+ ptrcall_max = p_params;
+ }
+
+ int address_of(const Address &p_address) {
+ switch (p_address.mode) {
+ case Address::SELF:
+ return GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS;
+ case Address::CLASS:
+ return GDScriptFunction::ADDR_TYPE_CLASS << GDScriptFunction::ADDR_BITS;
+ case Address::MEMBER:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS);
+ case Address::CLASS_CONSTANT:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT << GDScriptFunction::ADDR_BITS);
+ case Address::LOCAL_CONSTANT:
+ case Address::CONSTANT:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS);
+ case Address::LOCAL_VARIABLE:
+ case Address::TEMPORARY:
+ case Address::FUNCTION_PARAMETER:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
+ case Address::GLOBAL:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS);
+ case Address::NAMED_GLOBAL:
+ return p_address.address | (GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL << GDScriptFunction::ADDR_BITS);
+ case Address::NIL:
+ return GDScriptFunction::ADDR_TYPE_NIL << GDScriptFunction::ADDR_BITS;
+ }
+ return -1; // Unreachable.
+ }
+
+ void append(GDScriptFunction::Opcode p_code, int p_argument_count) {
+ opcodes.push_back((p_code & GDScriptFunction::INSTR_MASK) | (p_argument_count << GDScriptFunction::INSTR_BITS));
+ instr_args_max = MAX(instr_args_max, p_argument_count);
+ }
+
+ void append(int p_code) {
+ opcodes.push_back(p_code);
+ }
+
+ void append(const Address &p_address) {
+ opcodes.push_back(address_of(p_address));
+ }
+
+ void append(const StringName &p_name) {
+ opcodes.push_back(get_name_map_pos(p_name));
+ }
+
+ void append(const Variant::ValidatedOperatorEvaluator p_operation) {
+ opcodes.push_back(get_operation_pos(p_operation));
+ }
+
+ void append(const Variant::ValidatedSetter p_setter) {
+ opcodes.push_back(get_setter_pos(p_setter));
+ }
+
+ void append(const Variant::ValidatedGetter p_getter) {
+ opcodes.push_back(get_getter_pos(p_getter));
+ }
+
+ void append(const Variant::ValidatedKeyedSetter p_keyed_setter) {
+ opcodes.push_back(get_keyed_setter_pos(p_keyed_setter));
+ }
+
+ void append(const Variant::ValidatedKeyedGetter p_keyed_getter) {
+ opcodes.push_back(get_keyed_getter_pos(p_keyed_getter));
+ }
+
+ void append(const Variant::ValidatedIndexedSetter p_indexed_setter) {
+ opcodes.push_back(get_indexed_setter_pos(p_indexed_setter));
+ }
+
+ void append(const Variant::ValidatedIndexedGetter p_indexed_getter) {
+ opcodes.push_back(get_indexed_getter_pos(p_indexed_getter));
+ }
+
+ void append(const Variant::ValidatedBuiltInMethod p_method) {
+ opcodes.push_back(get_builtin_method_pos(p_method));
+ }
+
+ void append(const Variant::ValidatedConstructor p_constructor) {
+ opcodes.push_back(get_constructor_pos(p_constructor));
+ }
+
+ void append(const Variant::ValidatedUtilityFunction p_utility) {
+ opcodes.push_back(get_utility_pos(p_utility));
+ }
+
+ void append(const GDScriptUtilityFunctions::FunctionPtr p_gds_utility) {
+ opcodes.push_back(get_gds_utility_pos(p_gds_utility));
+ }
+
+ void append(MethodBind *p_method) {
+ opcodes.push_back(get_method_bind_pos(p_method));
+ }
+
+ void patch_jump(int p_address) {
+ opcodes.write[p_address] = opcodes.size();
+ }
+
+public:
+ virtual uint32_t add_parameter(const StringName &p_name, bool p_is_optional, const GDScriptDataType &p_type) override;
+ virtual uint32_t add_local(const StringName &p_name, const GDScriptDataType &p_type) override;
+ virtual uint32_t add_local_constant(const StringName &p_name, const Variant &p_constant) override;
+ virtual uint32_t add_or_get_constant(const Variant &p_constant) override;
+ virtual uint32_t add_or_get_name(const StringName &p_name) override;
+ virtual uint32_t add_temporary() override;
+ virtual void pop_temporary() override;
+
+ virtual void start_parameters() override;
+ virtual void end_parameters() override;
+
+ virtual void start_block() override;
+ virtual void end_block() override;
+
+ virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) override;
+ virtual GDScriptFunction *write_end() override;
+
+#ifdef DEBUG_ENABLED
+ virtual void set_signature(const String &p_signature) override;
+#endif
+ virtual void set_initial_line(int p_line) override;
+
+ virtual void write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) override;
+ virtual void write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) override;
+ virtual void write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) override;
+ virtual void write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) override;
+ virtual void write_and_left_operand(const Address &p_left_operand) override;
+ virtual void write_and_right_operand(const Address &p_right_operand) override;
+ virtual void write_end_and(const Address &p_target) override;
+ virtual void write_or_left_operand(const Address &p_left_operand) override;
+ virtual void write_or_right_operand(const Address &p_right_operand) override;
+ virtual void write_end_or(const Address &p_target) override;
+ virtual void write_start_ternary(const Address &p_target) override;
+ virtual void write_ternary_condition(const Address &p_condition) override;
+ virtual void write_ternary_true_expr(const Address &p_expr) override;
+ virtual void write_ternary_false_expr(const Address &p_expr) override;
+ virtual void write_end_ternary() override;
+ virtual void write_set(const Address &p_target, const Address &p_index, const Address &p_source) override;
+ virtual void write_get(const Address &p_target, const Address &p_index, const Address &p_source) override;
+ virtual void write_set_named(const Address &p_target, const StringName &p_name, const Address &p_source) override;
+ virtual void write_get_named(const Address &p_target, const StringName &p_name, const Address &p_source) override;
+ virtual void write_set_member(const Address &p_value, const StringName &p_name) override;
+ virtual void write_get_member(const Address &p_target, const StringName &p_name) override;
+ virtual void write_assign(const Address &p_target, const Address &p_source) override;
+ virtual void write_assign_true(const Address &p_target) override;
+ virtual void write_assign_false(const Address &p_target) override;
+ virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src) override;
+ virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) override;
+ virtual void write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) override;
+ virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) override;
+ virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override;
+ virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override;
+ virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override;
+ virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
+ virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) override;
+ virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) override;
+ virtual void write_construct_dictionary(const Address &p_target, const Vector<Address> &p_arguments) override;
+ virtual void write_await(const Address &p_target, const Address &p_operand) override;
+ virtual void write_if(const Address &p_condition) override;
+ virtual void write_else() override;
+ virtual void write_endif() override;
+ virtual void start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) override;
+ virtual void write_for_assignment(const Address &p_variable, const Address &p_list) override;
+ virtual void write_for() override;
+ virtual void write_endfor() override;
+ virtual void start_while_condition() override;
+ virtual void write_while(const Address &p_condition) override;
+ virtual void write_endwhile() override;
+ virtual void start_match() override;
+ virtual void start_match_branch() override;
+ virtual void end_match() override;
+ virtual void write_break() override;
+ virtual void write_continue() override;
+ virtual void write_continue_match() override;
+ virtual void write_breakpoint() override;
+ virtual void write_newline(int p_line) override;
+ virtual void write_return(const Address &p_return_value) override;
+ virtual void write_assert(const Address &p_test, const Address &p_message) override;
+
+ virtual ~GDScriptByteCodeGenerator();
+};
+
+#endif // GDSCRIPT_BYTE_CODEGEN
diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp
new file mode 100644
index 0000000000..113d36be98
--- /dev/null
+++ b/modules/gdscript/gdscript_cache.cpp
@@ -0,0 +1,255 @@
+/*************************************************************************/
+/* gdscript_cache.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_cache.h"
+
+#include "core/os/file_access.h"
+#include "core/templates/vector.h"
+#include "gdscript.h"
+#include "gdscript_analyzer.h"
+#include "gdscript_parser.h"
+
+bool GDScriptParserRef::is_valid() const {
+ return parser != nullptr;
+}
+
+GDScriptParserRef::Status GDScriptParserRef::get_status() const {
+ return status;
+}
+
+GDScriptParser *GDScriptParserRef::get_parser() const {
+ return parser;
+}
+
+Error GDScriptParserRef::raise_status(Status p_new_status) {
+ ERR_FAIL_COND_V(parser == nullptr, ERR_INVALID_DATA);
+
+ Error result = OK;
+
+ while (p_new_status > status) {
+ switch (status) {
+ case EMPTY:
+ result = parser->parse(GDScriptCache::get_source_code(path), path, false);
+ status = PARSED;
+ break;
+ case PARSED: {
+ analyzer = memnew(GDScriptAnalyzer(parser));
+ Error inheritance_result = analyzer->resolve_inheritance();
+ status = INHERITANCE_SOLVED;
+ if (result == OK) {
+ result = inheritance_result;
+ }
+ } break;
+ case INHERITANCE_SOLVED: {
+ Error interface_result = analyzer->resolve_interface();
+ status = INTERFACE_SOLVED;
+ if (result == OK) {
+ result = interface_result;
+ }
+ } break;
+ case INTERFACE_SOLVED: {
+ Error body_result = analyzer->resolve_body();
+ status = FULLY_SOLVED;
+ if (result == OK) {
+ result = body_result;
+ }
+ } break;
+ case FULLY_SOLVED: {
+ return result;
+ }
+ }
+ if (result != OK) {
+ if (parser != nullptr) {
+ memdelete(parser);
+ parser = nullptr;
+ }
+ if (analyzer != nullptr) {
+ memdelete(analyzer);
+ analyzer = nullptr;
+ }
+ return result;
+ }
+ }
+
+ return result;
+}
+
+GDScriptParserRef::~GDScriptParserRef() {
+ if (parser != nullptr) {
+ memdelete(parser);
+ }
+ if (analyzer != nullptr) {
+ memdelete(analyzer);
+ }
+ MutexLock lock(GDScriptCache::singleton->lock);
+ GDScriptCache::singleton->parser_map.erase(path);
+}
+
+GDScriptCache *GDScriptCache::singleton = nullptr;
+
+void GDScriptCache::remove_script(const String &p_path) {
+ MutexLock lock(singleton->lock);
+ singleton->shallow_gdscript_cache.erase(p_path);
+ singleton->full_gdscript_cache.erase(p_path);
+}
+
+Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptParserRef::Status p_status, Error &r_error, const String &p_owner) {
+ MutexLock lock(singleton->lock);
+ Ref<GDScriptParserRef> ref;
+ if (p_owner != String()) {
+ singleton->dependencies[p_owner].insert(p_path);
+ }
+ if (singleton->parser_map.has(p_path)) {
+ ref = Ref<GDScriptParserRef>(singleton->parser_map[p_path]);
+ } else {
+ if (!FileAccess::exists(p_path)) {
+ r_error = ERR_FILE_NOT_FOUND;
+ return ref;
+ }
+ GDScriptParser *parser = memnew(GDScriptParser);
+ ref.instance();
+ ref->parser = parser;
+ ref->path = p_path;
+ singleton->parser_map[p_path] = ref.ptr();
+ }
+
+ r_error = ref->raise_status(p_status);
+
+ return ref;
+}
+
+String GDScriptCache::get_source_code(const String &p_path) {
+ Vector<uint8_t> source_file;
+ Error err;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (err) {
+ ERR_FAIL_COND_V(err, "");
+ }
+
+ int len = f->get_len();
+ source_file.resize(len + 1);
+ int r = f->get_buffer(source_file.ptrw(), len);
+ f->close();
+ ERR_FAIL_COND_V(r != len, "");
+ source_file.write[len] = 0;
+
+ String source;
+ if (source.parse_utf8((const char *)source_file.ptr())) {
+ ERR_FAIL_V_MSG("", "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
+ }
+ return source;
+}
+
+Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const String &p_owner) {
+ MutexLock lock(singleton->lock);
+ if (p_owner != String()) {
+ singleton->dependencies[p_owner].insert(p_path);
+ }
+ if (singleton->full_gdscript_cache.has(p_path)) {
+ return singleton->full_gdscript_cache[p_path];
+ }
+ if (singleton->shallow_gdscript_cache.has(p_path)) {
+ return singleton->shallow_gdscript_cache[p_path];
+ }
+
+ Ref<GDScript> script;
+ script.instance();
+ script->set_path(p_path, true);
+ script->set_script_path(p_path);
+ script->load_source_code(p_path);
+
+ singleton->shallow_gdscript_cache[p_path] = script.ptr();
+ return script;
+}
+
+Ref<GDScript> GDScriptCache::get_full_script(const String &p_path, Error &r_error, const String &p_owner) {
+ MutexLock lock(singleton->lock);
+
+ if (p_owner != String()) {
+ singleton->dependencies[p_owner].insert(p_path);
+ }
+
+ r_error = OK;
+ if (singleton->full_gdscript_cache.has(p_path)) {
+ return singleton->full_gdscript_cache[p_path];
+ }
+ Ref<GDScript> script = get_shallow_script(p_path);
+
+ r_error = script->load_source_code(p_path);
+
+ if (r_error) {
+ return script;
+ }
+
+ r_error = script->reload();
+ if (r_error) {
+ return script;
+ }
+
+ singleton->full_gdscript_cache[p_path] = script.ptr();
+ singleton->shallow_gdscript_cache.erase(p_path);
+
+ return script;
+}
+
+Error GDScriptCache::finish_compiling(const String &p_owner) {
+ // Mark this as compiled.
+ Ref<GDScript> script = get_shallow_script(p_owner);
+ singleton->full_gdscript_cache[p_owner] = script.ptr();
+ singleton->shallow_gdscript_cache.erase(p_owner);
+
+ Set<String> depends = singleton->dependencies[p_owner];
+
+ Error err = OK;
+ for (const Set<String>::Element *E = depends.front(); E != nullptr; E = E->next()) {
+ Error this_err = OK;
+ // No need to save the script. We assume it's already referenced in the owner.
+ get_full_script(E->get(), this_err);
+
+ if (this_err != OK) {
+ err = this_err;
+ }
+ }
+
+ singleton->dependencies.erase(p_owner);
+
+ return err;
+}
+
+GDScriptCache::GDScriptCache() {
+ singleton = this;
+}
+
+GDScriptCache::~GDScriptCache() {
+ parser_map.clear();
+ shallow_gdscript_cache.clear();
+ full_gdscript_cache.clear();
+ singleton = nullptr;
+}
diff --git a/modules/gdscript/gdscript_cache.h b/modules/gdscript/gdscript_cache.h
new file mode 100644
index 0000000000..d1d2a2abbf
--- /dev/null
+++ b/modules/gdscript/gdscript_cache.h
@@ -0,0 +1,97 @@
+/*************************************************************************/
+/* gdscript_cache.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_CACHE_H
+#define GDSCRIPT_CACHE_H
+
+#include "core/object/reference.h"
+#include "core/os/mutex.h"
+#include "core/templates/hash_map.h"
+#include "core/templates/set.h"
+#include "gdscript.h"
+
+class GDScriptAnalyzer;
+class GDScriptParser;
+
+class GDScriptParserRef : public Reference {
+public:
+ enum Status {
+ EMPTY,
+ PARSED,
+ INHERITANCE_SOLVED,
+ INTERFACE_SOLVED,
+ FULLY_SOLVED,
+ };
+
+private:
+ GDScriptParser *parser = nullptr;
+ GDScriptAnalyzer *analyzer = nullptr;
+ Status status = EMPTY;
+ String path;
+
+ friend class GDScriptCache;
+
+public:
+ bool is_valid() const;
+ Status get_status() const;
+ GDScriptParser *get_parser() const;
+ Error raise_status(Status p_new_status);
+
+ GDScriptParserRef() {}
+ ~GDScriptParserRef();
+};
+
+class GDScriptCache {
+ // String key is full path.
+ HashMap<String, GDScriptParserRef *> parser_map;
+ HashMap<String, GDScript *> shallow_gdscript_cache;
+ HashMap<String, GDScript *> full_gdscript_cache;
+ HashMap<String, Set<String>> dependencies;
+
+ friend class GDScript;
+ friend class GDScriptParserRef;
+
+ static GDScriptCache *singleton;
+
+ Mutex lock;
+ static void remove_script(const String &p_path);
+
+public:
+ static Ref<GDScriptParserRef> get_parser(const String &p_path, GDScriptParserRef::Status status, Error &r_error, const String &p_owner = String());
+ static String get_source_code(const String &p_path);
+ static Ref<GDScript> get_shallow_script(const String &p_path, const String &p_owner = String());
+ static Ref<GDScript> get_full_script(const String &p_path, Error &r_error, const String &p_owner = String());
+ static Error finish_compiling(const String &p_owner);
+
+ GDScriptCache();
+ ~GDScriptCache();
+};
+
+#endif // GDSCRIPT_CACHE_H
diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h
new file mode 100644
index 0000000000..d72bd12033
--- /dev/null
+++ b/modules/gdscript/gdscript_codegen.h
@@ -0,0 +1,167 @@
+/*************************************************************************/
+/* gdscript_codegen.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_CODEGEN
+#define GDSCRIPT_CODEGEN
+
+#include "core/io/multiplayer_api.h"
+#include "core/string/string_name.h"
+#include "core/variant/variant.h"
+#include "gdscript_function.h"
+#include "gdscript_utility_functions.h"
+
+class GDScriptCodeGenerator {
+public:
+ struct Address {
+ enum AddressMode {
+ SELF,
+ CLASS,
+ MEMBER,
+ CONSTANT,
+ CLASS_CONSTANT,
+ LOCAL_CONSTANT,
+ LOCAL_VARIABLE,
+ FUNCTION_PARAMETER,
+ TEMPORARY,
+ GLOBAL,
+ NAMED_GLOBAL,
+ NIL,
+ };
+ AddressMode mode = NIL;
+ uint32_t address = 0;
+ GDScriptDataType type;
+
+ Address() {}
+ Address(AddressMode p_mode, const GDScriptDataType &p_type = GDScriptDataType()) {
+ mode = p_mode;
+ type = p_type;
+ }
+ Address(AddressMode p_mode, uint32_t p_address, const GDScriptDataType &p_type = GDScriptDataType()) {
+ mode = p_mode,
+ address = p_address;
+ type = p_type;
+ }
+ };
+
+ virtual uint32_t add_parameter(const StringName &p_name, bool p_is_optional, const GDScriptDataType &p_type) = 0;
+ virtual uint32_t add_local(const StringName &p_name, const GDScriptDataType &p_type) = 0;
+ virtual uint32_t add_local_constant(const StringName &p_name, const Variant &p_constant) = 0;
+ virtual uint32_t add_or_get_constant(const Variant &p_constant) = 0;
+ virtual uint32_t add_or_get_name(const StringName &p_name) = 0;
+ virtual uint32_t add_temporary() = 0;
+ virtual void pop_temporary() = 0;
+
+ virtual void start_parameters() = 0;
+ virtual void end_parameters() = 0;
+
+ virtual void start_block() = 0;
+ virtual void end_block() = 0;
+
+ // virtual int get_max_stack_level() = 0;
+ // virtual int get_max_function_arguments() = 0;
+
+ virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) = 0;
+ virtual GDScriptFunction *write_end() = 0;
+
+#ifdef DEBUG_ENABLED
+ virtual void set_signature(const String &p_signature) = 0;
+#endif
+ virtual void set_initial_line(int p_line) = 0;
+
+ // virtual void alloc_stack(int p_level) = 0; // Is this needed?
+ // virtual void alloc_call(int p_arg_count) = 0; // This might be automatic from other functions.
+
+ virtual void write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) = 0;
+ virtual void write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) = 0;
+ virtual void write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) = 0;
+ virtual void write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) = 0;
+ virtual void write_and_left_operand(const Address &p_left_operand) = 0;
+ virtual void write_and_right_operand(const Address &p_right_operand) = 0;
+ virtual void write_end_and(const Address &p_target) = 0;
+ virtual void write_or_left_operand(const Address &p_left_operand) = 0;
+ virtual void write_or_right_operand(const Address &p_right_operand) = 0;
+ virtual void write_end_or(const Address &p_target) = 0;
+ virtual void write_start_ternary(const Address &p_target) = 0;
+ virtual void write_ternary_condition(const Address &p_condition) = 0;
+ virtual void write_ternary_true_expr(const Address &p_expr) = 0;
+ virtual void write_ternary_false_expr(const Address &p_expr) = 0;
+ virtual void write_end_ternary() = 0;
+ virtual void write_set(const Address &p_target, const Address &p_index, const Address &p_source) = 0;
+ virtual void write_get(const Address &p_target, const Address &p_index, const Address &p_source) = 0;
+ virtual void write_set_named(const Address &p_target, const StringName &p_name, const Address &p_source) = 0;
+ virtual void write_get_named(const Address &p_target, const StringName &p_name, const Address &p_source) = 0;
+ virtual void write_set_member(const Address &p_value, const StringName &p_name) = 0;
+ virtual void write_get_member(const Address &p_target, const StringName &p_name) = 0;
+ virtual void write_assign(const Address &p_target, const Address &p_source) = 0;
+ virtual void write_assign_true(const Address &p_target) = 0;
+ virtual void write_assign_false(const Address &p_target) = 0;
+ virtual void write_assign_default_parameter(const Address &dst, const Address &src) = 0;
+ virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) = 0;
+ virtual void write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0;
+ virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) = 0;
+ virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) = 0;
+ virtual void write_construct_dictionary(const Address &p_target, const Vector<Address> &p_arguments) = 0;
+ virtual void write_await(const Address &p_target, const Address &p_operand) = 0;
+ virtual void write_if(const Address &p_condition) = 0;
+ // virtual void write_elseif(const Address &p_condition) = 0; This kind of makes things more difficult for no real benefit.
+ virtual void write_else() = 0;
+ virtual void write_endif() = 0;
+ virtual void start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) = 0;
+ virtual void write_for_assignment(const Address &p_variable, const Address &p_list) = 0;
+ virtual void write_for() = 0;
+ virtual void write_endfor() = 0;
+ virtual void start_while_condition() = 0; // Used to allow a jump to the expression evaluation.
+ virtual void write_while(const Address &p_condition) = 0;
+ virtual void write_endwhile() = 0;
+ virtual void start_match() = 0;
+ virtual void start_match_branch() = 0;
+ virtual void end_match() = 0;
+ virtual void write_break() = 0;
+ virtual void write_continue() = 0;
+ virtual void write_continue_match() = 0;
+ virtual void write_breakpoint() = 0;
+ virtual void write_newline(int p_line) = 0;
+ virtual void write_return(const Address &p_return_value) = 0;
+ virtual void write_assert(const Address &p_test, const Address &p_message) = 0;
+
+ virtual ~GDScriptCodeGenerator() {}
+};
+
+#endif // GDSCRIPT_CODEGEN
diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp
index 2bbec29043..b491440d4c 100644
--- a/modules/gdscript/gdscript_compiler.cpp
+++ b/modules/gdscript/gdscript_compiler.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,26 +31,29 @@
#include "gdscript_compiler.h"
#include "gdscript.h"
+#include "gdscript_byte_codegen.h"
+#include "gdscript_cache.h"
+#include "gdscript_utility_functions.h"
bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {
-
- if (codegen.function_node && codegen.function_node->_static)
+ if (codegen.function_node && codegen.function_node->is_static) {
return false;
+ }
- if (codegen.stack_identifiers.has(p_name))
+ if (codegen.locals.has(p_name)) {
return false; //shadowed
+ }
return _is_class_member_property(codegen.script, p_name);
}
bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {
-
GDScript *scr = owner;
GDScriptNativeClass *nc = nullptr;
while (scr) {
-
- if (scr->native.is_valid())
+ if (scr->native.is_valid()) {
nc = scr->native.ptr();
+ }
scr = scr->_base;
}
@@ -60,59 +63,22 @@ bool GDScriptCompiler::_is_class_member_property(GDScript *owner, const StringNa
}
void GDScriptCompiler::_set_error(const String &p_error, const GDScriptParser::Node *p_node) {
-
- if (error != "")
+ if (error != "") {
return;
+ }
error = p_error;
if (p_node) {
- err_line = p_node->line;
- err_column = p_node->column;
+ err_line = p_node->start_line;
+ err_column = p_node->leftmost_column;
} else {
err_line = 0;
err_column = 0;
}
}
-bool GDScriptCompiler::_create_unary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level) {
-
- ERR_FAIL_COND_V(on->arguments.size() != 1, false);
-
- int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level);
- if (src_address_a < 0)
- return false;
-
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR); // perform operator
- codegen.opcodes.push_back(op); //which operator
- codegen.opcodes.push_back(src_address_a); // argument 1
- codegen.opcodes.push_back(src_address_a); // argument 2 (repeated)
- //codegen.opcodes.push_back(GDScriptFunction::ADDR_TYPE_NIL); // argument 2 (unary only takes one parameter)
- return true;
-}
-
-bool GDScriptCompiler::_create_binary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer, int p_index_addr) {
-
- ERR_FAIL_COND_V(on->arguments.size() != 2, false);
-
- int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level, false, p_initializer, p_index_addr);
- if (src_address_a < 0)
- return false;
- if (src_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS)
- p_stack_level++; //uses stack for return, increase stack
-
- int src_address_b = _parse_expression(codegen, on->arguments[1], p_stack_level, false, p_initializer);
- if (src_address_b < 0)
- return false;
-
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_OPERATOR); // perform operator
- codegen.opcodes.push_back(op); //which operator
- codegen.opcodes.push_back(src_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
- return true;
-}
-
-GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype) const {
- if (!p_datatype.has_type) {
+GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner) const {
+ if (!p_datatype.is_set() || !p_datatype.is_hard_type()) {
return GDScriptDataType();
}
@@ -120,6 +86,9 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D
result.has_type = true;
switch (p_datatype.kind) {
+ case GDScriptParser::DataType::VARIANT: {
+ result.has_type = false;
+ } break;
case GDScriptParser::DataType::BUILTIN: {
result.kind = GDScriptDataType::BUILTIN;
result.builtin_type = p_datatype.builtin_type;
@@ -130,1712 +99,1948 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D
} break;
case GDScriptParser::DataType::SCRIPT: {
result.kind = GDScriptDataType::SCRIPT;
- result.script_type = p_datatype.script_type;
- result.native_type = result.script_type->get_instance_base_type();
- } break;
- case GDScriptParser::DataType::GDSCRIPT: {
- result.kind = GDScriptDataType::GDSCRIPT;
- result.script_type = p_datatype.script_type;
+ result.script_type_ref = Ref<Script>(p_datatype.script_type);
+ result.script_type = result.script_type_ref.ptr();
result.native_type = result.script_type->get_instance_base_type();
} break;
case GDScriptParser::DataType::CLASS: {
// Locate class by constructing the path to it and following that path
GDScriptParser::ClassNode *class_type = p_datatype.class_type;
- List<StringName> names;
- while (class_type->owner) {
- names.push_back(class_type->name);
- class_type = class_type->owner;
- }
+ if (class_type) {
+ if (class_type->fqcn.begins_with(main_script->path) || (!main_script->name.is_empty() && class_type->fqcn.begins_with(main_script->name))) {
+ // Local class.
+ List<StringName> names;
+ while (class_type->outer) {
+ names.push_back(class_type->identifier->name);
+ class_type = class_type->outer;
+ }
- Ref<GDScript> script = Ref<GDScript>(main_script);
- while (names.back()) {
- if (!script->subclasses.has(names.back()->get())) {
- ERR_PRINT("Parser bug: Cannot locate datatype class.");
- result.has_type = false;
- return GDScriptDataType();
+ Ref<GDScript> script = Ref<GDScript>(main_script);
+ while (names.back()) {
+ if (!script->subclasses.has(names.back()->get())) {
+ ERR_PRINT("Parser bug: Cannot locate datatype class.");
+ result.has_type = false;
+ return GDScriptDataType();
+ }
+ script = script->subclasses[names.back()->get()];
+ names.pop_back();
+ }
+ result.kind = GDScriptDataType::GDSCRIPT;
+ result.script_type_ref = script;
+ result.script_type = result.script_type_ref.ptr();
+ result.native_type = script->get_instance_base_type();
+ } else {
+ result.kind = GDScriptDataType::GDSCRIPT;
+ result.script_type_ref = GDScriptCache::get_shallow_script(p_datatype.script_path, main_script->path);
+ result.script_type = result.script_type_ref.ptr();
+ result.native_type = p_datatype.native_type;
}
- script = script->subclasses[names.back()->get()];
- names.pop_back();
}
-
- result.kind = GDScriptDataType::GDSCRIPT;
- result.script_type = script;
- result.native_type = script->get_instance_base_type();
} break;
- default: {
+ case GDScriptParser::DataType::ENUM_VALUE:
+ result.has_type = true;
+ result.kind = GDScriptDataType::BUILTIN;
+ result.builtin_type = Variant::INT;
+ break;
+ case GDScriptParser::DataType::ENUM:
+ result.has_type = true;
+ result.kind = GDScriptDataType::BUILTIN;
+ result.builtin_type = Variant::DICTIONARY;
+ break;
+ case GDScriptParser::DataType::UNRESOLVED: {
ERR_PRINT("Parser bug: converting unresolved type.");
return GDScriptDataType();
}
}
+ // Only hold strong reference to the script if it's not the owner of the
+ // element qualified with this type, to avoid cyclic references (leaks).
+ if (result.script_type && result.script_type == p_owner) {
+ result.script_type_ref = Ref<Script>();
+ }
+
return result;
}
-int GDScriptCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::OperatorNode *p_expression, int p_stack_level, int p_index_addr) {
-
- Variant::Operator var_op = Variant::OP_MAX;
-
- switch (p_expression->op) {
-
- case GDScriptParser::OperatorNode::OP_ASSIGN_ADD: var_op = Variant::OP_ADD; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_SUB: var_op = Variant::OP_SUBTRACT; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_MUL: var_op = Variant::OP_MULTIPLY; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_DIV: var_op = Variant::OP_DIVIDE; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_MOD: var_op = Variant::OP_MODULE; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op = Variant::OP_SHIFT_LEFT; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op = Variant::OP_SHIFT_RIGHT; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op = Variant::OP_BIT_AND; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op = Variant::OP_BIT_OR; break;
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op = Variant::OP_BIT_XOR; break;
- case GDScriptParser::OperatorNode::OP_INIT_ASSIGN:
- case GDScriptParser::OperatorNode::OP_ASSIGN: {
-
- //none
- } break;
- default: {
-
- ERR_FAIL_V(-1);
+static bool _is_exact_type(const PropertyInfo &p_par_type, const GDScriptDataType &p_arg_type) {
+ if (!p_arg_type.has_type) {
+ return false;
+ }
+ if (p_par_type.type == Variant::NIL) {
+ return false;
+ }
+ if (p_par_type.type == Variant::OBJECT) {
+ if (p_arg_type.kind == GDScriptDataType::BUILTIN) {
+ return false;
}
+ StringName class_name;
+ if (p_arg_type.kind == GDScriptDataType::NATIVE) {
+ class_name = p_arg_type.native_type;
+ } else {
+ class_name = p_arg_type.native_type == StringName() ? p_arg_type.script_type->get_instance_base_type() : p_arg_type.native_type;
+ }
+ return p_par_type.class_name == class_name || ClassDB::is_parent_class(class_name, p_par_type.class_name);
+ } else {
+ if (p_arg_type.kind != GDScriptDataType::BUILTIN) {
+ return false;
+ }
+ return p_par_type.type == p_arg_type.builtin_type;
}
+}
- bool initializer = p_expression->op == GDScriptParser::OperatorNode::OP_INIT_ASSIGN;
-
- if (var_op == Variant::OP_MAX) {
-
- return _parse_expression(codegen, p_expression->arguments[1], p_stack_level, false, initializer);
+static bool _have_exact_arguments(const MethodBind *p_method, const Vector<GDScriptCodeGenerator::Address> &p_arguments) {
+ if (p_method->get_argument_count() != p_arguments.size()) {
+ // ptrcall won't work with default arguments.
+ return false;
}
-
- if (!_create_binary_operator(codegen, p_expression, var_op, p_stack_level, initializer, p_index_addr))
- return -1;
-
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
+ MethodInfo info;
+ ClassDB::get_method_info(p_method->get_instance_class(), p_method->get_name(), &info);
+ for (int i = 0; i < p_arguments.size(); i++) {
+ const PropertyInfo &prop = info.arguments[i];
+ if (!_is_exact_type(prop, p_arguments[i].type)) {
+ return false;
+ }
+ }
+ return true;
}
-int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::Node *p_expression, int p_stack_level, bool p_root, bool p_initializer, int p_index_addr) {
-
- switch (p_expression->type) {
- //should parse variable declaration and adjust stack accordingly...
- case GDScriptParser::Node::TYPE_IDENTIFIER: {
- //return identifier
- //wait, identifier could be a local variable or something else... careful here, must reference properly
- //as stack may be more interesting to work with
+GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root, bool p_initializer, const GDScriptCodeGenerator::Address &p_index_addr) {
+ if (p_expression->is_constant) {
+ return codegen.add_constant(p_expression->reduced_value);
+ }
- //This could be made much simpler by just indexing "self", but done this way (with custom self-addressing modes) increases performance a lot.
+ GDScriptCodeGenerator *gen = codegen.generator;
+ switch (p_expression->type) {
+ case GDScriptParser::Node::IDENTIFIER: {
+ // Look for identifiers in current scope.
const GDScriptParser::IdentifierNode *in = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
StringName identifier = in->name;
- // TRY STACK!
- if (!p_initializer && codegen.stack_identifiers.has(identifier)) {
+ // Try function parameters.
+ if (codegen.parameters.has(identifier)) {
+ return codegen.parameters[identifier];
+ }
- int pos = codegen.stack_identifiers[identifier];
- return pos | (GDScriptFunction::ADDR_TYPE_STACK_VARIABLE << GDScriptFunction::ADDR_BITS);
+ // Try local variables and constants.
+ if (!p_initializer && codegen.locals.has(identifier)) {
+ return codegen.locals[identifier];
}
- // TRY CLASS MEMBER
+ // Try class members.
if (_is_class_member_property(codegen, identifier)) {
- //get property
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_GET_MEMBER); // perform operator
- codegen.opcodes.push_back(codegen.get_name_map_pos(identifier)); // argument 2 (unary only takes one parameter)
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
+ // Get property.
+ GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Could get the type of the class member here.
+ gen->write_get_member(temp, identifier);
+ return temp;
}
- //TRY MEMBERS!
- if (!codegen.function_node || !codegen.function_node->_static) {
-
- // TRY MEMBER VARIABLES!
- //static function
+ // Try members.
+ if (!codegen.function_node || !codegen.function_node->is_static) {
+ // Try member variables.
if (codegen.script->member_indices.has(identifier)) {
-
- int idx = codegen.script->member_indices[identifier].index;
- return idx | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS); //argument (stack root)
+ if (codegen.script->member_indices[identifier].getter != StringName() && codegen.script->member_indices[identifier].getter != codegen.function_name) {
+ // Perform getter.
+ GDScriptCodeGenerator::Address temp = codegen.add_temporary();
+ Vector<GDScriptCodeGenerator::Address> args; // No argument needed.
+ gen->write_call_self(temp, codegen.script->member_indices[identifier].getter, args);
+ return temp;
+ } else {
+ // No getter or inside getter: direct member access.,
+ int idx = codegen.script->member_indices[identifier].index;
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, idx, codegen.script->get_member_type(identifier));
+ }
}
}
- //TRY CLASS CONSTANTS
-
+ // Try class constants.
GDScript *owner = codegen.script;
while (owner) {
-
GDScript *scr = owner;
GDScriptNativeClass *nc = nullptr;
while (scr) {
-
if (scr->constants.has(identifier)) {
-
- //int idx=scr->constants[identifier];
- int idx = codegen.get_name_map_pos(identifier);
- return idx | (GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT << GDScriptFunction::ADDR_BITS); //argument (stack root)
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::CLASS_CONSTANT, gen->add_or_get_name(identifier)); // TODO: Get type here.
}
- if (scr->native.is_valid())
+ if (scr->native.is_valid()) {
nc = scr->native.ptr();
+ }
scr = scr->_base;
}
- // CLASS C++ Integer Constant
-
+ // Class C++ integer constant.
if (nc) {
-
bool success = false;
int constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success);
if (success) {
- Variant key = constant;
- int idx;
-
- if (!codegen.constant_map.has(key)) {
-
- idx = codegen.constant_map.size();
- codegen.constant_map[key] = idx;
-
- } else {
- idx = codegen.constant_map[key];
- }
-
- return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //make it a local constant (faster access)
+ return codegen.add_constant(constant);
}
}
owner = owner->_owner;
}
- if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
+ // Try signals and methods (can be made callables);
+ if (codegen.class_node->members_indices.has(identifier)) {
+ const GDScriptParser::ClassNode::Member &member = codegen.class_node->members[codegen.class_node->members_indices[identifier]];
+ if (member.type == GDScriptParser::ClassNode::Member::FUNCTION || member.type == GDScriptParser::ClassNode::Member::SIGNAL) {
+ // Get like it was a property.
+ GDScriptCodeGenerator::Address temp = codegen.add_temporary(); // TODO: Get type here.
+ GDScriptCodeGenerator::Address self(GDScriptCodeGenerator::Address::SELF);
- int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
- return idx | (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
+ gen->write_get_named(temp, identifier, self);
+ return temp;
+ }
}
- /* TRY GLOBAL CLASSES */
+ if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
+ int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::GLOBAL, idx); // TODO: Get type.
+ }
+ // Try global classes.
if (ScriptServer::is_global_class(identifier)) {
-
const GDScriptParser::ClassNode *class_node = codegen.class_node;
- while (class_node->owner) {
- class_node = class_node->owner;
+ while (class_node->outer) {
+ class_node = class_node->outer;
}
- if (class_node->name == identifier) {
- _set_error("Using own name in class file is not allowed (creates a cyclic reference)", p_expression);
- return -1;
- }
-
- RES res = ResourceLoader::load(ScriptServer::get_global_class_path(identifier));
- if (res.is_null()) {
- _set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression);
- return -1;
- }
-
- Variant key = res;
- int idx;
-
- if (!codegen.constant_map.has(key)) {
-
- idx = codegen.constant_map.size();
- codegen.constant_map[key] = idx;
+ RES res;
+ if (class_node->identifier && class_node->identifier->name == identifier) {
+ res = Ref<GDScript>(main_script);
} else {
- idx = codegen.constant_map[key];
+ res = ResourceLoader::load(ScriptServer::get_global_class_path(identifier));
+ if (res.is_null()) {
+ _set_error("Can't load global class " + String(identifier) + ", cyclic reference?", p_expression);
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
+ }
}
- return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //make it a local constant (faster access)
+ return codegen.add_constant(res);
}
#ifdef TOOLS_ENABLED
if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) {
-
- int idx = codegen.named_globals.find(identifier);
- if (idx == -1) {
- idx = codegen.named_globals.size();
- codegen.named_globals.push_back(identifier);
- }
- return idx | (GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL << GDScriptFunction::ADDR_BITS);
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::NAMED_GLOBAL, gen->add_or_get_name(identifier)); // TODO: Get type.
}
#endif
- //not found, error
-
+ // Not found, error.
_set_error("Identifier not found: " + String(identifier), p_expression);
-
- return -1;
-
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
} break;
- case GDScriptParser::Node::TYPE_CONSTANT: {
- //return constant
- const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(p_expression);
-
- int idx;
-
- if (!codegen.constant_map.has(cn->value)) {
-
- idx = codegen.constant_map.size();
- codegen.constant_map[cn->value] = idx;
-
- } else {
- idx = codegen.constant_map[cn->value];
- }
-
- return idx | (GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS); //argument (stack root)
+ case GDScriptParser::Node::LITERAL: {
+ // Return constant.
+ const GDScriptParser::LiteralNode *cn = static_cast<const GDScriptParser::LiteralNode *>(p_expression);
+ return codegen.add_constant(cn->value);
} break;
- case GDScriptParser::Node::TYPE_SELF: {
+ case GDScriptParser::Node::SELF: {
//return constant
- if (codegen.function_node && codegen.function_node->_static) {
+ if (codegen.function_node && codegen.function_node->is_static) {
_set_error("'self' not present in static function!", p_expression);
- return -1;
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
}
- return (GDScriptFunction::ADDR_TYPE_SELF << GDScriptFunction::ADDR_BITS);
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF);
} break;
- case GDScriptParser::Node::TYPE_ARRAY: {
-
+ case GDScriptParser::Node::ARRAY: {
const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
- Vector<int> values;
+ Vector<GDScriptCodeGenerator::Address> values;
- int slevel = p_stack_level;
+ // Create the result temporary first since it's the last to be killed.
+ GDScriptDataType array_type;
+ array_type.has_type = true;
+ array_type.kind = GDScriptDataType::BUILTIN;
+ array_type.builtin_type = Variant::ARRAY;
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(array_type);
for (int i = 0; i < an->elements.size(); i++) {
-
- int ret = _parse_expression(codegen, an->elements[i], slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
+ GDScriptCodeGenerator::Address val = _parse_expression(codegen, r_error, an->elements[i]);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
}
-
- values.push_back(ret);
+ values.push_back(val);
}
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT_ARRAY);
- codegen.opcodes.push_back(values.size());
- for (int i = 0; i < values.size(); i++)
- codegen.opcodes.push_back(values[i]);
+ gen->write_construct_array(result, values);
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
+ for (int i = 0; i < values.size(); i++) {
+ if (values[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ }
+ return result;
} break;
- case GDScriptParser::Node::TYPE_DICTIONARY: {
-
+ case GDScriptParser::Node::DICTIONARY: {
const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
- Vector<int> values;
+ Vector<GDScriptCodeGenerator::Address> elements;
- int slevel = p_stack_level;
+ // Create the result temporary first since it's the last to be killed.
+ GDScriptDataType dict_type;
+ dict_type.has_type = true;
+ dict_type.kind = GDScriptDataType::BUILTIN;
+ dict_type.builtin_type = Variant::DICTIONARY;
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(dict_type);
for (int i = 0; i < dn->elements.size(); i++) {
-
- int ret = _parse_expression(codegen, dn->elements[i].key, slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
+ // Key.
+ GDScriptCodeGenerator::Address element;
+ switch (dn->style) {
+ case GDScriptParser::DictionaryNode::PYTHON_DICT:
+ // Python-style: key is any expression.
+ element = _parse_expression(codegen, r_error, dn->elements[i].key);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ break;
+ case GDScriptParser::DictionaryNode::LUA_TABLE:
+ // Lua-style: key is an identifier interpreted as string.
+ String key = static_cast<const GDScriptParser::IdentifierNode *>(dn->elements[i].key)->name;
+ element = codegen.add_constant(key);
+ break;
}
- values.push_back(ret);
+ elements.push_back(element);
- ret = _parse_expression(codegen, dn->elements[i].value, slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
+ element = _parse_expression(codegen, r_error, dn->elements[i].value);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
}
- values.push_back(ret);
+ elements.push_back(element);
}
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY);
- codegen.opcodes.push_back(dn->elements.size());
- for (int i = 0; i < values.size(); i++)
- codegen.opcodes.push_back(values[i]);
+ gen->write_construct_dictionary(result, elements);
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
+ for (int i = 0; i < elements.size(); i++) {
+ if (elements[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ }
+ return result;
} break;
- case GDScriptParser::Node::TYPE_CAST: {
+ case GDScriptParser::Node::CAST: {
const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
+ GDScriptDataType cast_type = _gdtype_from_datatype(cn->cast_type->get_datatype());
- int slevel = p_stack_level;
- int src_addr = _parse_expression(codegen, cn->source_node, slevel);
- if (src_addr < 0)
- return src_addr;
- if (src_addr & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
-
- GDScriptDataType cast_type = _gdtype_from_datatype(cn->cast_type);
+ // Create temporary for result first since it will be deleted last.
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(cast_type);
- switch (cast_type.kind) {
- case GDScriptDataType::BUILTIN: {
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_BUILTIN);
- codegen.opcodes.push_back(cast_type.builtin_type);
- } break;
- case GDScriptDataType::NATIVE: {
- int class_idx;
- if (GDScriptLanguage::get_singleton()->get_global_map().has(cast_type.native_type)) {
-
- class_idx = GDScriptLanguage::get_singleton()->get_global_map()[cast_type.native_type];
- class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
- } else {
- _set_error("Invalid native class type '" + String(cast_type.native_type) + "'.", cn);
- return -1;
- }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_NATIVE); // perform operator
- codegen.opcodes.push_back(class_idx); // variable type
- } break;
- case GDScriptDataType::SCRIPT:
- case GDScriptDataType::GDSCRIPT: {
+ GDScriptCodeGenerator::Address source = _parse_expression(codegen, r_error, cn->operand);
- Variant script = cast_type.script_type;
- int idx = codegen.get_constant_pos(script);
- idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access)
+ gen->write_cast(result, source, cast_type);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CAST_TO_SCRIPT); // perform operator
- codegen.opcodes.push_back(idx); // variable type
- } break;
- default: {
- _set_error("Parser bug: unresolved data type.", cn);
- return -1;
- }
+ if (source.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
}
- codegen.opcodes.push_back(src_addr); // source address
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
-
+ return result;
} break;
- case GDScriptParser::Node::TYPE_OPERATOR: {
- //hell breaks loose
-
- const GDScriptParser::OperatorNode *on = static_cast<const GDScriptParser::OperatorNode *>(p_expression);
- switch (on->op) {
-
- //call/constructor operator
- case GDScriptParser::OperatorNode::OP_PARENT_CALL: {
-
- ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
+ case GDScriptParser::Node::CALL: {
+ const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);
+ GDScriptDataType type = _gdtype_from_datatype(call->get_datatype());
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(type);
+
+ Vector<GDScriptCodeGenerator::Address> arguments;
+ for (int i = 0; i < call->arguments.size(); i++) {
+ GDScriptCodeGenerator::Address arg = _parse_expression(codegen, r_error, call->arguments[i]);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ arguments.push_back(arg);
+ }
- const GDScriptParser::IdentifierNode *in = (const GDScriptParser::IdentifierNode *)on->arguments[0];
+ if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(call->function_name) != Variant::VARIANT_MAX) {
+ // Construct a built-in type.
+ Variant::Type vtype = GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(call->callee)->name);
+
+ gen->write_construct(result, vtype, arguments);
+ } else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && Variant::has_utility_function(call->function_name)) {
+ // Variant utility function.
+ gen->write_call_utility(result, call->function_name, arguments);
+ } else if (!call->is_super && call->callee->type == GDScriptParser::Node::IDENTIFIER && GDScriptUtilityFunctions::function_exists(call->function_name)) {
+ // GDScript utility function.
+ gen->write_call_gdscript_utility(result, GDScriptUtilityFunctions::get_function(call->function_name), arguments);
+ } else {
+ // Regular function.
+ const GDScriptParser::ExpressionNode *callee = call->callee;
- Vector<int> arguments;
- int slevel = p_stack_level;
- for (int i = 1; i < on->arguments.size(); i++) {
+ if (call->is_super) {
+ // Super call.
+ gen->write_super_call(result, call->function_name, arguments);
+ } else {
+ if (callee->type == GDScriptParser::Node::IDENTIFIER) {
+ // Self function call.
+ if (ClassDB::has_method(codegen.script->native->get_name(), call->function_name)) {
+ // Native method, use faster path.
+ GDScriptCodeGenerator::Address self;
+ self.mode = GDScriptCodeGenerator::Address::SELF;
+ MethodBind *method = ClassDB::get_method(codegen.script->native->get_name(), call->function_name);
+
+ if (_have_exact_arguments(method, arguments)) {
+ // Exact arguments, use ptrcall.
+ gen->write_call_ptrcall(result, self, method, arguments);
+ } else {
+ // Not exact arguments, but still can use method bind call.
+ gen->write_call_method_bind(result, self, method, arguments);
+ }
+ } else if ((codegen.function_node && codegen.function_node->is_static) || call->function_name == "new") {
+ GDScriptCodeGenerator::Address self;
+ self.mode = GDScriptCodeGenerator::Address::CLASS;
+ if (within_await) {
+ gen->write_call_async(result, self, call->function_name, arguments);
+ } else {
+ gen->write_call(result, self, call->function_name, arguments);
+ }
+ } else {
+ if (within_await) {
+ gen->write_call_self_async(result, call->function_name, arguments);
+ } else {
+ gen->write_call_self(result, call->function_name, arguments);
+ }
+ }
+ } else if (callee->type == GDScriptParser::Node::SUBSCRIPT) {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);
- int ret = _parse_expression(codegen, on->arguments[i], slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
+ if (subscript->is_attribute) {
+ GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ if (within_await) {
+ gen->write_call_async(result, base, call->function_name, arguments);
+ } else if (base.type.has_type && base.type.kind != GDScriptDataType::BUILTIN) {
+ // Native method, use faster path.
+ StringName class_name;
+ if (base.type.kind == GDScriptDataType::NATIVE) {
+ class_name = base.type.native_type;
+ } else {
+ class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type;
+ }
+ if (ClassDB::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) {
+ MethodBind *method = ClassDB::get_method(class_name, call->function_name);
+ if (_have_exact_arguments(method, arguments)) {
+ // Exact arguments, use ptrcall.
+ gen->write_call_ptrcall(result, base, method, arguments);
+ } else {
+ // Not exact arguments, but still can use method bind call.
+ gen->write_call_method_bind(result, base, method, arguments);
+ }
+ } else {
+ gen->write_call(result, base, call->function_name, arguments);
+ }
+ } else if (base.type.has_type && base.type.kind == GDScriptDataType::BUILTIN) {
+ gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments);
+ } else {
+ gen->write_call(result, base, call->function_name, arguments);
+ }
+ if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ } else {
+ _set_error("Cannot call something that isn't a function.", call->callee);
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
}
- arguments.push_back(ret);
+ } else {
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
}
+ }
+ }
- //push call bytecode
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_SELF_BASE); // basic type constructor
+ for (int i = 0; i < arguments.size(); i++) {
+ if (arguments[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ }
+ return result;
+ } break;
+ case GDScriptParser::Node::GET_NODE: {
+ const GDScriptParser::GetNodeNode *get_node = static_cast<const GDScriptParser::GetNodeNode *>(p_expression);
- codegen.opcodes.push_back(codegen.get_name_map_pos(in->name)); //instance
- codegen.opcodes.push_back(arguments.size()); //argument count
- codegen.alloc_call(arguments.size());
- for (int i = 0; i < arguments.size(); i++)
- codegen.opcodes.push_back(arguments[i]); //arguments
+ String node_name;
+ if (get_node->string != nullptr) {
+ node_name += String(get_node->string->value);
+ } else {
+ for (int i = 0; i < get_node->chain.size(); i++) {
+ if (i > 0) {
+ node_name += "/";
+ }
+ node_name += get_node->chain[i]->name;
+ }
+ }
- } break;
- case GDScriptParser::OperatorNode::OP_CALL: {
+ Vector<GDScriptCodeGenerator::Address> args;
+ args.push_back(codegen.add_constant(NodePath(node_name)));
- if (on->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) {
- //construct a basic type
- ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(get_node->get_datatype()));
- const GDScriptParser::TypeNode *tn = (const GDScriptParser::TypeNode *)on->arguments[0];
- int vtype = tn->vtype;
+ MethodBind *get_node_method = ClassDB::get_method("Node", "get_node");
+ gen->write_call_ptrcall(result, GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), get_node_method, args);
- Vector<int> arguments;
- int slevel = p_stack_level;
- for (int i = 1; i < on->arguments.size(); i++) {
+ return result;
+ } break;
+ case GDScriptParser::Node::PRELOAD: {
+ const GDScriptParser::PreloadNode *preload = static_cast<const GDScriptParser::PreloadNode *>(p_expression);
- int ret = _parse_expression(codegen, on->arguments[i], slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
- arguments.push_back(ret);
- }
+ // Add resource as constant.
+ return codegen.add_constant(preload->resource);
+ } break;
+ case GDScriptParser::Node::AWAIT: {
+ const GDScriptParser::AwaitNode *await = static_cast<const GDScriptParser::AwaitNode *>(p_expression);
+
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(p_expression->get_datatype()));
+ within_await = true;
+ GDScriptCodeGenerator::Address argument = _parse_expression(codegen, r_error, await->to_await);
+ within_await = false;
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- //push call bytecode
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CONSTRUCT); // basic type constructor
- codegen.opcodes.push_back(vtype); //instance
- codegen.opcodes.push_back(arguments.size()); //argument count
- codegen.alloc_call(arguments.size());
- for (int i = 0; i < arguments.size(); i++)
- codegen.opcodes.push_back(arguments[i]); //arguments
+ gen->write_await(result, argument);
- } else if (on->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) {
- //built in function
+ if (argument.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
+ return result;
+ } break;
+ // Indexing operator.
+ case GDScriptParser::Node::SUBSCRIPT: {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(subscript->get_datatype()));
+
+ GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- Vector<int> arguments;
- int slevel = p_stack_level;
- for (int i = 1; i < on->arguments.size(); i++) {
+ bool named = subscript->is_attribute;
+ StringName name;
+ GDScriptCodeGenerator::Address index;
+ if (p_index_addr.mode != GDScriptCodeGenerator::Address::NIL) {
+ index = p_index_addr;
+ } else if (subscript->is_attribute) {
+ if (subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
+ GDScriptParser::IdentifierNode *identifier = subscript->attribute;
+ const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name);
- int ret = _parse_expression(codegen, on->arguments[i], slevel);
- if (ret < 0)
- return ret;
+#ifdef DEBUG_ENABLED
+ if (MI && MI->get().getter == codegen.function_name) {
+ String n = identifier->name;
+ _set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", identifier);
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
+ }
+#endif
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
+ if (MI && MI->get().getter == "") {
+ // Remove result temp as we don't need it.
+ gen->pop_temporary();
+ // Faster than indexing self (as if no self. had been used).
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::MEMBER, MI->get().index, _gdtype_from_datatype(subscript->get_datatype()));
+ }
+ }
- arguments.push_back(ret);
- }
+ name = subscript->attribute->name;
+ named = true;
+ } else {
+ if (subscript->index->type == GDScriptParser::Node::LITERAL && static_cast<const GDScriptParser::LiteralNode *>(subscript->index)->value.get_type() == Variant::STRING) {
+ // Also, somehow, named (speed up anyway).
+ name = static_cast<const GDScriptParser::LiteralNode *>(subscript->index)->value;
+ named = true;
+ } else {
+ // Regular indexing.
+ index = _parse_expression(codegen, r_error, subscript->index);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ }
+ }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_BUILT_IN);
- codegen.opcodes.push_back(static_cast<const GDScriptParser::BuiltInFunctionNode *>(on->arguments[0])->function);
- codegen.opcodes.push_back(on->arguments.size() - 1);
- codegen.alloc_call(on->arguments.size() - 1);
- for (int i = 0; i < arguments.size(); i++)
- codegen.opcodes.push_back(arguments[i]);
+ if (named) {
+ gen->write_get_named(result, name, base);
+ } else {
+ gen->write_get(result, index, base);
+ }
- } else {
- //regular function
- ERR_FAIL_COND_V(on->arguments.size() < 2, -1);
+ if (index.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- const GDScriptParser::Node *instance = on->arguments[0];
+ return result;
+ } break;
+ case GDScriptParser::Node::UNARY_OPERATOR: {
+ const GDScriptParser::UnaryOpNode *unary = static_cast<const GDScriptParser::UnaryOpNode *>(p_expression);
- if (instance->type == GDScriptParser::Node::TYPE_SELF) {
- //room for optimization
- }
+ GDScriptCodeGenerator::Address result = codegen.add_temporary();
- Vector<int> arguments;
- int slevel = p_stack_level;
+ GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, unary->operand);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- for (int i = 0; i < on->arguments.size(); i++) {
+ gen->write_unary_operator(result, unary->variant_op, operand);
- int ret;
+ if (operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- if (i == 0 && on->arguments[i]->type == GDScriptParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) {
- //static call to self
- ret = (GDScriptFunction::ADDR_TYPE_CLASS << GDScriptFunction::ADDR_BITS);
- } else if (i == 1) {
+ return result;
+ }
+ case GDScriptParser::Node::BINARY_OPERATOR: {
+ const GDScriptParser::BinaryOpNode *binary = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
- if (on->arguments[i]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- _set_error("Attempt to call a non-identifier.", on);
- return -1;
- }
- GDScriptParser::IdentifierNode *id = static_cast<GDScriptParser::IdentifierNode *>(on->arguments[i]);
- ret = codegen.get_name_map_pos(id->name);
+ GDScriptCodeGenerator::Address result = codegen.add_temporary();
- } else {
+ switch (binary->operation) {
+ case GDScriptParser::BinaryOpNode::OP_LOGIC_AND: {
+ // AND operator with early out on failure.
+ GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
+ gen->write_and_left_operand(left_operand);
+ GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
+ gen->write_and_right_operand(right_operand);
- ret = _parse_expression(codegen, on->arguments[i], slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
- }
- arguments.push_back(ret);
- }
+ gen->write_end_and(result);
- codegen.opcodes.push_back(p_root ? GDScriptFunction::OPCODE_CALL : GDScriptFunction::OPCODE_CALL_RETURN); // perform operator
- codegen.opcodes.push_back(on->arguments.size() - 2);
- codegen.alloc_call(on->arguments.size() - 2);
- for (int i = 0; i < arguments.size(); i++)
- codegen.opcodes.push_back(arguments[i]);
+ if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
}
} break;
- case GDScriptParser::OperatorNode::OP_YIELD: {
+ case GDScriptParser::BinaryOpNode::OP_LOGIC_OR: {
+ // OR operator with early out on success.
+ GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
+ gen->write_or_left_operand(left_operand);
+ GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
+ gen->write_or_right_operand(right_operand);
- ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size() != 2, -1);
+ gen->write_end_or(result);
- Vector<int> arguments;
- int slevel = p_stack_level;
- for (int i = 0; i < on->arguments.size(); i++) {
-
- int ret = _parse_expression(codegen, on->arguments[i], slevel);
- if (ret < 0)
- return ret;
- if ((ret >> GDScriptFunction::ADDR_BITS & GDScriptFunction::ADDR_TYPE_STACK) == GDScriptFunction::ADDR_TYPE_STACK) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
- arguments.push_back(ret);
+ if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
}
-
- //push call bytecode
- codegen.opcodes.push_back(arguments.size() == 0 ? GDScriptFunction::OPCODE_YIELD : GDScriptFunction::OPCODE_YIELD_SIGNAL); // basic type constructor
- for (int i = 0; i < arguments.size(); i++)
- codegen.opcodes.push_back(arguments[i]); //arguments
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_YIELD_RESUME);
- //next will be where to place the result :)
-
} break;
+ case GDScriptParser::BinaryOpNode::OP_TYPE_TEST: {
+ GDScriptCodeGenerator::Address operand = _parse_expression(codegen, r_error, binary->left_operand);
- //indexing operator
- case GDScriptParser::OperatorNode::OP_INDEX:
- case GDScriptParser::OperatorNode::OP_INDEX_NAMED: {
-
- ERR_FAIL_COND_V(on->arguments.size() != 2, -1);
-
- int slevel = p_stack_level;
- bool named = (on->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED);
-
- int from = _parse_expression(codegen, on->arguments[0], slevel);
- if (from < 0)
- return from;
-
- int index;
- if (p_index_addr != 0) {
- index = p_index_addr;
- } else if (named) {
- if (on->arguments[0]->type == GDScriptParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) {
-
- GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(on->arguments[1]);
- const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name);
-
-#ifdef DEBUG_ENABLED
- if (MI && MI->get().getter == codegen.function_node->name) {
- String n = static_cast<GDScriptParser::IdentifierNode *>(on->arguments[1])->name;
- _set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", on);
- return -1;
- }
-#endif
-
- if (MI && MI->get().getter == "") {
- // Faster than indexing self (as if no self. had been used)
- return (MI->get().index) | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS);
- }
- }
-
- index = codegen.get_name_map_pos(static_cast<GDScriptParser::IdentifierNode *>(on->arguments[1])->name);
-
+ if (binary->right_operand->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name) != Variant::VARIANT_MAX) {
+ // `is` with builtin type)
+ Variant::Type type = GDScriptParser::get_builtin_type(static_cast<const GDScriptParser::IdentifierNode *>(binary->right_operand)->name);
+ gen->write_type_test_builtin(result, operand, type);
} else {
-
- if (on->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT && static_cast<const GDScriptParser::ConstantNode *>(on->arguments[1])->value.get_type() == Variant::STRING) {
- //also, somehow, named (speed up anyway)
- StringName name = static_cast<const GDScriptParser::ConstantNode *>(on->arguments[1])->value;
- index = codegen.get_name_map_pos(name);
- named = true;
-
- } else {
- //regular indexing
- if (from & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
-
- index = _parse_expression(codegen, on->arguments[1], slevel);
- if (index < 0)
- return index;
+ GDScriptCodeGenerator::Address type = _parse_expression(codegen, r_error, binary->right_operand);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ gen->write_type_test(result, operand, type);
+ if (type.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
}
}
-
- codegen.opcodes.push_back(named ? GDScriptFunction::OPCODE_GET_NAMED : GDScriptFunction::OPCODE_GET); // perform operator
- codegen.opcodes.push_back(from); // argument 1
- codegen.opcodes.push_back(index); // argument 2 (unary only takes one parameter)
-
- } break;
- case GDScriptParser::OperatorNode::OP_AND: {
-
- // AND operator with early out on failure
-
- int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
- if (res < 0)
- return res;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
- codegen.opcodes.push_back(res);
- int jump_fail_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
-
- res = _parse_expression(codegen, on->arguments[1], p_stack_level);
- if (res < 0)
- return res;
-
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
- codegen.opcodes.push_back(res);
- int jump_fail_pos2 = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
-
- codegen.alloc_stack(p_stack_level); //it will be used..
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TRUE);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size() + 3);
- codegen.opcodes.write[jump_fail_pos] = codegen.opcodes.size();
- codegen.opcodes.write[jump_fail_pos2] = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_FALSE);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
-
} break;
- case GDScriptParser::OperatorNode::OP_OR: {
-
- // OR operator with early out on success
-
- int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
- if (res < 0)
- return res;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF);
- codegen.opcodes.push_back(res);
- int jump_success_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
-
- res = _parse_expression(codegen, on->arguments[1], p_stack_level);
- if (res < 0)
- return res;
-
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF);
- codegen.opcodes.push_back(res);
- int jump_success_pos2 = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
-
- codegen.alloc_stack(p_stack_level); //it will be used..
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_FALSE);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size() + 3);
- codegen.opcodes.write[jump_success_pos] = codegen.opcodes.size();
- codegen.opcodes.write[jump_success_pos2] = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TRUE);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
+ default: {
+ GDScriptCodeGenerator::Address left_operand = _parse_expression(codegen, r_error, binary->left_operand);
+ GDScriptCodeGenerator::Address right_operand = _parse_expression(codegen, r_error, binary->right_operand);
- } break;
- // ternary operators
- case GDScriptParser::OperatorNode::OP_TERNARY_IF: {
+ gen->write_binary_operator(result, binary->variant_op, left_operand, right_operand);
- // x IF a ELSE y operator with early out on failure
+ if (right_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (left_operand.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ }
+ }
+ return result;
+ } break;
+ case GDScriptParser::Node::TERNARY_OPERATOR: {
+ // x IF a ELSE y operator with early out on failure.
+ const GDScriptParser::TernaryOpNode *ternary = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);
+ GDScriptCodeGenerator::Address result = codegen.add_temporary(_gdtype_from_datatype(ternary->get_datatype()));
- int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
- if (res < 0)
- return res;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
- codegen.opcodes.push_back(res);
- int jump_fail_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
+ gen->write_start_ternary(result);
- res = _parse_expression(codegen, on->arguments[1], p_stack_level);
- if (res < 0)
- return res;
+ GDScriptCodeGenerator::Address condition = _parse_expression(codegen, r_error, ternary->condition);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ gen->write_ternary_condition(condition);
- codegen.alloc_stack(p_stack_level); //it will be used..
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(res);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- int jump_past_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
+ if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- codegen.opcodes.write[jump_fail_pos] = codegen.opcodes.size();
- res = _parse_expression(codegen, on->arguments[2], p_stack_level);
- if (res < 0)
- return res;
+ GDScriptCodeGenerator::Address true_expr = _parse_expression(codegen, r_error, ternary->true_expr);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ gen->write_ternary_true_expr(true_expr);
+ if (true_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
- codegen.opcodes.push_back(p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(res);
+ GDScriptCodeGenerator::Address false_expr = _parse_expression(codegen, r_error, ternary->false_expr);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ gen->write_ternary_false_expr(false_expr);
+ if (false_expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- codegen.opcodes.write[jump_past_pos] = codegen.opcodes.size();
+ gen->write_end_ternary();
- return p_stack_level | GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS;
+ return result;
+ } break;
+ case GDScriptParser::Node::ASSIGNMENT: {
+ const GDScriptParser::AssignmentNode *assignment = static_cast<const GDScriptParser::AssignmentNode *>(p_expression);
- } break;
- //unary operators
- case GDScriptParser::OperatorNode::OP_NEG: {
- if (!_create_unary_operator(codegen, on, Variant::OP_NEGATE, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_POS: {
- if (!_create_unary_operator(codegen, on, Variant::OP_POSITIVE, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_NOT: {
- if (!_create_unary_operator(codegen, on, Variant::OP_NOT, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_BIT_INVERT: {
- if (!_create_unary_operator(codegen, on, Variant::OP_BIT_NEGATE, p_stack_level)) return -1;
- } break;
- //binary operators (in precedence order)
- case GDScriptParser::OperatorNode::OP_IN: {
- if (!_create_binary_operator(codegen, on, Variant::OP_IN, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_EQUAL: {
- if (!_create_binary_operator(codegen, on, Variant::OP_EQUAL, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_NOT_EQUAL: {
- if (!_create_binary_operator(codegen, on, Variant::OP_NOT_EQUAL, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_LESS: {
- if (!_create_binary_operator(codegen, on, Variant::OP_LESS, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_LESS_EQUAL: {
- if (!_create_binary_operator(codegen, on, Variant::OP_LESS_EQUAL, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_GREATER: {
- if (!_create_binary_operator(codegen, on, Variant::OP_GREATER, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_GREATER_EQUAL: {
- if (!_create_binary_operator(codegen, on, Variant::OP_GREATER_EQUAL, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_ADD: {
- if (!_create_binary_operator(codegen, on, Variant::OP_ADD, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_SUB: {
- if (!_create_binary_operator(codegen, on, Variant::OP_SUBTRACT, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_MUL: {
- if (!_create_binary_operator(codegen, on, Variant::OP_MULTIPLY, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_DIV: {
- if (!_create_binary_operator(codegen, on, Variant::OP_DIVIDE, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_MOD: {
- if (!_create_binary_operator(codegen, on, Variant::OP_MODULE, p_stack_level)) return -1;
- } break;
- //case GDScriptParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break;
- //case GDScriptParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break;
- case GDScriptParser::OperatorNode::OP_BIT_AND: {
- if (!_create_binary_operator(codegen, on, Variant::OP_BIT_AND, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_BIT_OR: {
- if (!_create_binary_operator(codegen, on, Variant::OP_BIT_OR, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_BIT_XOR: {
- if (!_create_binary_operator(codegen, on, Variant::OP_BIT_XOR, p_stack_level)) return -1;
- } break;
- //shift
- case GDScriptParser::OperatorNode::OP_SHIFT_LEFT: {
- if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_LEFT, p_stack_level)) return -1;
- } break;
- case GDScriptParser::OperatorNode::OP_SHIFT_RIGHT: {
- if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_RIGHT, p_stack_level)) return -1;
- } break;
- //assignment operators
- case GDScriptParser::OperatorNode::OP_ASSIGN_ADD:
- case GDScriptParser::OperatorNode::OP_ASSIGN_SUB:
- case GDScriptParser::OperatorNode::OP_ASSIGN_MUL:
- case GDScriptParser::OperatorNode::OP_ASSIGN_DIV:
- case GDScriptParser::OperatorNode::OP_ASSIGN_MOD:
- case GDScriptParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT:
- case GDScriptParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT:
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_AND:
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_OR:
- case GDScriptParser::OperatorNode::OP_ASSIGN_BIT_XOR:
- case GDScriptParser::OperatorNode::OP_INIT_ASSIGN:
- case GDScriptParser::OperatorNode::OP_ASSIGN: {
-
- ERR_FAIL_COND_V(on->arguments.size() != 2, -1);
-
- if (on->arguments[0]->type == GDScriptParser::Node::TYPE_OPERATOR && (static_cast<GDScriptParser::OperatorNode *>(on->arguments[0])->op == GDScriptParser::OperatorNode::OP_INDEX || static_cast<GDScriptParser::OperatorNode *>(on->arguments[0])->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED)) {
-
- // SET (chained) MODE!
+ if (assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
+ // SET (chained) MODE!
+ const GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(assignment->assignee);
#ifdef DEBUG_ENABLED
- if (static_cast<GDScriptParser::OperatorNode *>(on->arguments[0])->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) {
- const GDScriptParser::OperatorNode *inon = static_cast<GDScriptParser::OperatorNode *>(on->arguments[0]);
-
- if (inon->arguments[0]->type == GDScriptParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) {
-
- const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDScriptParser::IdentifierNode *>(inon->arguments[1])->name);
- if (MI && MI->get().setter == codegen.function_node->name) {
- String n = static_cast<GDScriptParser::IdentifierNode *>(inon->arguments[1])->name;
- _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", inon);
- return -1;
+ if (subscript->is_attribute && subscript->base->type == GDScriptParser::Node::SELF && codegen.script) {
+ const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(subscript->attribute->name);
+ if (MI && MI->get().setter == codegen.function_name) {
+ String n = subscript->attribute->name;
+ _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", subscript);
+ r_error = ERR_COMPILATION_FAILED;
+ return GDScriptCodeGenerator::Address();
+ }
+ }
+#endif
+ /* Find chain of sets */
+
+ StringName assign_property;
+
+ List<const GDScriptParser::SubscriptNode *> chain;
+
+ {
+ // Create get/set chain.
+ const GDScriptParser::SubscriptNode *n = subscript;
+ while (true) {
+ chain.push_back(n);
+ if (n->base->type != GDScriptParser::Node::SUBSCRIPT) {
+ // Check for a built-in property.
+ if (n->base->type == GDScriptParser::Node::IDENTIFIER) {
+ GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(n->base);
+ if (_is_class_member_property(codegen, identifier->name)) {
+ assign_property = identifier->name;
}
}
+ break;
}
-#endif
-
- int slevel = p_stack_level;
-
- GDScriptParser::OperatorNode *op = static_cast<GDScriptParser::OperatorNode *>(on->arguments[0]);
-
- /* Find chain of sets */
+ n = static_cast<const GDScriptParser::SubscriptNode *>(n->base);
+ }
+ }
- StringName assign_property;
+ /* Chain of gets */
- List<GDScriptParser::OperatorNode *> chain;
+ // Get at (potential) root stack pos, so it can be returned.
+ GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, chain.back()->get()->base);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- {
- //create get/set chain
- GDScriptParser::OperatorNode *n = op;
- while (true) {
+ GDScriptCodeGenerator::Address prev_base = base;
- chain.push_back(n);
- if (n->arguments[0]->type != GDScriptParser::Node::TYPE_OPERATOR) {
+ struct ChainInfo {
+ bool is_named = false;
+ GDScriptCodeGenerator::Address base;
+ GDScriptCodeGenerator::Address key;
+ StringName name;
+ };
- //check for a built-in property
- if (n->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER) {
+ List<ChainInfo> set_chain;
- GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(n->arguments[0]);
- if (_is_class_member_property(codegen, identifier->name)) {
- assign_property = identifier->name;
- }
- }
- break;
- }
- n = static_cast<GDScriptParser::OperatorNode *>(n->arguments[0]);
- if (n->op != GDScriptParser::OperatorNode::OP_INDEX && n->op != GDScriptParser::OperatorNode::OP_INDEX_NAMED)
- break;
- }
+ for (List<const GDScriptParser::SubscriptNode *>::Element *E = chain.back(); E; E = E->prev()) {
+ if (E == chain.front()) {
+ // Skip the main subscript, since we'll assign to that.
+ break;
+ }
+ const GDScriptParser::SubscriptNode *subscript_elem = E->get();
+ GDScriptCodeGenerator::Address value = codegen.add_temporary(_gdtype_from_datatype(subscript_elem->get_datatype()));
+ GDScriptCodeGenerator::Address key;
+ StringName name;
+
+ if (subscript_elem->is_attribute) {
+ name = subscript_elem->attribute->name;
+ gen->write_get_named(value, name, prev_base);
+ } else {
+ key = _parse_expression(codegen, r_error, subscript_elem->index);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
}
+ gen->write_get(value, key, prev_base);
+ }
- /* Chain of gets */
+ // Store base and key for setting it back later.
+ set_chain.push_front({ subscript_elem->is_attribute, prev_base, key, name }); // Push to front to invert the list.
+ prev_base = value;
+ }
- //get at (potential) root stack pos, so it can be returned
- int prev_pos = _parse_expression(codegen, chain.back()->get()->arguments[0], slevel);
- if (prev_pos < 0)
- return prev_pos;
- int retval = prev_pos;
+ // Get value to assign.
+ GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ // Get the key if needed.
+ GDScriptCodeGenerator::Address key;
+ StringName name;
+ if (subscript->is_attribute) {
+ name = subscript->attribute->name;
+ } else {
+ key = _parse_expression(codegen, r_error, subscript->index);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ }
- if (retval & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
+ // Perform operator if any.
+ if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
+ GDScriptCodeGenerator::Address value = codegen.add_temporary();
+ if (subscript->is_attribute) {
+ gen->write_get_named(value, name, prev_base);
+ } else {
+ gen->write_get(value, key, prev_base);
+ }
+ gen->write_binary_operator(value, assignment->variant_op, value, assigned);
+ if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ assigned = value;
+ }
- Vector<int> setchain;
+ // Perform assignment.
+ if (subscript->is_attribute) {
+ gen->write_set_named(prev_base, name, assigned);
+ } else {
+ gen->write_set(prev_base, key, assigned);
+ }
+ if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
- if (assign_property != StringName()) {
+ assigned = prev_base;
- // recover and assign at the end, this allows stuff like
- // position.x+=2.0
- // in Node2D
- setchain.push_back(prev_pos);
- setchain.push_back(codegen.get_name_map_pos(assign_property));
- setchain.push_back(GDScriptFunction::OPCODE_SET_MEMBER);
+ // Set back the values into their bases.
+ for (List<ChainInfo>::Element *E = set_chain.front(); E; E = E->next()) {
+ const ChainInfo &info = E->get();
+ if (!info.is_named) {
+ gen->write_set(info.base, info.key, assigned);
+ if (info.key.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
}
+ } else {
+ gen->write_set_named(info.base, info.name, assigned);
+ }
+ if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ assigned = info.base;
+ }
- for (List<GDScriptParser::OperatorNode *>::Element *E = chain.back(); E; E = E->prev()) {
-
- if (E == chain.front()) //ignore first
- break;
-
- bool named = E->get()->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED;
- int key_idx;
+ // If this is a local member, also assign to it.
+ // This allow things like: position.x += 2.0
+ if (assign_property != StringName()) {
+ gen->write_set_member(assigned, assign_property);
+ }
- if (named) {
+ if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ } else if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name)) {
+ // Assignment to member property.
+ GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ GDScriptCodeGenerator::Address assign_temp = assigned;
- key_idx = codegen.get_name_map_pos(static_cast<const GDScriptParser::IdentifierNode *>(E->get()->arguments[1])->name);
- //printf("named key %x\n",key_idx);
+ StringName name = static_cast<GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
- } else {
-
- if (prev_pos & (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS)) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
+ if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
+ GDScriptCodeGenerator::Address member = codegen.add_temporary();
+ gen->write_get_member(member, name);
+ gen->write_binary_operator(assigned, assignment->variant_op, member, assigned);
+ gen->pop_temporary();
+ }
- GDScriptParser::Node *key = E->get()->arguments[1];
- key_idx = _parse_expression(codegen, key, slevel);
- //printf("expr key %x\n",key_idx);
+ gen->write_set_member(assigned, name);
- //stack was raised here if retval was stack but..
- }
+ if (assign_temp.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ } else {
+ // Regular assignment.
+ GDScriptCodeGenerator::Address target;
+
+ bool has_setter = false;
+ bool is_in_setter = false;
+ StringName setter_function;
+ if (assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
+ StringName var_name = static_cast<const GDScriptParser::IdentifierNode *>(assignment->assignee)->name;
+ if (!codegen.locals.has(var_name) && codegen.script->member_indices.has(var_name)) {
+ setter_function = codegen.script->member_indices[var_name].setter;
+ if (setter_function != StringName()) {
+ has_setter = true;
+ is_in_setter = setter_function == codegen.function_name;
+ target.mode = GDScriptCodeGenerator::Address::MEMBER;
+ target.address = codegen.script->member_indices[var_name].index;
+ }
+ }
+ }
- if (key_idx < 0) //error
- return key_idx;
+ if (has_setter) {
+ if (!is_in_setter) {
+ // Store stack slot for the temp value.
+ target = codegen.add_temporary(_gdtype_from_datatype(assignment->assignee->get_datatype()));
+ }
+ } else {
+ target = _parse_expression(codegen, r_error, assignment->assignee);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
+ }
- codegen.opcodes.push_back(named ? GDScriptFunction::OPCODE_GET_NAMED : GDScriptFunction::OPCODE_GET);
- codegen.opcodes.push_back(prev_pos);
- codegen.opcodes.push_back(key_idx);
- slevel++;
- codegen.alloc_stack(slevel);
- int dst_pos = (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) | slevel;
+ GDScriptCodeGenerator::Address assigned = _parse_expression(codegen, r_error, assignment->assigned_value);
+ GDScriptCodeGenerator::Address op_result;
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- codegen.opcodes.push_back(dst_pos);
+ if (assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
+ // Perform operation.
+ op_result = codegen.add_temporary();
+ gen->write_binary_operator(op_result, assignment->variant_op, target, assigned);
+ } else {
+ op_result = assigned;
+ assigned = GDScriptCodeGenerator::Address();
+ }
- //add in reverse order, since it will be reverted
+ GDScriptDataType assign_type = _gdtype_from_datatype(assignment->assignee->get_datatype());
- setchain.push_back(dst_pos);
- setchain.push_back(key_idx);
- setchain.push_back(prev_pos);
- setchain.push_back(named ? GDScriptFunction::OPCODE_SET_NAMED : GDScriptFunction::OPCODE_SET);
+ if (has_setter && !is_in_setter) {
+ // Call setter.
+ Vector<GDScriptCodeGenerator::Address> args;
+ args.push_back(op_result);
+ gen->write_call(GDScriptCodeGenerator::Address(), GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), setter_function, args);
+ } else {
+ // Just assign.
+ gen->write_assign(target, op_result);
+ }
- prev_pos = dst_pos;
- }
+ if (op_result.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ if (target.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ gen->pop_temporary();
+ }
+ }
+ return GDScriptCodeGenerator::Address(); // Assignment does not return a value.
+ } break;
+ default: {
+ ERR_FAIL_V_MSG(GDScriptCodeGenerator::Address(), "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); // Unreachable code.
+ } break;
+ }
+}
- setchain.invert();
+GDScriptCodeGenerator::Address GDScriptCompiler::_parse_match_pattern(CodeGen &codegen, Error &r_error, const GDScriptParser::PatternNode *p_pattern, const GDScriptCodeGenerator::Address &p_value_addr, const GDScriptCodeGenerator::Address &p_type_addr, const GDScriptCodeGenerator::Address &p_previous_test, bool p_is_first, bool p_is_nested) {
+ switch (p_pattern->pattern_type) {
+ case GDScriptParser::PatternNode::PT_LITERAL: {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
+ }
- int set_index;
- bool named = false;
+ // Get literal type into constant map.
+ GDScriptCodeGenerator::Address literal_type_addr = codegen.add_constant((int)p_pattern->literal->value.get_type());
- if (op->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) {
+ // Equality is always a boolean.
+ GDScriptDataType equality_type;
+ equality_type.has_type = true;
+ equality_type.kind = GDScriptDataType::BUILTIN;
+ equality_type.builtin_type = Variant::BOOL;
- set_index = codegen.get_name_map_pos(static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name);
- named = true;
- } else {
+ // Check type equality.
+ GDScriptCodeGenerator::Address type_equality_addr = codegen.add_temporary(equality_type);
+ codegen.generator->write_binary_operator(type_equality_addr, Variant::OP_EQUAL, p_type_addr, literal_type_addr);
+ codegen.generator->write_and_left_operand(type_equality_addr);
- set_index = _parse_expression(codegen, op->arguments[1], slevel + 1);
- named = false;
- }
-
- if (set_index < 0) //error
- return set_index;
+ // Get literal.
+ GDScriptCodeGenerator::Address literal_addr = _parse_expression(codegen, r_error, p_pattern->literal);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- if (set_index & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
+ // Check value equality.
+ GDScriptCodeGenerator::Address equality_addr = codegen.add_temporary(equality_type);
+ codegen.generator->write_binary_operator(equality_addr, Variant::OP_EQUAL, p_value_addr, literal_addr);
+ codegen.generator->write_and_right_operand(equality_addr);
- int set_value = _parse_assign_right_expression(codegen, on, slevel + 1, named ? 0 : set_index);
- if (set_value < 0) //error
- return set_value;
+ // AND both together (reuse temporary location).
+ codegen.generator->write_end_and(type_equality_addr);
- codegen.opcodes.push_back(named ? GDScriptFunction::OPCODE_SET_NAMED : GDScriptFunction::OPCODE_SET);
- codegen.opcodes.push_back(prev_pos);
- codegen.opcodes.push_back(set_index);
- codegen.opcodes.push_back(set_value);
+ codegen.generator->pop_temporary(); // Remove equality_addr from stack.
- for (int i = 0; i < setchain.size(); i++) {
+ if (literal_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
- codegen.opcodes.push_back(setchain[i]);
- }
+ // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
+ if (p_is_nested) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_and_right_operand(type_equality_addr);
+ codegen.generator->write_end_and(p_previous_test);
+ } else if (!p_is_first) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_or_right_operand(type_equality_addr);
+ codegen.generator->write_end_or(p_previous_test);
+ } else {
+ // Just assign this value to the accumulator temporary.
+ codegen.generator->write_assign(p_previous_test, type_equality_addr);
+ }
+ codegen.generator->pop_temporary(); // Remove type_equality_addr.
- return retval;
+ return p_previous_test;
+ } break;
+ case GDScriptParser::PatternNode::PT_EXPRESSION: {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
+ }
+ // Create the result temps first since it's the last to go away.
+ GDScriptCodeGenerator::Address result_addr = codegen.add_temporary();
+ GDScriptCodeGenerator::Address equality_test_addr = codegen.add_temporary();
+
+ // Evaluate expression.
+ GDScriptCodeGenerator::Address expr_addr;
+ expr_addr = _parse_expression(codegen, r_error, p_pattern->expression);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- } else if (on->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER && _is_class_member_property(codegen, static_cast<GDScriptParser::IdentifierNode *>(on->arguments[0])->name)) {
- //assignment to member property
+ // Evaluate expression type.
+ Vector<GDScriptCodeGenerator::Address> typeof_args;
+ typeof_args.push_back(expr_addr);
+ codegen.generator->write_call_utility(result_addr, "typeof", typeof_args);
- int slevel = p_stack_level;
+ // Check type equality.
+ codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, result_addr);
+ codegen.generator->write_and_left_operand(result_addr);
- int src_address = _parse_assign_right_expression(codegen, on, slevel);
- if (src_address < 0)
- return -1;
+ // Check value equality.
+ codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_value_addr, expr_addr);
+ codegen.generator->write_and_right_operand(equality_test_addr);
- StringName name = static_cast<GDScriptParser::IdentifierNode *>(on->arguments[0])->name;
+ // AND both type and value equality.
+ codegen.generator->write_end_and(result_addr);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_SET_MEMBER);
- codegen.opcodes.push_back(codegen.get_name_map_pos(name));
- codegen.opcodes.push_back(src_address);
+ // We don't need the expression temporary anymore.
+ if (expr_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ codegen.generator->pop_temporary(); // Remove type equality temporary.
+
+ // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
+ if (p_is_nested) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_and_right_operand(result_addr);
+ codegen.generator->write_end_and(p_previous_test);
+ } else if (!p_is_first) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_or_right_operand(result_addr);
+ codegen.generator->write_end_or(p_previous_test);
+ } else {
+ // Just assign this value to the accumulator temporary.
+ codegen.generator->write_assign(p_previous_test, result_addr);
+ }
+ codegen.generator->pop_temporary(); // Remove temp result addr.
- return GDScriptFunction::ADDR_TYPE_NIL << GDScriptFunction::ADDR_BITS;
- } else {
+ return p_previous_test;
+ } break;
+ case GDScriptParser::PatternNode::PT_ARRAY: {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
+ }
+ // Get array type into constant map.
+ GDScriptCodeGenerator::Address array_type_addr = codegen.add_constant((int)Variant::ARRAY);
+
+ // Equality is always a boolean.
+ GDScriptDataType temp_type;
+ temp_type.has_type = true;
+ temp_type.kind = GDScriptDataType::BUILTIN;
+ temp_type.builtin_type = Variant::BOOL;
+
+ // Check type equality.
+ GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);
+ codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, array_type_addr);
+ codegen.generator->write_and_left_operand(result_addr);
+
+ // Store pattern length in constant map.
+ GDScriptCodeGenerator::Address array_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->array.size() - 1 : p_pattern->array.size());
+
+ // Get value length.
+ temp_type.builtin_type = Variant::INT;
+ GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);
+ Vector<GDScriptCodeGenerator::Address> len_args;
+ len_args.push_back(p_value_addr);
+ codegen.generator->write_call_gdscript_utility(value_length_addr, GDScriptUtilityFunctions::get_function("len"), len_args);
+
+ // Test length compatibility.
+ temp_type.builtin_type = Variant::BOOL;
+ GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);
+ codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, array_length_addr);
+ codegen.generator->write_and_right_operand(length_compat_addr);
+
+ // AND type and length check.
+ codegen.generator->write_end_and(result_addr);
+
+ // Remove length temporaries.
+ codegen.generator->pop_temporary();
+ codegen.generator->pop_temporary();
+
+ // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
+ if (p_is_nested) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_and_right_operand(result_addr);
+ codegen.generator->write_end_and(p_previous_test);
+ } else if (!p_is_first) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_or_right_operand(result_addr);
+ codegen.generator->write_end_or(p_previous_test);
+ } else {
+ // Just assign this value to the accumulator temporary.
+ codegen.generator->write_assign(p_previous_test, result_addr);
+ }
+ codegen.generator->pop_temporary(); // Remove temp result addr.
+
+ // Create temporaries outside the loop so they can be reused.
+ GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();
+ GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();
+ GDScriptCodeGenerator::Address test_addr = p_previous_test;
+
+ // Evaluate element by element.
+ for (int i = 0; i < p_pattern->array.size(); i++) {
+ if (p_pattern->array[i]->pattern_type == GDScriptParser::PatternNode::PT_REST) {
+ // Don't want to access an extra element of the user array.
+ break;
+ }
- //REGULAR ASSIGNMENT MODE!!
+ // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
+ codegen.generator->write_and_left_operand(test_addr);
- int slevel = p_stack_level;
+ // Add index to constant map.
+ GDScriptCodeGenerator::Address index_addr = codegen.add_constant(i);
- int dst_address_a = _parse_expression(codegen, on->arguments[0], slevel, false, on->op == GDScriptParser::OperatorNode::OP_INIT_ASSIGN);
- if (dst_address_a < 0)
- return -1;
+ // Get the actual element from the user-sent array.
+ codegen.generator->write_get(element_addr, index_addr, p_value_addr);
- if (dst_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) {
- slevel++;
- codegen.alloc_stack(slevel);
- }
+ // Also get type of element.
+ Vector<GDScriptCodeGenerator::Address> typeof_args;
+ typeof_args.push_back(element_addr);
+ codegen.generator->write_call_utility(element_type_addr, "typeof", typeof_args);
- int src_address_b = _parse_assign_right_expression(codegen, on, slevel);
- if (src_address_b < 0)
- return -1;
-
- GDScriptDataType assign_type = _gdtype_from_datatype(on->arguments[0]->get_datatype());
-
- if (assign_type.has_type && !on->datatype.has_type) {
- // Typed assignment
- switch (assign_type.kind) {
- case GDScriptDataType::BUILTIN: {
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN); // perform operator
- codegen.opcodes.push_back(assign_type.builtin_type); // variable type
- codegen.opcodes.push_back(dst_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2
- } break;
- case GDScriptDataType::NATIVE: {
- int class_idx;
- if (GDScriptLanguage::get_singleton()->get_global_map().has(assign_type.native_type)) {
-
- class_idx = GDScriptLanguage::get_singleton()->get_global_map()[assign_type.native_type];
- class_idx |= (GDScriptFunction::ADDR_TYPE_GLOBAL << GDScriptFunction::ADDR_BITS); //argument (stack root)
- } else {
- _set_error("Invalid native class type '" + String(assign_type.native_type) + "'.", on->arguments[0]);
- return -1;
- }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE); // perform operator
- codegen.opcodes.push_back(class_idx); // variable type
- codegen.opcodes.push_back(dst_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2
- } break;
- case GDScriptDataType::SCRIPT:
- case GDScriptDataType::GDSCRIPT: {
-
- Variant script = assign_type.script_type;
- int idx = codegen.get_constant_pos(script);
- idx |= GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT << GDScriptFunction::ADDR_BITS; //make it a local constant (faster access)
-
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT); // perform operator
- codegen.opcodes.push_back(idx); // variable type
- codegen.opcodes.push_back(dst_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2
- } break;
- default: {
- ERR_PRINT("Compiler bug: unresolved assign.");
-
- // Shouldn't get here, but fail-safe to a regular assignment
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator
- codegen.opcodes.push_back(dst_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
- }
- }
- } else {
- // Either untyped assignment or already type-checked by the parser
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN); // perform operator
- codegen.opcodes.push_back(dst_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
- }
- return dst_address_a; //if anything, returns wathever was assigned or correct stack position
- }
- } break;
- case GDScriptParser::OperatorNode::OP_IS: {
-
- ERR_FAIL_COND_V(on->arguments.size() != 2, false);
+ // Try the pattern inside the element.
+ test_addr = _parse_match_pattern(codegen, r_error, p_pattern->array[i], element_addr, element_type_addr, p_previous_test, false, true);
+ if (r_error != OK) {
+ return GDScriptCodeGenerator::Address();
+ }
- int slevel = p_stack_level;
+ codegen.generator->write_and_right_operand(test_addr);
+ codegen.generator->write_end_and(test_addr);
+ }
+ // Remove element temporaries.
+ codegen.generator->pop_temporary();
+ codegen.generator->pop_temporary();
- int src_address_a = _parse_expression(codegen, on->arguments[0], slevel);
- if (src_address_a < 0)
- return -1;
+ return test_addr;
+ } break;
+ case GDScriptParser::PatternNode::PT_DICTIONARY: {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
+ }
+ // Get dictionary type into constant map.
+ GDScriptCodeGenerator::Address dict_type_addr = codegen.add_constant((int)Variant::DICTIONARY);
+
+ // Equality is always a boolean.
+ GDScriptDataType temp_type;
+ temp_type.has_type = true;
+ temp_type.kind = GDScriptDataType::BUILTIN;
+ temp_type.builtin_type = Variant::BOOL;
+
+ // Check type equality.
+ GDScriptCodeGenerator::Address result_addr = codegen.add_temporary(temp_type);
+ codegen.generator->write_binary_operator(result_addr, Variant::OP_EQUAL, p_type_addr, dict_type_addr);
+ codegen.generator->write_and_left_operand(result_addr);
+
+ // Store pattern length in constant map.
+ GDScriptCodeGenerator::Address dict_length_addr = codegen.add_constant(p_pattern->rest_used ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());
+
+ // Get user's dictionary length.
+ temp_type.builtin_type = Variant::INT;
+ GDScriptCodeGenerator::Address value_length_addr = codegen.add_temporary(temp_type);
+ Vector<GDScriptCodeGenerator::Address> func_args;
+ func_args.push_back(p_value_addr);
+ codegen.generator->write_call_gdscript_utility(value_length_addr, GDScriptUtilityFunctions::get_function("len"), func_args);
+
+ // Test length compatibility.
+ temp_type.builtin_type = Variant::BOOL;
+ GDScriptCodeGenerator::Address length_compat_addr = codegen.add_temporary(temp_type);
+ codegen.generator->write_binary_operator(length_compat_addr, p_pattern->rest_used ? Variant::OP_GREATER_EQUAL : Variant::OP_EQUAL, value_length_addr, dict_length_addr);
+ codegen.generator->write_and_right_operand(length_compat_addr);
+
+ // AND type and length check.
+ codegen.generator->write_end_and(result_addr);
+
+ // Remove length temporaries.
+ codegen.generator->pop_temporary();
+ codegen.generator->pop_temporary();
+
+ // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
+ if (p_is_nested) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_and_right_operand(result_addr);
+ codegen.generator->write_end_and(p_previous_test);
+ } else if (!p_is_first) {
+ // Use the previous value as target, since we only need one temporary variable.
+ codegen.generator->write_or_right_operand(result_addr);
+ codegen.generator->write_end_or(p_previous_test);
+ } else {
+ // Just assign this value to the accumulator temporary.
+ codegen.generator->write_assign(p_previous_test, result_addr);
+ }
+ codegen.generator->pop_temporary(); // Remove temp result addr.
+
+ // Create temporaries outside the loop so they can be reused.
+ temp_type.builtin_type = Variant::BOOL;
+ GDScriptCodeGenerator::Address test_result = codegen.add_temporary(temp_type);
+ GDScriptCodeGenerator::Address element_addr = codegen.add_temporary();
+ GDScriptCodeGenerator::Address element_type_addr = codegen.add_temporary();
+ GDScriptCodeGenerator::Address test_addr = p_previous_test;
+
+ // Evaluate element by element.
+ for (int i = 0; i < p_pattern->dictionary.size(); i++) {
+ const GDScriptParser::PatternNode::Pair &element = p_pattern->dictionary[i];
+ if (element.value_pattern && element.value_pattern->pattern_type == GDScriptParser::PatternNode::PT_REST) {
+ // Ignore rest pattern.
+ break;
+ }
- if (src_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS)
- slevel++; //uses stack for return, increase stack
+ // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
+ codegen.generator->write_and_left_operand(test_addr);
- int src_address_b = _parse_expression(codegen, on->arguments[1], slevel);
- if (src_address_b < 0)
- return -1;
+ // Get the pattern key.
+ GDScriptCodeGenerator::Address pattern_key_addr = _parse_expression(codegen, r_error, element.key);
+ if (r_error) {
+ return GDScriptCodeGenerator::Address();
+ }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_EXTENDS_TEST); // perform operator
- codegen.opcodes.push_back(src_address_a); // argument 1
- codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter)
+ // Check if pattern key exists in user's dictionary. This will be AND-ed with next result.
+ func_args.clear();
+ func_args.push_back(pattern_key_addr);
+ codegen.generator->write_call(test_result, p_value_addr, "has", func_args);
- } break;
- case GDScriptParser::OperatorNode::OP_IS_BUILTIN: {
- ERR_FAIL_COND_V(on->arguments.size() != 2, false);
- ERR_FAIL_COND_V(on->arguments[1]->type != GDScriptParser::Node::TYPE_TYPE, false);
+ if (element.value_pattern != nullptr) {
+ // Use AND here too, as we don't want to be checking elements if previous test failed (which means this might be an invalid get).
+ codegen.generator->write_and_left_operand(test_result);
- int slevel = p_stack_level;
+ // Get actual value from user dictionary.
+ codegen.generator->write_get(element_addr, pattern_key_addr, p_value_addr);
- int src_address_a = _parse_expression(codegen, on->arguments[0], slevel);
- if (src_address_a < 0)
- return -1;
+ // Also get type of value.
+ func_args.clear();
+ func_args.push_back(element_addr);
+ codegen.generator->write_call_utility(element_type_addr, "typeof", func_args);
- if (src_address_a & GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS)
- slevel++; //uses stack for return, increase stack
+ // Try the pattern inside the value.
+ test_addr = _parse_match_pattern(codegen, r_error, element.value_pattern, element_addr, element_type_addr, test_addr, false, true);
+ if (r_error != OK) {
+ return GDScriptCodeGenerator::Address();
+ }
+ codegen.generator->write_and_right_operand(test_addr);
+ codegen.generator->write_end_and(test_addr);
+ }
- const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(on->arguments[1]);
+ codegen.generator->write_and_right_operand(test_addr);
+ codegen.generator->write_end_and(test_addr);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_IS_BUILTIN); // perform operator
- codegen.opcodes.push_back(src_address_a); // argument 1
- codegen.opcodes.push_back((int)tn->vtype); // argument 2 (unary only takes one parameter)
- } break;
- default: {
+ // Remove pattern key temporary.
+ if (pattern_key_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ }
- ERR_FAIL_V_MSG(0, "Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression."); //unreachable code
+ // Remove element temporaries.
+ codegen.generator->pop_temporary();
+ codegen.generator->pop_temporary();
+ codegen.generator->pop_temporary();
- } break;
+ return test_addr;
+ } break;
+ case GDScriptParser::PatternNode::PT_REST:
+ // Do nothing.
+ return p_previous_test;
+ break;
+ case GDScriptParser::PatternNode::PT_BIND: {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
}
+ // Get the bind address.
+ GDScriptCodeGenerator::Address bind = codegen.locals[p_pattern->bind->name];
- int dst_addr = (p_stack_level) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode
- codegen.alloc_stack(p_stack_level);
- return dst_addr;
- } break;
- //TYPE_TYPE,
- default: {
+ // Assign value to bound variable.
+ codegen.generator->write_assign(bind, p_value_addr);
+ }
+ [[fallthrough]]; // Act like matching anything too.
+ case GDScriptParser::PatternNode::PT_WILDCARD:
+ // If this is a fall through we don't want to do this again.
+ if (p_pattern->pattern_type != GDScriptParser::PatternNode::PT_BIND) {
+ if (p_is_nested) {
+ codegen.generator->write_and_left_operand(p_previous_test);
+ } else if (!p_is_first) {
+ codegen.generator->write_or_left_operand(p_previous_test);
+ }
+ }
+ // This matches anything so just do the same as `if(true)`.
+ // If this isn't the first, we need to OR with the previous pattern. If it's nested, we use AND instead.
+ if (p_is_nested) {
+ // Use the operator with the `true` constant so it works as always matching.
+ GDScriptCodeGenerator::Address constant = codegen.add_constant(true);
+ codegen.generator->write_and_right_operand(constant);
+ codegen.generator->write_end_and(p_previous_test);
+ } else if (!p_is_first) {
+ // Use the operator with the `true` constant so it works as always matching.
+ GDScriptCodeGenerator::Address constant = codegen.add_constant(true);
+ codegen.generator->write_or_right_operand(constant);
+ codegen.generator->write_end_or(p_previous_test);
+ } else {
+ // Just assign this value to the accumulator temporary.
+ codegen.generator->write_assign_true(p_previous_test);
+ }
+ return p_previous_test;
+ }
+ ERR_FAIL_V_MSG(p_previous_test, "Reaching the end of pattern compilation without matching a pattern.");
+}
- ERR_FAIL_V_MSG(-1, "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); //unreachable code
- } break;
+void GDScriptCompiler::_add_locals_in_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block) {
+ for (int i = 0; i < p_block->locals.size(); i++) {
+ if (p_block->locals[i].type == GDScriptParser::SuiteNode::Local::PARAMETER || p_block->locals[i].type == GDScriptParser::SuiteNode::Local::FOR_VARIABLE) {
+ // Parameters are added directly from function and loop variables are declared explicitly.
+ continue;
+ }
+ codegen.add_local(p_block->locals[i].name, _gdtype_from_datatype(p_block->locals[i].get_datatype()));
}
}
-Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) {
+Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals) {
+ Error error = OK;
+ GDScriptCodeGenerator *gen = codegen.generator;
- codegen.push_stack_identifiers();
- int new_identifiers = 0;
- codegen.current_line = p_block->line;
+ codegen.start_block();
- for (int i = 0; i < p_block->statements.size(); i++) {
+ if (p_add_locals) {
+ _add_locals_in_block(codegen, p_block);
+ }
+ for (int i = 0; i < p_block->statements.size(); i++) {
const GDScriptParser::Node *s = p_block->statements[i];
- switch (s->type) {
- case GDScriptParser::Node::TYPE_NEWLINE: {
#ifdef DEBUG_ENABLED
- const GDScriptParser::NewLineNode *nl = static_cast<const GDScriptParser::NewLineNode *>(s);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_LINE);
- codegen.opcodes.push_back(nl->line);
- codegen.current_line = nl->line;
+ // Add a newline before each statement, since the debugger needs those.
+ gen->write_newline(s->start_line);
#endif
- } break;
- case GDScriptParser::Node::TYPE_CONTROL_FLOW: {
- // try subblocks
- const GDScriptParser::ControlFlowNode *cf = static_cast<const GDScriptParser::ControlFlowNode *>(s);
-
- switch (cf->cf_type) {
+ switch (s->type) {
+ case GDScriptParser::Node::MATCH: {
+ const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(s);
- case GDScriptParser::ControlFlowNode::CF_MATCH: {
- GDScriptParser::MatchNode *match = cf->match;
+ gen->start_match();
+ codegen.start_block();
- GDScriptParser::IdentifierNode *id = memnew(GDScriptParser::IdentifierNode);
- id->name = "#match_value";
+ // Evaluate the match expression.
+ GDScriptCodeGenerator::Address value_local = codegen.add_local("@match_value", _gdtype_from_datatype(match->test->get_datatype()));
+ GDScriptCodeGenerator::Address value = _parse_expression(codegen, error, match->test);
+ if (error) {
+ return error;
+ }
- // var #match_value
- // copied because there is no _parse_statement :(
- codegen.add_stack_identifier(id->name, p_stack_level++);
- codegen.alloc_stack(p_stack_level);
- new_identifiers++;
+ // Assign to local.
+ // TODO: This can be improved by passing the target to parse_expression().
+ gen->write_assign(value_local, value);
- GDScriptParser::OperatorNode *op = memnew(GDScriptParser::OperatorNode);
- op->op = GDScriptParser::OperatorNode::OP_ASSIGN;
- op->arguments.push_back(id);
- op->arguments.push_back(match->val_to_match);
+ if (value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
- int ret = _parse_expression(codegen, op, p_stack_level);
- if (ret < 0) {
- memdelete(id);
- memdelete(op);
- return ERR_PARSE_ERROR;
- }
+ // Then, let's save the type of the value in the stack too, so we can reuse for later comparisons.
+ GDScriptDataType typeof_type;
+ typeof_type.has_type = true;
+ typeof_type.kind = GDScriptDataType::BUILTIN;
+ typeof_type.builtin_type = Variant::INT;
+ GDScriptCodeGenerator::Address type = codegen.add_local("@match_type", typeof_type);
+
+ Vector<GDScriptCodeGenerator::Address> typeof_args;
+ typeof_args.push_back(value);
+ gen->write_call_utility(type, "typeof", typeof_args);
+
+ // Now we can actually start testing.
+ // For each branch.
+ for (int j = 0; j < match->branches.size(); j++) {
+ if (j > 0) {
+ // Use `else` to not check the next branch after matching.
+ gen->write_else();
+ }
- // break address
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size() + 3);
- int break_addr = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(0); // break addr
-
- for (int j = 0; j < match->compiled_pattern_branches.size(); j++) {
- GDScriptParser::MatchNode::CompiledPatternBranch branch = match->compiled_pattern_branches[j];
-
- // jump over continue
- // jump unconditionally
- // continue address
- // compile the condition
- int ret2 = _parse_expression(codegen, branch.compiled_pattern, p_stack_level);
- if (ret2 < 0) {
- memdelete(id);
- memdelete(op);
- return ERR_PARSE_ERROR;
- }
+ const GDScriptParser::MatchBranchNode *branch = match->branches[j];
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF);
- codegen.opcodes.push_back(ret2);
- codegen.opcodes.push_back(codegen.opcodes.size() + 3);
- int continue_addr = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(0);
-
- Error err = _parse_block(codegen, branch.body, p_stack_level, p_break_addr, continue_addr);
- if (err) {
- memdelete(id);
- memdelete(op);
- return ERR_PARSE_ERROR;
- }
+ gen->start_match_branch(); // Need so lower level code can patch 'continue' jumps.
+ codegen.start_block(); // Create an extra block around for binds.
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(break_addr);
+ // Add locals in block before patterns, so temporaries don't use the stack address for binds.
+ _add_locals_in_block(codegen, branch->block);
- codegen.opcodes.write[continue_addr + 1] = codegen.opcodes.size();
+#ifdef DEBUG_ENABLED
+ // Add a newline before each branch, since the debugger needs those.
+ gen->write_newline(branch->start_line);
+#endif
+ // For each pattern in branch.
+ GDScriptCodeGenerator::Address pattern_result = codegen.add_temporary();
+ for (int k = 0; k < branch->patterns.size(); k++) {
+ pattern_result = _parse_match_pattern(codegen, error, branch->patterns[k], value, type, pattern_result, k == 0, false);
+ if (error != OK) {
+ return error;
}
+ }
- codegen.opcodes.write[break_addr + 1] = codegen.opcodes.size();
-
- memdelete(id);
- memdelete(op);
-
- } break;
-
- case GDScriptParser::ControlFlowNode::CF_IF: {
+ // Check if pattern did match.
+ gen->write_if(pattern_result);
- int ret2 = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
- if (ret2 < 0)
- return ERR_PARSE_ERROR;
+ // Remove the result from stack.
+ gen->pop_temporary();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
- codegen.opcodes.push_back(ret2);
- int else_addr = codegen.opcodes.size();
- codegen.opcodes.push_back(0); //temporary
+ // Parse the branch block.
+ error = _parse_block(codegen, branch->block, false); // Don't add locals again.
+ if (error) {
+ return error;
+ }
- Error err = _parse_block(codegen, cf->body, p_stack_level, p_break_addr, p_continue_addr);
- if (err)
- return err;
+ codegen.end_block(); // Get out of extra block.
+ }
- if (cf->body_else) {
+ // End all nested `if`s.
+ for (int j = 0; j < match->branches.size(); j++) {
+ gen->write_endif();
+ }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- int end_addr = codegen.opcodes.size();
- codegen.opcodes.push_back(0);
- codegen.opcodes.write[else_addr] = codegen.opcodes.size();
+ gen->end_match();
+ } break;
+ case GDScriptParser::Node::IF: {
+ const GDScriptParser::IfNode *if_n = static_cast<const GDScriptParser::IfNode *>(s);
+ GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, if_n->condition);
+ if (error) {
+ return error;
+ }
- Error err2 = _parse_block(codegen, cf->body_else, p_stack_level, p_break_addr, p_continue_addr);
- if (err2)
- return err2;
+ gen->write_if(condition);
- codegen.opcodes.write[end_addr] = codegen.opcodes.size();
- } else {
- //end without else
- codegen.opcodes.write[else_addr] = codegen.opcodes.size();
- }
+ if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
- } break;
- case GDScriptParser::ControlFlowNode::CF_FOR: {
-
- int slevel = p_stack_level;
- int iter_stack_pos = slevel;
- int iterator_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- int counter_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- int container_pos = (slevel++) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
- codegen.alloc_stack(slevel);
-
- codegen.push_stack_identifiers();
- codegen.add_stack_identifier(static_cast<const GDScriptParser::IdentifierNode *>(cf->arguments[0])->name, iter_stack_pos);
-
- int ret2 = _parse_expression(codegen, cf->arguments[1], slevel, false);
- if (ret2 < 0)
- return ERR_COMPILATION_FAILED;
-
- //assign container
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSIGN);
- codegen.opcodes.push_back(container_pos);
- codegen.opcodes.push_back(ret2);
-
- //begin loop
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ITERATE_BEGIN);
- codegen.opcodes.push_back(counter_pos);
- codegen.opcodes.push_back(container_pos);
- codegen.opcodes.push_back(codegen.opcodes.size() + 4);
- codegen.opcodes.push_back(iterator_pos);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP); //skip code for next
- codegen.opcodes.push_back(codegen.opcodes.size() + 8);
- //break loop
- int break_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP); //skip code for next
- codegen.opcodes.push_back(0); //skip code for next
- //next loop
- int continue_pos = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ITERATE);
- codegen.opcodes.push_back(counter_pos);
- codegen.opcodes.push_back(container_pos);
- codegen.opcodes.push_back(break_pos);
- codegen.opcodes.push_back(iterator_pos);
-
- Error err = _parse_block(codegen, cf->body, slevel, break_pos, continue_pos);
- if (err)
- return err;
+ error = _parse_block(codegen, if_n->true_block);
+ if (error) {
+ return error;
+ }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(continue_pos);
- codegen.opcodes.write[break_pos + 1] = codegen.opcodes.size();
+ if (if_n->false_block) {
+ gen->write_else();
- codegen.pop_stack_identifiers();
+ error = _parse_block(codegen, if_n->false_block);
+ if (error) {
+ return error;
+ }
+ }
- } break;
- case GDScriptParser::ControlFlowNode::CF_WHILE: {
+ gen->write_endif();
+ } break;
+ case GDScriptParser::Node::FOR: {
+ const GDScriptParser::ForNode *for_n = static_cast<const GDScriptParser::ForNode *>(s);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size() + 3);
- int break_addr = codegen.opcodes.size();
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(0);
- int continue_addr = codegen.opcodes.size();
+ codegen.start_block();
+ GDScriptCodeGenerator::Address iterator = codegen.add_local(for_n->variable->name, _gdtype_from_datatype(for_n->variable->get_datatype()));
- int ret2 = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
- if (ret2 < 0)
- return ERR_PARSE_ERROR;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_IF_NOT);
- codegen.opcodes.push_back(ret2);
- codegen.opcodes.push_back(break_addr);
- Error err = _parse_block(codegen, cf->body, p_stack_level, break_addr, continue_addr);
- if (err)
- return err;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(continue_addr);
+ gen->start_for(iterator.type, _gdtype_from_datatype(for_n->list->get_datatype()));
- codegen.opcodes.write[break_addr + 1] = codegen.opcodes.size();
+ GDScriptCodeGenerator::Address list = _parse_expression(codegen, error, for_n->list);
+ if (error) {
+ return error;
+ }
- } break;
- case GDScriptParser::ControlFlowNode::CF_BREAK: {
+ gen->write_for_assignment(iterator, list);
- if (p_break_addr < 0) {
+ if (list.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
- _set_error("'break'' not within loop", cf);
- return ERR_COMPILATION_FAILED;
- }
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(p_break_addr);
+ gen->write_for();
- } break;
- case GDScriptParser::ControlFlowNode::CF_CONTINUE: {
+ error = _parse_block(codegen, for_n->loop);
+ if (error) {
+ return error;
+ }
- if (p_continue_addr < 0) {
+ gen->write_endfor();
- _set_error("'continue' not within loop", cf);
- return ERR_COMPILATION_FAILED;
- }
+ codegen.end_block();
+ } break;
+ case GDScriptParser::Node::WHILE: {
+ const GDScriptParser::WhileNode *while_n = static_cast<const GDScriptParser::WhileNode *>(s);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(p_continue_addr);
+ gen->start_while_condition();
- } break;
- case GDScriptParser::ControlFlowNode::CF_RETURN: {
+ GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, while_n->condition);
+ if (error) {
+ return error;
+ }
- int ret2;
+ gen->write_while(condition);
- if (cf->arguments.size()) {
+ if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
- ret2 = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
- if (ret2 < 0)
- return ERR_PARSE_ERROR;
+ error = _parse_block(codegen, while_n->loop);
+ if (error) {
+ return error;
+ }
- } else {
+ gen->write_endwhile();
+ } break;
+ case GDScriptParser::Node::BREAK: {
+ gen->write_break();
+ } break;
+ case GDScriptParser::Node::CONTINUE: {
+ const GDScriptParser::ContinueNode *cont = static_cast<const GDScriptParser::ContinueNode *>(s);
+ if (cont->is_for_match) {
+ gen->write_continue_match();
+ } else {
+ gen->write_continue();
+ }
+ } break;
+ case GDScriptParser::Node::RETURN: {
+ const GDScriptParser::ReturnNode *return_n = static_cast<const GDScriptParser::ReturnNode *>(s);
- ret2 = GDScriptFunction::ADDR_TYPE_NIL << GDScriptFunction::ADDR_BITS;
- }
+ GDScriptCodeGenerator::Address return_value;
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_RETURN);
- codegen.opcodes.push_back(ret2);
+ if (return_n->return_value != nullptr) {
+ return_value = _parse_expression(codegen, error, return_n->return_value);
+ if (error) {
+ return error;
+ }
+ }
- } break;
+ gen->write_return(return_value);
+ if (return_value.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
}
} break;
- case GDScriptParser::Node::TYPE_ASSERT: {
+ case GDScriptParser::Node::ASSERT: {
#ifdef DEBUG_ENABLED
- // try subblocks
-
const GDScriptParser::AssertNode *as = static_cast<const GDScriptParser::AssertNode *>(s);
- int ret2 = _parse_expression(codegen, as->condition, p_stack_level, false);
- if (ret2 < 0)
- return ERR_PARSE_ERROR;
+ GDScriptCodeGenerator::Address condition = _parse_expression(codegen, error, as->condition);
+ if (error) {
+ return error;
+ }
+
+ GDScriptCodeGenerator::Address message;
- int message_ret = 0;
if (as->message) {
- message_ret = _parse_expression(codegen, as->message, p_stack_level + 1, false);
- if (message_ret < 0)
- return ERR_PARSE_ERROR;
+ message = _parse_expression(codegen, error, as->message);
+ if (error) {
+ return error;
+ }
}
+ gen->write_assert(condition, message);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_ASSERT);
- codegen.opcodes.push_back(ret2);
- codegen.opcodes.push_back(message_ret);
+ if (condition.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ if (message.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
#endif
} break;
- case GDScriptParser::Node::TYPE_BREAKPOINT: {
+ case GDScriptParser::Node::BREAKPOINT: {
#ifdef DEBUG_ENABLED
- // try subblocks
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_BREAKPOINT);
+ gen->write_breakpoint();
#endif
} break;
- case GDScriptParser::Node::TYPE_LOCAL_VAR: {
-
- const GDScriptParser::LocalVarNode *lv = static_cast<const GDScriptParser::LocalVarNode *>(s);
-
- // since we are using properties now for most class access, allow shadowing of class members to make user's life easier.
- //
- //if (_is_class_member_property(codegen, lv->name)) {
- // _set_error("Name for local variable '" + String(lv->name) + "' can't shadow class property of the same name.", lv);
- // return ERR_ALREADY_EXISTS;
- //}
-
- codegen.add_stack_identifier(lv->name, p_stack_level++);
- codegen.alloc_stack(p_stack_level);
- new_identifiers++;
+ case GDScriptParser::Node::VARIABLE: {
+ const GDScriptParser::VariableNode *lv = static_cast<const GDScriptParser::VariableNode *>(s);
+ // Should be already in stack when the block began.
+ GDScriptCodeGenerator::Address local = codegen.locals[lv->identifier->name];
+
+ if (lv->initializer != nullptr) {
+ GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, lv->initializer);
+ if (error) {
+ return error;
+ }
+ gen->write_assign(local, src_address);
+ if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ }
+ } break;
+ case GDScriptParser::Node::CONSTANT: {
+ // Local constants.
+ const GDScriptParser::ConstantNode *lc = static_cast<const GDScriptParser::ConstantNode *>(s);
+ if (!lc->initializer->is_constant) {
+ _set_error("Local constant must have a constant value as initializer.", lc->initializer);
+ return ERR_PARSE_ERROR;
+ }
+ codegen.add_local_constant(lc->identifier->name, lc->initializer->reduced_value);
} break;
+ case GDScriptParser::Node::PASS:
+ // Nothing to do.
+ break;
default: {
- //expression
- int ret2 = _parse_expression(codegen, s, p_stack_level, true);
- if (ret2 < 0)
- return ERR_PARSE_ERROR;
+ // Expression.
+ if (s->is_expression()) {
+ GDScriptCodeGenerator::Address expr = _parse_expression(codegen, error, static_cast<const GDScriptParser::ExpressionNode *>(s), true);
+ if (error) {
+ return error;
+ }
+ if (expr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ } else {
+ ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Bug in bytecode compiler, unexpected node in parse tree while parsing statement."); // Unreachable code.
+ }
} break;
}
}
- codegen.pop_stack_identifiers();
+
+ codegen.end_block();
return OK;
}
Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready) {
-
- Vector<int> bytecode;
+ Error error = OK;
CodeGen codegen;
+ codegen.generator = memnew(GDScriptByteCodeGenerator);
codegen.class_node = p_class;
codegen.script = p_script;
codegen.function_node = p_func;
- codegen.stack_max = 0;
- codegen.current_line = 0;
- codegen.call_max = 0;
- codegen.debug_stack = EngineDebugger::is_active();
- Vector<StringName> argnames;
- int stack_level = 0;
+ StringName func_name;
+ bool is_static = false;
+ MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+ GDScriptDataType return_type;
+ return_type.has_type = true;
+ return_type.kind = GDScriptDataType::BUILTIN;
+ return_type.builtin_type = Variant::NIL;
if (p_func) {
- for (int i = 0; i < p_func->arguments.size(); i++) {
- // since we are using properties now for most class access, allow shadowing of class members to make user's life easier.
- //
- //if (_is_class_member_property(p_script, p_func->arguments[i])) {
- // _set_error("Name for argument '" + String(p_func->arguments[i]) + "' can't shadow class property of the same name.", p_func);
- // return ERR_ALREADY_EXISTS;
- //}
-
- codegen.add_stack_identifier(p_func->arguments[i], i);
-#ifdef TOOLS_ENABLED
- argnames.push_back(p_func->arguments[i]);
-#endif
+ func_name = p_func->identifier->name;
+ is_static = p_func->is_static;
+ rpc_mode = p_func->rpc_mode;
+ return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script);
+ } else {
+ if (p_for_ready) {
+ func_name = "_ready";
+ } else {
+ func_name = "@implicit_new";
}
- stack_level = p_func->arguments.size();
}
- codegen.alloc_stack(stack_level);
-
- /* Parse initializer -if applies- */
-
- bool is_initializer = !p_for_ready && !p_func;
-
- if (is_initializer || (p_func && String(p_func->name) == "_init")) {
- //parse initializer for class members
- if (!p_func && p_class->extends_used && p_script->native.is_null()) {
+ codegen.function_name = func_name;
+ codegen.generator->write_start(p_script, func_name, is_static, rpc_mode, return_type);
- //call implicit parent constructor
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_CALL_SELF_BASE);
- codegen.opcodes.push_back(codegen.get_name_map_pos("_init"));
- codegen.opcodes.push_back(0);
- codegen.opcodes.push_back((GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS) | 0);
- }
- Error err = _parse_block(codegen, p_class->initializer, stack_level);
- if (err)
- return err;
- is_initializer = true;
- }
+ int optional_parameters = 0;
- if (p_for_ready || (p_func && String(p_func->name) == "_ready")) {
- //parse initializer for class members
- if (p_class->ready->statements.size()) {
- Error err = _parse_block(codegen, p_class->ready, stack_level);
- if (err)
- return err;
+ if (p_func) {
+ for (int i = 0; i < p_func->parameters.size(); i++) {
+ const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];
+ GDScriptDataType par_type = _gdtype_from_datatype(parameter->get_datatype(), p_script);
+ uint32_t par_addr = codegen.generator->add_parameter(parameter->identifier->name, parameter->default_value != nullptr, par_type);
+ codegen.parameters[parameter->identifier->name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::FUNCTION_PARAMETER, par_addr, par_type);
+
+ if (p_func->parameters[i]->default_value != nullptr) {
+ optional_parameters++;
+ }
}
}
- /* Parse default argument code -if applies- */
-
- Vector<int> defarg_addr;
- StringName func_name;
+ // Parse initializer if applies.
+ bool is_implicit_initializer = !p_for_ready && !p_func;
+ bool is_initializer = p_func && String(p_func->identifier->name) == GDScriptLanguage::get_singleton()->strings._init;
+ bool is_for_ready = p_for_ready || (p_func && String(p_func->identifier->name) == "_ready");
- if (p_func) {
+ if (is_implicit_initializer || is_for_ready) {
+ // Initialize class fields.
+ for (int i = 0; i < p_class->members.size(); i++) {
+ if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) {
+ continue;
+ }
+ const GDScriptParser::VariableNode *field = p_class->members[i].variable;
+ if (field->onready != is_for_ready) {
+ // Only initialize in _ready.
+ continue;
+ }
- if (p_func->default_values.size()) {
+ if (field->initializer) {
+ // Emit proper line change.
+ codegen.generator->write_newline(field->initializer->start_line);
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_JUMP_TO_DEF_ARGUMENT);
- defarg_addr.push_back(codegen.opcodes.size());
- for (int i = 0; i < p_func->default_values.size(); i++) {
+ GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, field->initializer, false, true);
+ if (error) {
+ memdelete(codegen.generator);
+ return error;
+ }
+ GDScriptCodeGenerator::Address dst_address(GDScriptCodeGenerator::Address::MEMBER, codegen.script->member_indices[field->identifier->name].index, _gdtype_from_datatype(field->get_datatype()));
- _parse_expression(codegen, p_func->default_values[i], stack_level, true);
- defarg_addr.push_back(codegen.opcodes.size());
+ codegen.generator->write_assign(dst_address, src_address);
+ if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
}
+ }
+ }
- defarg_addr.invert();
+ // Parse default argument code if applies.
+ if (p_func) {
+ if (optional_parameters > 0) {
+ codegen.generator->start_parameters();
+ for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) {
+ const GDScriptParser::ParameterNode *parameter = p_func->parameters[i];
+ GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, error, parameter->default_value, true);
+ if (error) {
+ memdelete(codegen.generator);
+ return error;
+ }
+ GDScriptCodeGenerator::Address dst_addr = codegen.parameters[parameter->identifier->name];
+ codegen.generator->write_assign_default_parameter(dst_addr, src_addr);
+ if (src_addr.mode == GDScriptCodeGenerator::Address::TEMPORARY) {
+ codegen.generator->pop_temporary();
+ }
+ }
+ codegen.generator->end_parameters();
}
- Error err = _parse_block(codegen, p_func->body, stack_level);
- if (err)
+ Error err = _parse_block(codegen, p_func->body);
+ if (err) {
+ memdelete(codegen.generator);
return err;
-
- func_name = p_func->name;
- } else {
- if (p_for_ready)
- func_name = "_ready";
- else
- func_name = "_init";
+ }
}
- codegen.opcodes.push_back(GDScriptFunction::OPCODE_END);
+#ifdef DEBUG_ENABLED
+ if (EngineDebugger::is_active()) {
+ String signature;
+ // Path.
+ if (p_script->get_path() != String()) {
+ signature += p_script->get_path();
+ }
+ // Location.
+ if (p_func) {
+ signature += "::" + itos(p_func->body->start_line);
+ } else {
+ signature += "::0";
+ }
- /*
- if (String(p_func->name)=="") { //initializer func
- gdfunc = &p_script->initializer;
- */
- //} else { //regular func
- p_script->member_functions[func_name] = memnew(GDScriptFunction);
- GDScriptFunction *gdfunc = p_script->member_functions[func_name];
- //}
+ // Function and class.
- if (p_func) {
- gdfunc->_static = p_func->_static;
- gdfunc->rpc_mode = p_func->rpc_mode;
- gdfunc->argument_types.resize(p_func->argument_types.size());
- for (int i = 0; i < p_func->argument_types.size(); i++) {
- gdfunc->argument_types.write[i] = _gdtype_from_datatype(p_func->argument_types[i]);
+ if (p_class->identifier) {
+ signature += "::" + String(p_class->identifier->name) + "." + String(func_name);
+ } else {
+ signature += "::" + String(func_name);
}
- gdfunc->return_type = _gdtype_from_datatype(p_func->return_type);
- } else {
- gdfunc->_static = false;
- gdfunc->rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
- gdfunc->return_type = GDScriptDataType();
- gdfunc->return_type.has_type = true;
- gdfunc->return_type.kind = GDScriptDataType::BUILTIN;
- gdfunc->return_type.builtin_type = Variant::NIL;
+
+ codegen.generator->set_signature(signature);
}
+#endif
+ if (p_func) {
+ codegen.generator->set_initial_line(p_func->start_line);
#ifdef TOOLS_ENABLED
- gdfunc->arg_names = argnames;
+ p_script->member_lines[func_name] = p_func->start_line;
+ p_script->doc_functions[func_name] = p_func->doc_description;
#endif
- //constants
- if (codegen.constant_map.size()) {
- gdfunc->_constant_count = codegen.constant_map.size();
- gdfunc->constants.resize(codegen.constant_map.size());
- gdfunc->_constants_ptr = gdfunc->constants.ptrw();
- const Variant *K = nullptr;
- while ((K = codegen.constant_map.next(K))) {
- int idx = codegen.constant_map[*K];
- gdfunc->constants.write[idx] = *K;
- }
} else {
-
- gdfunc->_constants_ptr = nullptr;
- gdfunc->_constant_count = 0;
+ codegen.generator->set_initial_line(0);
}
- //global names
- if (codegen.name_map.size()) {
- gdfunc->global_names.resize(codegen.name_map.size());
- gdfunc->_global_names_ptr = &gdfunc->global_names[0];
- for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) {
+ GDScriptFunction *gd_function = codegen.generator->write_end();
- gdfunc->global_names.write[E->get()] = E->key();
- }
- gdfunc->_global_names_count = gdfunc->global_names.size();
-
- } else {
- gdfunc->_global_names_ptr = nullptr;
- gdfunc->_global_names_count = 0;
+ if (is_initializer) {
+ p_script->initializer = gd_function;
+ } else if (is_implicit_initializer) {
+ p_script->implicit_initializer = gd_function;
}
-#ifdef TOOLS_ENABLED
- // Named globals
- if (codegen.named_globals.size()) {
- gdfunc->named_globals.resize(codegen.named_globals.size());
- gdfunc->_named_globals_ptr = gdfunc->named_globals.ptr();
- for (int i = 0; i < codegen.named_globals.size(); i++) {
- gdfunc->named_globals.write[i] = codegen.named_globals[i];
+ if (p_func) {
+ // if no return statement -> return type is void not unresolved Variant
+ if (p_func->body->has_return) {
+ gd_function->return_type = _gdtype_from_datatype(p_func->get_datatype());
+ } else {
+ gd_function->return_type = GDScriptDataType();
+ gd_function->return_type.has_type = true;
+ gd_function->return_type.kind = GDScriptDataType::BUILTIN;
+ gd_function->return_type.builtin_type = Variant::NIL;
}
- gdfunc->_named_globals_count = gdfunc->named_globals.size();
- }
+#ifdef TOOLS_ENABLED
+ gd_function->default_arg_values = p_func->default_arg_values;
#endif
+ }
- if (codegen.opcodes.size()) {
+ p_script->member_functions[func_name] = gd_function;
- gdfunc->code = codegen.opcodes;
- gdfunc->_code_ptr = &gdfunc->code[0];
- gdfunc->_code_size = codegen.opcodes.size();
+ memdelete(codegen.generator);
+
+ return OK;
+}
+
+Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) {
+ Error error = OK;
+ CodeGen codegen;
+ codegen.generator = memnew(GDScriptByteCodeGenerator);
+
+ codegen.class_node = p_class;
+ codegen.script = p_script;
+ StringName func_name;
+
+ if (p_is_setter) {
+ func_name = "@" + p_variable->identifier->name + "_setter";
} else {
+ func_name = "@" + p_variable->identifier->name + "_getter";
+ }
- gdfunc->_code_ptr = nullptr;
- gdfunc->_code_size = 0;
+ GDScriptDataType return_type;
+ if (p_is_setter) {
+ return_type.has_type = true;
+ return_type.kind = GDScriptDataType::BUILTIN;
+ return_type.builtin_type = Variant::NIL;
+ } else {
+ return_type = _gdtype_from_datatype(p_variable->get_datatype(), p_script);
}
- if (defarg_addr.size()) {
+ codegen.generator->write_start(p_script, func_name, false, p_variable->rpc_mode, return_type);
- gdfunc->default_arguments = defarg_addr;
- gdfunc->_default_arg_count = defarg_addr.size() - 1;
- gdfunc->_default_arg_ptr = &gdfunc->default_arguments[0];
- } else {
- gdfunc->_default_arg_count = 0;
- gdfunc->_default_arg_ptr = nullptr;
+ if (p_is_setter) {
+ uint32_t par_addr = codegen.generator->add_parameter(p_variable->setter_parameter->name, false, _gdtype_from_datatype(p_variable->get_datatype()));
+ codegen.parameters[p_variable->setter_parameter->name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::FUNCTION_PARAMETER, par_addr, _gdtype_from_datatype(p_variable->get_datatype()));
}
- gdfunc->_argument_count = p_func ? p_func->arguments.size() : 0;
- gdfunc->_stack_size = codegen.stack_max;
- gdfunc->_call_size = codegen.call_max;
- gdfunc->name = func_name;
+ error = _parse_block(codegen, p_is_setter ? p_variable->setter : p_variable->getter);
+ if (error) {
+ memdelete(codegen.generator);
+ return error;
+ }
+
+ GDScriptFunction *gd_function = codegen.generator->write_end();
+
+ p_script->member_functions[func_name] = gd_function;
+
#ifdef DEBUG_ENABLED
if (EngineDebugger::is_active()) {
String signature;
//path
- if (p_script->get_path() != String())
+ if (p_script->get_path() != String()) {
signature += p_script->get_path();
- //loc
- if (p_func) {
- signature += "::" + itos(p_func->body->line);
- } else {
- signature += "::0";
}
+ //loc
+ signature += "::" + itos(p_is_setter ? p_variable->setter->start_line : p_variable->getter->start_line);
//function and class
- if (p_class->name) {
- signature += "::" + String(p_class->name) + "." + String(func_name);
+ if (p_class->identifier) {
+ signature += "::" + String(p_class->identifier->name) + "." + String(func_name);
} else {
signature += "::" + String(func_name);
}
- gdfunc->profile.signature = signature;
+ codegen.generator->set_signature(signature);
}
#endif
- gdfunc->_script = p_script;
- gdfunc->source = source;
-
-#ifdef DEBUG_ENABLED
+ codegen.generator->set_initial_line(p_is_setter ? p_variable->setter->start_line : p_variable->getter->start_line);
- {
- gdfunc->func_cname = (String(source) + " - " + String(func_name)).utf8();
- gdfunc->_func_cname = gdfunc->func_cname.get_data();
- }
-
-#endif
- if (p_func) {
- gdfunc->_initial_line = p_func->line;
#ifdef TOOLS_ENABLED
-
- p_script->member_lines[func_name] = p_func->line;
+ p_script->member_lines[func_name] = p_is_setter ? p_variable->setter->start_line : p_variable->getter->start_line;
#endif
- } else {
- gdfunc->_initial_line = 0;
- }
-
- if (codegen.debug_stack)
- gdfunc->stack_debug = codegen.stack_debug;
-
- if (is_initializer)
- p_script->initializer = gdfunc;
+ memdelete(codegen.generator);
return OK;
}
Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
-
parsing_classes.insert(p_script);
- if (p_class->owner && p_class->owner->owner) {
+ if (p_class->outer && p_class->outer->outer) {
// Owner is not root
if (!parsed_classes.has(p_script->_owner)) {
if (parsing_classes.has(p_script->_owner)) {
- _set_error("Cyclic class reference for '" + String(p_class->name) + "'.", p_class);
+ _set_error("Cyclic class reference for '" + String(p_class->identifier->name) + "'.", p_class);
return ERR_PARSE_ERROR;
}
- Error err = _parse_class_level(p_script->_owner, p_class->owner, p_keep_state);
+ Error err = _parse_class_level(p_script->_owner, p_class->outer, p_keep_state);
if (err) {
return err;
}
}
}
+#ifdef TOOLS_ENABLED
+ p_script->doc_functions.clear();
+ p_script->doc_variables.clear();
+ p_script->doc_constants.clear();
+ p_script->doc_enums.clear();
+ p_script->doc_signals.clear();
+ p_script->doc_tutorials.clear();
+
+ p_script->doc_brief_description = p_class->doc_brief_description;
+ p_script->doc_description = p_class->doc_description;
+ for (int i = 0; i < p_class->doc_tutorials.size(); i++) {
+ DocData::TutorialDoc td;
+ td.title = p_class->doc_tutorials[i].first;
+ td.link = p_class->doc_tutorials[i].second;
+ p_script->doc_tutorials.append(td);
+ }
+#endif
+
p_script->native = Ref<GDScriptNativeClass>();
p_script->base = Ref<GDScript>();
p_script->_base = nullptr;
@@ -1850,8 +2055,8 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
p_script->_signals.clear();
p_script->initializer = nullptr;
- p_script->tool = p_class->tool;
- p_script->name = p_class->name;
+ p_script->tool = parser->is_tool();
+ p_script->name = p_class->identifier ? p_class->identifier->name : "";
Ref<GDScriptNativeClass> native;
@@ -1865,23 +2070,38 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
p_script->native = native;
} break;
case GDScriptDataType::GDSCRIPT: {
- Ref<GDScript> base = base_type.script_type;
+ Ref<GDScript> base = Ref<GDScript>(base_type.script_type);
p_script->base = base;
p_script->_base = base.ptr();
- p_script->member_indices = base->member_indices;
- if (p_class->base_type.kind == GDScriptParser::DataType::CLASS) {
- if (!parsed_classes.has(p_script->_base)) {
- if (parsing_classes.has(p_script->_base)) {
- _set_error("Cyclic class reference for '" + String(p_class->name) + "'.", p_class);
- return ERR_PARSE_ERROR;
+ if (p_class->base_type.kind == GDScriptParser::DataType::CLASS && p_class->base_type.class_type != nullptr) {
+ if (p_class->base_type.script_path == main_script->path) {
+ if (!parsed_classes.has(p_script->_base)) {
+ if (parsing_classes.has(p_script->_base)) {
+ String class_name = p_class->identifier ? p_class->identifier->name : "<main>";
+ _set_error("Cyclic class reference for '" + class_name + "'.", p_class);
+ return ERR_PARSE_ERROR;
+ }
+ Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state);
+ if (err) {
+ return err;
+ }
}
- Error err = _parse_class_level(p_script->_base, p_class->base_type.class_type, p_keep_state);
+ } else {
+ Error err = OK;
+ base = GDScriptCache::get_full_script(p_class->base_type.script_path, err, main_script->path);
if (err) {
return err;
}
+ if (base.is_null() && !base->is_valid()) {
+ return ERR_COMPILATION_FAILED;
+ }
}
}
+
+ p_script->member_indices = base->member_indices;
+ native = base->native;
+ p_script->native = native;
} break;
default: {
_set_error("Parser bug: invalid inheritance.", p_class);
@@ -1889,91 +2109,171 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
} break;
}
- for (int i = 0; i < p_class->variables.size(); i++) {
-
- StringName name = p_class->variables[i].identifier;
-
- GDScript::MemberInfo minfo;
- minfo.index = p_script->member_indices.size();
- minfo.setter = p_class->variables[i].setter;
- minfo.getter = p_class->variables[i].getter;
- minfo.rpc_mode = p_class->variables[i].rpc_mode;
- minfo.data_type = _gdtype_from_datatype(p_class->variables[i].data_type);
-
- PropertyInfo prop_info = minfo.data_type;
- prop_info.name = name;
- PropertyInfo export_info = p_class->variables[i]._export;
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = p_class->members[i];
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::VARIABLE: {
+ const GDScriptParser::VariableNode *variable = member.variable;
+ StringName name = variable->identifier->name;
+
+ GDScript::MemberInfo minfo;
+ minfo.index = p_script->member_indices.size();
+ switch (variable->property) {
+ case GDScriptParser::VariableNode::PROP_NONE:
+ break; // Nothing to do.
+ case GDScriptParser::VariableNode::PROP_SETGET:
+ if (variable->setter_pointer != nullptr) {
+ minfo.setter = variable->setter_pointer->name;
+ }
+ if (variable->getter_pointer != nullptr) {
+ minfo.getter = variable->getter_pointer->name;
+ }
+ break;
+ case GDScriptParser::VariableNode::PROP_INLINE:
+ if (variable->setter != nullptr) {
+ minfo.setter = "@" + variable->identifier->name + "_setter";
+ }
+ if (variable->getter != nullptr) {
+ minfo.getter = "@" + variable->identifier->name + "_getter";
+ }
+ break;
+ }
+ minfo.rpc_mode = variable->rpc_mode;
+ minfo.data_type = _gdtype_from_datatype(variable->get_datatype(), p_script);
- if (export_info.type != Variant::NIL) {
+ PropertyInfo prop_info = minfo.data_type;
+ prop_info.name = name;
+ PropertyInfo export_info = variable->export_info;
- if (!minfo.data_type.has_type) {
- prop_info.type = export_info.type;
- prop_info.class_name = export_info.class_name;
- }
- prop_info.hint = export_info.hint;
- prop_info.hint_string = export_info.hint_string;
- prop_info.usage = export_info.usage;
+ if (variable->exported) {
+ if (!minfo.data_type.has_type) {
+ prop_info.type = export_info.type;
+ prop_info.class_name = export_info.class_name;
+ }
+ prop_info.hint = export_info.hint;
+ prop_info.hint_string = export_info.hint_string;
+ prop_info.usage = export_info.usage;
+ } else {
+ prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE;
+ }
#ifdef TOOLS_ENABLED
- if (p_class->variables[i].default_value.get_type() != Variant::NIL) {
- p_script->member_default_values[name] = p_class->variables[i].default_value;
- }
+ p_script->doc_variables[name] = variable->doc_description;
#endif
- } else {
- prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE;
- }
- p_script->member_info[name] = prop_info;
- p_script->member_indices[name] = minfo;
- p_script->members.insert(name);
+ p_script->member_info[name] = prop_info;
+ p_script->member_indices[name] = minfo;
+ p_script->members.insert(name);
#ifdef TOOLS_ENABLED
- p_script->member_lines[name] = p_class->variables[i].line;
+ if (variable->initializer != nullptr && variable->initializer->is_constant) {
+ p_script->member_default_values[name] = variable->initializer->reduced_value;
+ } else {
+ p_script->member_default_values.erase(name);
+ }
+ p_script->member_lines[name] = variable->start_line;
#endif
- }
-
- for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
+ } break;
- StringName name = E->key();
+ case GDScriptParser::ClassNode::Member::CONSTANT: {
+ const GDScriptParser::ConstantNode *constant = member.constant;
+ StringName name = constant->identifier->name;
- ERR_CONTINUE(E->get().expression->type != GDScriptParser::Node::TYPE_CONSTANT);
+ p_script->constants.insert(name, constant->initializer->reduced_value);
+#ifdef TOOLS_ENABLED
+ p_script->member_lines[name] = constant->start_line;
+ if (constant->doc_description != String()) {
+ p_script->doc_constants[name] = constant->doc_description;
+ }
+#endif
+ } break;
- GDScriptParser::ConstantNode *constant = static_cast<GDScriptParser::ConstantNode *>(E->get().expression);
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
+ const GDScriptParser::EnumNode::Value &enum_value = member.enum_value;
+ StringName name = enum_value.identifier->name;
- p_script->constants.insert(name, constant->value);
+ p_script->constants.insert(name, enum_value.value);
#ifdef TOOLS_ENABLED
-
- p_script->member_lines[name] = E->get().expression->line;
+ p_script->member_lines[name] = enum_value.identifier->start_line;
+ if (!p_script->doc_enums.has("@unnamed_enums")) {
+ p_script->doc_enums["@unnamed_enums"] = DocData::EnumDoc();
+ p_script->doc_enums["@unnamed_enums"].name = "@unnamed_enums";
+ }
+ DocData::ConstantDoc const_doc;
+ const_doc.name = enum_value.identifier->name;
+ const_doc.value = Variant(enum_value.value).operator String(); // TODO-DOC: enum value currently is int.
+ const_doc.description = enum_value.doc_description;
+ p_script->doc_enums["@unnamed_enums"].values.push_back(const_doc);
#endif
- }
+ } break;
+
+ case GDScriptParser::ClassNode::Member::SIGNAL: {
+ const GDScriptParser::SignalNode *signal = member.signal;
+ StringName name = signal->identifier->name;
- for (int i = 0; i < p_class->_signals.size(); i++) {
+ GDScript *c = p_script;
- StringName name = p_class->_signals[i].name;
+ while (c) {
+ if (c->_signals.has(name)) {
+ _set_error("Signal '" + name + "' redefined (in current or parent class)", p_class);
+ return ERR_ALREADY_EXISTS;
+ }
+
+ if (c->base.is_valid()) {
+ c = c->base.ptr();
+ } else {
+ c = nullptr;
+ }
+ }
- GDScript *c = p_script;
+ if (native.is_valid()) {
+ if (ClassDB::has_signal(native->get_name(), name)) {
+ _set_error("Signal '" + name + "' redefined (original in native class '" + String(native->get_name()) + "')", p_class);
+ return ERR_ALREADY_EXISTS;
+ }
+ }
- while (c) {
+ Vector<StringName> parameters_names;
+ parameters_names.resize(signal->parameters.size());
+ for (int j = 0; j < signal->parameters.size(); j++) {
+ parameters_names.write[j] = signal->parameters[j]->identifier->name;
+ }
+ p_script->_signals[name] = parameters_names;
+#ifdef TOOLS_ENABLED
+ if (!signal->doc_description.is_empty()) {
+ p_script->doc_signals[name] = signal->doc_description;
+ }
+#endif
+ } break;
- if (c->_signals.has(name)) {
- _set_error("Signal '" + name + "' redefined (in current or parent class)", p_class);
- return ERR_ALREADY_EXISTS;
- }
+ case GDScriptParser::ClassNode::Member::ENUM: {
+ const GDScriptParser::EnumNode *enum_n = member.m_enum;
- if (c->base.is_valid()) {
- c = c->base.ptr();
- } else {
- c = nullptr;
- }
- }
+ // TODO: Make enums not be just a dictionary?
+ Dictionary new_enum;
+ for (int j = 0; j < enum_n->values.size(); j++) {
+ int value = enum_n->values[j].value;
+ // Needs to be string because Variant::get will convert to String.
+ new_enum[String(enum_n->values[j].identifier->name)] = value;
+ }
- if (native.is_valid()) {
- if (ClassDB::has_signal(native->get_name(), name)) {
- _set_error("Signal '" + name + "' redefined (original in native class '" + String(native->get_name()) + "')", p_class);
- return ERR_ALREADY_EXISTS;
- }
+ p_script->constants.insert(enum_n->identifier->name, new_enum);
+#ifdef TOOLS_ENABLED
+ p_script->member_lines[enum_n->identifier->name] = enum_n->start_line;
+ p_script->doc_enums[enum_n->identifier->name] = DocData::EnumDoc();
+ p_script->doc_enums[enum_n->identifier->name].name = enum_n->identifier->name;
+ p_script->doc_enums[enum_n->identifier->name].description = enum_n->doc_description;
+ for (int j = 0; j < enum_n->values.size(); j++) {
+ DocData::ConstantDoc const_doc;
+ const_doc.name = enum_n->values[j].identifier->name;
+ const_doc.value = Variant(enum_n->values[j].value).operator String();
+ const_doc.description = enum_n->values[j].doc_description;
+ p_script->doc_enums[enum_n->identifier->name].values.push_back(const_doc);
+ }
+#endif
+ } break;
+ default:
+ break; // Nothing to do here.
}
-
- p_script->_signals[name] = p_class->_signals[i].arguments;
}
parsed_classes.insert(p_script);
@@ -1981,21 +2281,27 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
//parse sub-classes
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- StringName name = p_class->subclasses[i]->name;
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = p_class->members[i];
+ if (member.type != member.CLASS) {
+ continue;
+ }
+ const GDScriptParser::ClassNode *inner_class = member.m_class;
+ StringName name = inner_class->identifier->name;
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_ptr) && !parsing_classes.has(subclass_ptr)) {
- Error err = _parse_class_level(subclass_ptr, p_class->subclasses[i], p_keep_state);
- if (err)
+ Error err = _parse_class_level(subclass_ptr, inner_class, p_keep_state);
+ if (err) {
return err;
+ }
}
#ifdef TOOLS_ENABLED
- p_script->member_lines[name] = p_class->subclasses[i]->line;
+ p_script->member_lines[name] = inner_class->start_line;
#endif
p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants
@@ -2007,41 +2313,52 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
//parse methods
- bool has_initializer = false;
bool has_ready = false;
- for (int i = 0; i < p_class->functions.size(); i++) {
-
- if (!has_initializer && p_class->functions[i]->name == "_init")
- has_initializer = true;
- if (!has_ready && p_class->functions[i]->name == "_ready")
- has_ready = true;
- Error err = _parse_function(p_script, p_class, p_class->functions[i]);
- if (err)
- return err;
- }
-
- //parse static methods
-
- for (int i = 0; i < p_class->static_functions.size(); i++) {
-
- Error err = _parse_function(p_script, p_class, p_class->static_functions[i]);
- if (err)
- return err;
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = p_class->members[i];
+ if (member.type == member.FUNCTION) {
+ const GDScriptParser::FunctionNode *function = member.function;
+ if (!has_ready && function->identifier->name == "_ready") {
+ has_ready = true;
+ }
+ Error err = _parse_function(p_script, p_class, function);
+ if (err) {
+ return err;
+ }
+ } else if (member.type == member.VARIABLE) {
+ const GDScriptParser::VariableNode *variable = member.variable;
+ if (variable->property == GDScriptParser::VariableNode::PROP_INLINE) {
+ if (variable->setter != nullptr) {
+ Error err = _parse_setter_getter(p_script, p_class, variable, true);
+ if (err) {
+ return err;
+ }
+ }
+ if (variable->getter != nullptr) {
+ Error err = _parse_setter_getter(p_script, p_class, variable, false);
+ if (err) {
+ return err;
+ }
+ }
+ }
+ }
}
- if (!has_initializer) {
- //create a constructor
+ {
+ // Create an implicit constructor in any case.
Error err = _parse_function(p_script, p_class, nullptr);
- if (err)
+ if (err) {
return err;
+ }
}
- if (!has_ready && p_class->ready->statements.size()) {
- //create a constructor
+ if (!has_ready && p_class->onready_used) {
+ //create a _ready constructor
Error err = _parse_function(p_script, p_class, nullptr, true);
- if (err)
+ if (err) {
return err;
+ }
}
#ifdef DEBUG_ENABLED
@@ -2050,7 +2367,6 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa
if (p_keep_state) {
for (Set<Object *>::Element *E = p_script->instances.front(); E;) {
-
Set<Object *>::Element *N = E->next();
ScriptInstance *si = E->get()->get_script_instance();
@@ -2085,7 +2401,6 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa
}
#endif
} else {
-
GDScriptInstance *gi = static_cast<GDScriptInstance *>(si);
gi->reload_members();
}
@@ -2095,11 +2410,15 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa
}
#endif
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- StringName name = p_class->subclasses[i]->name;
+ for (int i = 0; i < p_class->members.size(); i++) {
+ if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
+ continue;
+ }
+ const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
+ StringName name = inner_class->identifier->name;
GDScript *subclass = p_script->subclasses[name].ptr();
- Error err = _parse_class_blocks(subclass, p_class->subclasses[i], p_keep_state);
+ Error err = _parse_class_blocks(subclass, inner_class, p_keep_state);
if (err) {
return err;
}
@@ -2110,7 +2429,6 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa
}
void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state) {
-
Map<StringName, Ref<GDScript>> old_subclasses;
if (p_keep_state) {
@@ -2119,8 +2437,12 @@ void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::C
p_script->subclasses.clear();
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- StringName name = p_class->subclasses[i]->name;
+ for (int i = 0; i < p_class->members.size(); i++) {
+ if (p_class->members[i].type != GDScriptParser::ClassNode::Member::CLASS) {
+ continue;
+ }
+ const GDScriptParser::ClassNode *inner_class = p_class->members[i].m_class;
+ StringName name = inner_class->identifier->name;
Ref<GDScript> subclass;
String fully_qualified_name = p_script->fully_qualified_name + "::" + name;
@@ -2140,19 +2462,17 @@ void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::C
subclass->fully_qualified_name = fully_qualified_name;
p_script->subclasses.insert(name, subclass);
- _make_scripts(subclass.ptr(), p_class->subclasses[i], false);
+ _make_scripts(subclass.ptr(), inner_class, false);
}
}
Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state) {
-
err_line = -1;
err_column = -1;
error = "";
parser = p_parser;
main_script = p_script;
- const GDScriptParser::Node *root = parser->get_parse_tree();
- ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, ERR_INVALID_DATA);
+ const GDScriptParser::ClassNode *root = parser->get_tree();
source = p_script->get_path();
@@ -2160,32 +2480,33 @@ Error GDScriptCompiler::compile(const GDScriptParser *p_parser, GDScript *p_scri
p_script->fully_qualified_name = p_script->path;
// Create scripts for subclasses beforehand so they can be referenced
- _make_scripts(p_script, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state);
+ _make_scripts(p_script, root, p_keep_state);
p_script->_owner = nullptr;
- Error err = _parse_class_level(p_script, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state);
+ Error err = _parse_class_level(p_script, root, p_keep_state);
- if (err)
+ if (err) {
return err;
+ }
- err = _parse_class_blocks(p_script, static_cast<const GDScriptParser::ClassNode *>(root), p_keep_state);
+ err = _parse_class_blocks(p_script, root, p_keep_state);
- if (err)
+ if (err) {
return err;
+ }
- return OK;
+ return GDScriptCache::finish_compiling(p_script->get_path());
}
String GDScriptCompiler::get_error() const {
-
return error;
}
-int GDScriptCompiler::get_error_line() const {
+int GDScriptCompiler::get_error_line() const {
return err_line;
}
-int GDScriptCompiler::get_error_column() const {
+int GDScriptCompiler::get_error_column() const {
return err_column;
}
diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h
index 34b066b5c7..00953ad752 100644
--- a/modules/gdscript/gdscript_compiler.h
+++ b/modules/gdscript/gdscript_compiler.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,107 +31,86 @@
#ifndef GDSCRIPT_COMPILER_H
#define GDSCRIPT_COMPILER_H
-#include "core/set.h"
+#include "core/templates/set.h"
#include "gdscript.h"
+#include "gdscript_codegen.h"
+#include "gdscript_function.h"
#include "gdscript_parser.h"
class GDScriptCompiler {
-
- const GDScriptParser *parser;
+ const GDScriptParser *parser = nullptr;
Set<GDScript *> parsed_classes;
Set<GDScript *> parsing_classes;
- GDScript *main_script;
- struct CodeGen {
+ GDScript *main_script = nullptr;
- GDScript *script;
- const GDScriptParser::ClassNode *class_node;
- const GDScriptParser::FunctionNode *function_node;
- bool debug_stack;
-
- List<Map<StringName, int>> stack_id_stack;
- Map<StringName, int> stack_identifiers;
-
- List<GDScriptFunction::StackDebug> stack_debug;
- List<Map<StringName, int>> block_identifier_stack;
- Map<StringName, int> block_identifiers;
-
- void add_stack_identifier(const StringName &p_id, int p_stackpos) {
- stack_identifiers[p_id] = p_stackpos;
- if (debug_stack) {
- block_identifiers[p_id] = p_stackpos;
- GDScriptFunction::StackDebug sd;
- sd.added = true;
- sd.line = current_line;
- sd.identifier = p_id;
- sd.pos = p_stackpos;
- stack_debug.push_back(sd);
- }
+ struct CodeGen {
+ GDScript *script = nullptr;
+ const GDScriptParser::ClassNode *class_node = nullptr;
+ const GDScriptParser::FunctionNode *function_node = nullptr;
+ StringName function_name;
+ GDScriptCodeGenerator *generator = nullptr;
+ Map<StringName, GDScriptCodeGenerator::Address> parameters;
+ Map<StringName, GDScriptCodeGenerator::Address> locals;
+ List<Map<StringName, GDScriptCodeGenerator::Address>> locals_stack;
+
+ GDScriptCodeGenerator::Address add_local(const StringName &p_name, const GDScriptDataType &p_type) {
+ uint32_t addr = generator->add_local(p_name, p_type);
+ locals[p_name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::LOCAL_VARIABLE, addr, p_type);
+ return locals[p_name];
}
- void push_stack_identifiers() {
- stack_id_stack.push_back(stack_identifiers);
- if (debug_stack) {
-
- block_identifier_stack.push_back(block_identifiers);
- block_identifiers.clear();
- }
+ GDScriptCodeGenerator::Address add_local_constant(const StringName &p_name, const Variant &p_value) {
+ uint32_t addr = generator->add_local_constant(p_name, p_value);
+ locals[p_name] = GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::LOCAL_CONSTANT, addr);
+ return locals[p_name];
}
- void pop_stack_identifiers() {
- stack_identifiers = stack_id_stack.back()->get();
- stack_id_stack.pop_back();
-
- if (debug_stack) {
- for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) {
+ GDScriptCodeGenerator::Address add_temporary(const GDScriptDataType &p_type = GDScriptDataType()) {
+ uint32_t addr = generator->add_temporary();
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::TEMPORARY, addr, p_type);
+ }
- GDScriptFunction::StackDebug sd;
- sd.added = false;
- sd.identifier = E->key();
- sd.line = current_line;
- sd.pos = E->get();
- stack_debug.push_back(sd);
+ GDScriptCodeGenerator::Address add_constant(const Variant &p_constant) {
+ GDScriptDataType type;
+ type.has_type = true;
+ type.kind = GDScriptDataType::BUILTIN;
+ type.builtin_type = p_constant.get_type();
+ if (type.builtin_type == Variant::OBJECT) {
+ Object *obj = p_constant;
+ if (obj) {
+ type.kind = GDScriptDataType::NATIVE;
+ type.native_type = obj->get_class_name();
+
+ Ref<Script> script = obj->get_script();
+ if (script.is_valid()) {
+ type.script_type = script.ptr();
+ Ref<GDScript> gdscript = script;
+ if (gdscript.is_valid()) {
+ type.kind = GDScriptDataType::GDSCRIPT;
+ } else {
+ type.kind = GDScriptDataType::SCRIPT;
+ }
+ }
+ } else {
+ type.builtin_type = Variant::NIL;
}
- block_identifiers = block_identifier_stack.back()->get();
- block_identifier_stack.pop_back();
}
- }
- HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
- Map<StringName, int> name_map;
-#ifdef TOOLS_ENABLED
- Vector<StringName> named_globals;
-#endif
-
- int get_name_map_pos(const StringName &p_identifier) {
- int ret;
- if (!name_map.has(p_identifier)) {
- ret = name_map.size();
- name_map[p_identifier] = ret;
- } else {
- ret = name_map[p_identifier];
- }
- return ret;
+ uint32_t addr = generator->add_or_get_constant(p_constant);
+ return GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::CONSTANT, addr, type);
}
- int get_constant_pos(const Variant &p_constant) {
- if (constant_map.has(p_constant))
- return constant_map[p_constant];
- int pos = constant_map.size();
- constant_map[p_constant] = pos;
- return pos;
+ void start_block() {
+ Map<StringName, GDScriptCodeGenerator::Address> old_locals = locals;
+ locals_stack.push_back(old_locals);
+ generator->start_block();
}
- Vector<int> opcodes;
- void alloc_stack(int p_level) {
- if (p_level >= stack_max) stack_max = p_level + 1;
- }
- void alloc_call(int p_params) {
- if (p_params >= call_max) call_max = p_params;
+ void end_block() {
+ locals = locals_stack.back()->get();
+ locals_stack.pop_back();
+ generator->end_block();
}
-
- int current_line;
- int stack_max;
- int call_max;
};
bool _is_class_member_property(CodeGen &codegen, const StringName &p_name);
@@ -139,15 +118,18 @@ class GDScriptCompiler {
void _set_error(const String &p_error, const GDScriptParser::Node *p_node);
- bool _create_unary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level);
- bool _create_binary_operator(CodeGen &codegen, const GDScriptParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer = false, int p_index_addr = 0);
+ Error _create_binary_operator(CodeGen &codegen, const GDScriptParser::BinaryOpNode *on, Variant::Operator op, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address());
+ Error _create_binary_operator(CodeGen &codegen, const GDScriptParser::ExpressionNode *p_left_operand, const GDScriptParser::ExpressionNode *p_right_operand, Variant::Operator op, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address());
- GDScriptDataType _gdtype_from_datatype(const GDScriptParser::DataType &p_datatype) const;
+ GDScriptDataType _gdtype_from_datatype(const GDScriptParser::DataType &p_datatype, GDScript *p_owner = nullptr) const;
- int _parse_assign_right_expression(CodeGen &codegen, const GDScriptParser::OperatorNode *p_expression, int p_stack_level, int p_index_addr = 0);
- int _parse_expression(CodeGen &codegen, const GDScriptParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false, int p_index_addr = 0);
- Error _parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1);
+ GDScriptCodeGenerator::Address _parse_assign_right_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::AssignmentNode *p_assignmentint, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address());
+ GDScriptCodeGenerator::Address _parse_expression(CodeGen &codegen, Error &r_error, const GDScriptParser::ExpressionNode *p_expression, bool p_root = false, bool p_initializer = false, const GDScriptCodeGenerator::Address &p_index_addr = GDScriptCodeGenerator::Address());
+ GDScriptCodeGenerator::Address _parse_match_pattern(CodeGen &codegen, Error &r_error, const GDScriptParser::PatternNode *p_pattern, const GDScriptCodeGenerator::Address &p_value_addr, const GDScriptCodeGenerator::Address &p_type_addr, const GDScriptCodeGenerator::Address &p_previous_test, bool p_is_first, bool p_is_nested);
+ void _add_locals_in_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block);
+ Error _parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals = true);
Error _parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false);
+ Error _parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter);
Error _parse_class_level(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state);
Error _parse_class_blocks(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state);
void _make_scripts(GDScript *p_script, const GDScriptParser::ClassNode *p_class, bool p_keep_state);
@@ -155,6 +137,7 @@ class GDScriptCompiler {
int err_column;
StringName source;
String error;
+ bool within_await = false;
public:
Error compile(const GDScriptParser *p_parser, GDScript *p_script, bool p_keep_state = false);
diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp
new file mode 100644
index 0000000000..17cb5e3c96
--- /dev/null
+++ b/modules/gdscript/gdscript_disassembler.cpp
@@ -0,0 +1,842 @@
+/*************************************************************************/
+/* gdscript_disassembler.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#ifdef DEBUG_ENABLED
+
+#include "gdscript_function.h"
+
+#include "core/string/string_builder.h"
+#include "gdscript.h"
+
+static String _get_variant_string(const Variant &p_variant) {
+ String txt;
+ if (p_variant.get_type() == Variant::STRING) {
+ txt = "\"" + String(p_variant) + "\"";
+ } else if (p_variant.get_type() == Variant::STRING_NAME) {
+ txt = "&\"" + String(p_variant) + "\"";
+ } else if (p_variant.get_type() == Variant::NODE_PATH) {
+ txt = "^\"" + String(p_variant) + "\"";
+ } else if (p_variant.get_type() == Variant::OBJECT) {
+ Object *obj = p_variant;
+ if (!obj) {
+ txt = "null";
+ } else {
+ GDScriptNativeClass *cls = Object::cast_to<GDScriptNativeClass>(obj);
+ if (cls) {
+ txt += cls->get_name();
+ txt += " (class)";
+ } else {
+ txt = obj->get_class();
+ if (obj->get_script_instance()) {
+ txt += "(" + obj->get_script_instance()->get_script()->get_path() + ")";
+ }
+ }
+ }
+ } else {
+ txt = p_variant;
+ }
+ return txt;
+}
+
+static String _disassemble_address(const GDScript *p_script, const GDScriptFunction &p_function, int p_address) {
+ int addr = p_address & GDScriptFunction::ADDR_MASK;
+
+ switch (p_address >> GDScriptFunction::ADDR_BITS) {
+ case GDScriptFunction::ADDR_TYPE_SELF: {
+ return "self";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_CLASS: {
+ return "class";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_MEMBER: {
+ return "member(" + p_script->debug_get_member_by_index(addr) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_CLASS_CONSTANT: {
+ return "class_const(" + p_function.get_global_name(addr) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_LOCAL_CONSTANT: {
+ return "const(" + _get_variant_string(p_function.get_constant(addr)) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_STACK: {
+ return "stack(" + itos(addr) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_STACK_VARIABLE: {
+ return "var_stack(" + itos(addr) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_GLOBAL: {
+ return "global(" + _get_variant_string(GDScriptLanguage::get_singleton()->get_global_array()[addr]) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_NAMED_GLOBAL: {
+ return "named_global(" + p_function.get_global_name(addr) + ")";
+ } break;
+ case GDScriptFunction::ADDR_TYPE_NIL: {
+ return "nil";
+ } break;
+ }
+
+ return "<err>";
+}
+
+void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const {
+#define DADDR(m_ip) (_disassemble_address(_script, *this, _code_ptr[ip + m_ip]))
+
+ for (int ip = 0; ip < _code_size;) {
+ StringBuilder text;
+ int incr = 0;
+
+ text += " ";
+ text += itos(ip);
+ text += ": ";
+
+ // This makes the compiler complain if some opcode is unchecked in the switch.
+ Opcode code = Opcode(_code_ptr[ip] & INSTR_MASK);
+ int instr_var_args = (_code_ptr[ip] & INSTR_ARGS_MASK) >> INSTR_BITS;
+
+ switch (code) {
+ case OPCODE_OPERATOR: {
+ int operation = _code_ptr[ip + 4];
+
+ text += "operator ";
+
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += " ";
+ text += Variant::get_operator_name(Variant::Operator(operation));
+ text += " ";
+ text += DADDR(2);
+
+ incr += 5;
+ } break;
+ case OPCODE_OPERATOR_VALIDATED: {
+ text += "validated operator ";
+
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += " <operator function> ";
+ text += DADDR(2);
+
+ incr += 5;
+ } break;
+ case OPCODE_EXTENDS_TEST: {
+ text += "is object ";
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += " is ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_IS_BUILTIN: {
+ text += "is builtin ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += " is ";
+ text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 3]));
+
+ incr += 4;
+ } break;
+ case OPCODE_SET_KEYED: {
+ text += "set keyed ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "] = ";
+ text += DADDR(3);
+
+ incr += 4;
+ } break;
+ case OPCODE_SET_KEYED_VALIDATED: {
+ text += "set keyed validated ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "] = ";
+ text += DADDR(3);
+
+ incr += 5;
+ } break;
+ case OPCODE_SET_INDEXED_VALIDATED: {
+ text += "set indexed validated ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "] = ";
+ text += DADDR(3);
+
+ incr += 5;
+ } break;
+ case OPCODE_GET_KEYED: {
+ text += "get keyed ";
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "]";
+
+ incr += 4;
+ } break;
+ case OPCODE_GET_KEYED_VALIDATED: {
+ text += "get keyed validated ";
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "]";
+
+ incr += 5;
+ } break;
+ case OPCODE_GET_INDEXED_VALIDATED: {
+ text += "get indexed validated ";
+ text += DADDR(3);
+ text += " = ";
+ text += DADDR(1);
+ text += "[";
+ text += DADDR(2);
+ text += "]";
+
+ incr += 5;
+ } break;
+ case OPCODE_SET_NAMED: {
+ text += "set_named ";
+ text += DADDR(1);
+ text += "[\"";
+ text += _global_names_ptr[_code_ptr[ip + 3]];
+ text += "\"] = ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_SET_NAMED_VALIDATED: {
+ text += "set_named validated ";
+ text += DADDR(1);
+ text += "[\"";
+ text += "<unknown name>";
+ text += "\"] = ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_GET_NAMED: {
+ text += "get_named ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += "[\"";
+ text += _global_names_ptr[_code_ptr[ip + 3]];
+ text += "\"]";
+
+ incr += 4;
+ } break;
+ case OPCODE_GET_NAMED_VALIDATED: {
+ text += "get_named validated ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += "[\"";
+ text += "<unknown name>";
+ text += "\"]";
+
+ incr += 4;
+ } break;
+ case OPCODE_SET_MEMBER: {
+ text += "set_member ";
+ text += "[\"";
+ text += _global_names_ptr[_code_ptr[ip + 2]];
+ text += "\"] = ";
+ text += DADDR(1);
+
+ incr += 3;
+ } break;
+ case OPCODE_GET_MEMBER: {
+ text += "get_member ";
+ text += DADDR(1);
+ text += " = ";
+ text += "[\"";
+ text += _global_names_ptr[_code_ptr[ip + 2]];
+ text += "\"]";
+
+ incr += 3;
+ } break;
+ case OPCODE_ASSIGN: {
+ text += "assign ";
+ text += DADDR(1);
+ text += " = ";
+ text += DADDR(2);
+
+ incr += 3;
+ } break;
+ case OPCODE_ASSIGN_TRUE: {
+ text += "assign ";
+ text += DADDR(1);
+ text += " = true";
+
+ incr += 2;
+ } break;
+ case OPCODE_ASSIGN_FALSE: {
+ text += "assign ";
+ text += DADDR(1);
+ text += " = false";
+
+ incr += 2;
+ } break;
+ case OPCODE_ASSIGN_TYPED_BUILTIN: {
+ text += "assign typed builtin (";
+ text += Variant::get_type_name((Variant::Type)_code_ptr[ip + 3]);
+ text += ") ";
+ text += DADDR(1);
+ text += " = ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_ASSIGN_TYPED_NATIVE: {
+ text += "assign typed native (";
+ text += DADDR(3);
+ text += ") ";
+ text += DADDR(1);
+ text += " = ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_ASSIGN_TYPED_SCRIPT: {
+ Variant script = _constants_ptr[_code_ptr[ip + 3]];
+ Script *sc = Object::cast_to<Script>(script.operator Object *());
+
+ text += "assign typed script (";
+ text += sc->get_path();
+ text += ") ";
+ text += DADDR(1);
+ text += " = ";
+ text += DADDR(2);
+
+ incr += 4;
+ } break;
+ case OPCODE_CAST_TO_BUILTIN: {
+ text += "cast builtin ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += " as ";
+ text += Variant::get_type_name(Variant::Type(_code_ptr[ip + 1]));
+
+ incr += 4;
+ } break;
+ case OPCODE_CAST_TO_NATIVE: {
+ text += "cast native ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += " as ";
+ text += DADDR(3);
+
+ incr += 4;
+ } break;
+ case OPCODE_CAST_TO_SCRIPT: {
+ text += "cast ";
+ text += DADDR(2);
+ text += " = ";
+ text += DADDR(1);
+ text += " as ";
+ text += DADDR(3);
+
+ incr += 4;
+ } break;
+ case OPCODE_CONSTRUCT: {
+ Variant::Type t = Variant::Type(_code_ptr[ip + 3 + instr_var_args]);
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+
+ text += "construct ";
+ text += DADDR(1 + argc);
+ text += " = ";
+
+ text += Variant::get_type_name(t) + "(";
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(i + 1);
+ }
+ text += ")";
+
+ incr = 3 + instr_var_args;
+ } break;
+ case OPCODE_CONSTRUCT_VALIDATED: {
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+
+ text += "construct validated ";
+ text += DADDR(1 + argc);
+ text += " = ";
+
+ text += "<unkown type>(";
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(i + 1);
+ }
+ text += ")";
+
+ incr = 3 + instr_var_args;
+ } break;
+ case OPCODE_CONSTRUCT_ARRAY: {
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += " make_array ";
+ text += DADDR(1 + argc);
+ text += " = [";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+
+ text += "]";
+
+ incr += 3 + argc;
+ } break;
+ case OPCODE_CONSTRUCT_DICTIONARY: {
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += "make_dict ";
+ text += DADDR(1 + argc * 2);
+ text += " = {";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i * 2 + 0);
+ text += ": ";
+ text += DADDR(1 + i * 2 + 1);
+ }
+
+ text += "}";
+
+ incr += 3 + argc * 2;
+ } break;
+ case OPCODE_CALL:
+ case OPCODE_CALL_RETURN:
+ case OPCODE_CALL_ASYNC: {
+ bool ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_RETURN;
+ bool async = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_ASYNC;
+
+ if (ret) {
+ text += "call-ret ";
+ } else if (async) {
+ text += "call-async ";
+ } else {
+ text += "call ";
+ }
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ if (ret || async) {
+ text += DADDR(2 + argc) + " = ";
+ }
+
+ text += DADDR(1 + argc) + ".";
+ text += String(_global_names_ptr[_code_ptr[ip + 2 + instr_var_args]]);
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 5 + argc;
+ } break;
+ case OPCODE_CALL_METHOD_BIND:
+ case OPCODE_CALL_METHOD_BIND_RET: {
+ bool ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_METHOD_BIND_RET;
+
+ if (ret) {
+ text += "call-method_bind-ret ";
+ } else {
+ text += "call-method_bind ";
+ }
+
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]];
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ if (ret) {
+ text += DADDR(2 + argc) + " = ";
+ }
+
+ text += DADDR(1 + argc) + ".";
+ text += method->get_name();
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 5 + argc;
+ } break;
+ case OPCODE_CALL_PTRCALL_NO_RETURN: {
+ text += "call-ptrcall (no return) ";
+
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]];
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+
+ text += DADDR(1 + argc) + ".";
+ text += method->get_name();
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 5 + argc;
+ } break;
+
+#define DISASSEMBLE_PTRCALL(m_type) \
+ case OPCODE_CALL_PTRCALL_##m_type: { \
+ text += "call-ptrcall (return "; \
+ text += #m_type; \
+ text += ") "; \
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2 + instr_var_args]]; \
+ int argc = _code_ptr[ip + 1 + instr_var_args]; \
+ text += DADDR(2 + argc) + " = "; \
+ text += DADDR(1 + argc) + "."; \
+ text += method->get_name(); \
+ text += "("; \
+ for (int i = 0; i < argc; i++) { \
+ if (i > 0) \
+ text += ", "; \
+ text += DADDR(1 + i); \
+ } \
+ text += ")"; \
+ incr = 5 + argc; \
+ } break
+
+ DISASSEMBLE_PTRCALL(BOOL);
+ DISASSEMBLE_PTRCALL(INT);
+ DISASSEMBLE_PTRCALL(FLOAT);
+ DISASSEMBLE_PTRCALL(STRING);
+ DISASSEMBLE_PTRCALL(VECTOR2);
+ DISASSEMBLE_PTRCALL(VECTOR2I);
+ DISASSEMBLE_PTRCALL(RECT2);
+ DISASSEMBLE_PTRCALL(RECT2I);
+ DISASSEMBLE_PTRCALL(VECTOR3);
+ DISASSEMBLE_PTRCALL(VECTOR3I);
+ DISASSEMBLE_PTRCALL(TRANSFORM2D);
+ DISASSEMBLE_PTRCALL(PLANE);
+ DISASSEMBLE_PTRCALL(AABB);
+ DISASSEMBLE_PTRCALL(BASIS);
+ DISASSEMBLE_PTRCALL(TRANSFORM);
+ DISASSEMBLE_PTRCALL(COLOR);
+ DISASSEMBLE_PTRCALL(STRING_NAME);
+ DISASSEMBLE_PTRCALL(NODE_PATH);
+ DISASSEMBLE_PTRCALL(RID);
+ DISASSEMBLE_PTRCALL(QUAT);
+ DISASSEMBLE_PTRCALL(OBJECT);
+ DISASSEMBLE_PTRCALL(CALLABLE);
+ DISASSEMBLE_PTRCALL(SIGNAL);
+ DISASSEMBLE_PTRCALL(DICTIONARY);
+ DISASSEMBLE_PTRCALL(ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_BYTE_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_INT32_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_INT64_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_FLOAT32_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_FLOAT64_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_STRING_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_VECTOR2_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_VECTOR3_ARRAY);
+ DISASSEMBLE_PTRCALL(PACKED_COLOR_ARRAY);
+
+ case OPCODE_CALL_BUILTIN_TYPE_VALIDATED: {
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+
+ text += "call-builtin-method validated ";
+
+ text += DADDR(2 + argc) + " = ";
+
+ text += DADDR(1) + ".";
+ text += "<unknown method>";
+
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 5 + argc;
+ } break;
+ case OPCODE_CALL_UTILITY: {
+ text += "call-utility ";
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += DADDR(1 + argc) + " = ";
+
+ text += _global_names_ptr[_code_ptr[ip + 2 + instr_var_args]];
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 4 + argc;
+ } break;
+ case OPCODE_CALL_UTILITY_VALIDATED: {
+ text += "call-utility ";
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += DADDR(1 + argc) + " = ";
+
+ text += "<unkown function>";
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 4 + argc;
+ } break;
+ case OPCODE_CALL_GDSCRIPT_UTILITY: {
+ text += "call-gscript-utility ";
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += DADDR(1 + argc) + " = ";
+
+ text += "<unknown function>";
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 4 + argc;
+ } break;
+ case OPCODE_CALL_SELF_BASE: {
+ text += "call-self-base ";
+
+ int argc = _code_ptr[ip + 1 + instr_var_args];
+ text += DADDR(2 + argc) + " = ";
+
+ text += _global_names_ptr[_code_ptr[ip + 2 + instr_var_args]];
+ text += "(";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ text += ", ";
+ text += DADDR(1 + i);
+ }
+ text += ")";
+
+ incr = 4 + argc;
+ } break;
+ case OPCODE_AWAIT: {
+ text += "await ";
+ text += DADDR(1);
+
+ incr += 2;
+ } break;
+ case OPCODE_AWAIT_RESUME: {
+ text += "await resume ";
+ text += DADDR(1);
+
+ incr = 2;
+ } break;
+ case OPCODE_JUMP: {
+ text += "jump ";
+ text += itos(_code_ptr[ip + 1]);
+
+ incr = 2;
+ } break;
+ case OPCODE_JUMP_IF: {
+ text += "jump-if ";
+ text += DADDR(1);
+ text += " to ";
+ text += itos(_code_ptr[ip + 2]);
+
+ incr = 3;
+ } break;
+ case OPCODE_JUMP_IF_NOT: {
+ text += "jump-if-not ";
+ text += DADDR(1);
+ text += " to ";
+ text += itos(_code_ptr[ip + 2]);
+
+ incr = 3;
+ } break;
+ case OPCODE_JUMP_TO_DEF_ARGUMENT: {
+ text += "jump-to-default-argument ";
+
+ incr = 1;
+ } break;
+ case OPCODE_RETURN: {
+ text += "return ";
+ text += DADDR(1);
+
+ incr = 2;
+ } break;
+
+#define DISASSEMBLE_ITERATE(m_type) \
+ case OPCODE_ITERATE_##m_type: { \
+ text += "for-loop (typed "; \
+ text += #m_type; \
+ text += ") "; \
+ text += DADDR(3); \
+ text += " in "; \
+ text += DADDR(2); \
+ text += " counter "; \
+ text += DADDR(1); \
+ text += " end "; \
+ text += itos(_code_ptr[ip + 4]); \
+ incr += 5; \
+ } break
+
+#define DISASSEMBLE_ITERATE_BEGIN(m_type) \
+ case OPCODE_ITERATE_BEGIN_##m_type: { \
+ text += "for-init (typed "; \
+ text += #m_type; \
+ text += ") "; \
+ text += DADDR(3); \
+ text += " in "; \
+ text += DADDR(2); \
+ text += " counter "; \
+ text += DADDR(1); \
+ text += " end "; \
+ text += itos(_code_ptr[ip + 4]); \
+ incr += 5; \
+ } break
+
+#define DISASSEMBLE_ITERATE_TYPES(m_macro) \
+ m_macro(INT); \
+ m_macro(FLOAT); \
+ m_macro(VECTOR2); \
+ m_macro(VECTOR2I); \
+ m_macro(VECTOR3); \
+ m_macro(VECTOR3I); \
+ m_macro(STRING); \
+ m_macro(DICTIONARY); \
+ m_macro(ARRAY); \
+ m_macro(PACKED_BYTE_ARRAY); \
+ m_macro(PACKED_INT32_ARRAY); \
+ m_macro(PACKED_INT64_ARRAY); \
+ m_macro(PACKED_FLOAT32_ARRAY); \
+ m_macro(PACKED_FLOAT64_ARRAY); \
+ m_macro(PACKED_STRING_ARRAY); \
+ m_macro(PACKED_VECTOR2_ARRAY); \
+ m_macro(PACKED_VECTOR3_ARRAY); \
+ m_macro(PACKED_COLOR_ARRAY); \
+ m_macro(OBJECT)
+
+ case OPCODE_ITERATE_BEGIN: {
+ text += "for-init ";
+ text += DADDR(3);
+ text += " in ";
+ text += DADDR(2);
+ text += " counter ";
+ text += DADDR(1);
+ text += " end ";
+ text += itos(_code_ptr[ip + 4]);
+
+ incr += 5;
+ } break;
+ DISASSEMBLE_ITERATE_TYPES(DISASSEMBLE_ITERATE_BEGIN);
+ case OPCODE_ITERATE: {
+ text += "for-loop ";
+ text += DADDR(2);
+ text += " in ";
+ text += DADDR(2);
+ text += " counter ";
+ text += DADDR(1);
+ text += " end ";
+ text += itos(_code_ptr[ip + 4]);
+
+ incr += 5;
+ } break;
+ DISASSEMBLE_ITERATE_TYPES(DISASSEMBLE_ITERATE);
+ case OPCODE_LINE: {
+ int line = _code_ptr[ip + 1] - 1;
+ if (line >= 0 && line < p_code_lines.size()) {
+ text += "line ";
+ text += itos(line + 1);
+ text += ": ";
+ text += p_code_lines[line];
+ } else {
+ text += "";
+ }
+
+ incr += 2;
+ } break;
+ case OPCODE_ASSERT: {
+ text += "assert (";
+ text += DADDR(1);
+ text += ", ";
+ text += DADDR(2);
+ text += ")";
+
+ incr += 3;
+ } break;
+ case OPCODE_BREAKPOINT: {
+ text += "breakpoint";
+
+ incr += 1;
+ } break;
+ case OPCODE_END: {
+ text += "== END ==";
+
+ incr += 1;
+ } break;
+ }
+
+ ip += incr;
+ if (text.get_string_length() > 0) {
+ print_line(text.as_string());
+ }
+ }
+}
+
+#endif
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index ab3228d076..b17971cf93 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,30 +30,32 @@
#include "gdscript.h"
-#include "core/engine.h"
-#include "core/global_constants.h"
+#include "core/config/engine.h"
+#include "core/core_constants.h"
#include "core/os/file_access.h"
+#include "gdscript_analyzer.h"
#include "gdscript_compiler.h"
+#include "gdscript_parser.h"
+#include "gdscript_tokenizer.h"
+#include "gdscript_utility_functions.h"
#ifdef TOOLS_ENABLED
+#include "core/config/project_settings.h"
#include "editor/editor_file_system.h"
#include "editor/editor_settings.h"
#endif
void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
-
p_delimiters->push_back("#");
}
void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
-
p_delimiters->push_back("\" \"");
p_delimiters->push_back("' '");
p_delimiters->push_back("\"\"\" \"\"\"");
}
String GDScriptLanguage::_get_processed_template(const String &p_template, const String &p_base_class_name) const {
-
String processed_template = p_template;
#ifdef TOOLS_ENABLED
@@ -109,27 +111,43 @@ Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const Str
}
bool GDScriptLanguage::is_using_templates() {
-
return true;
}
void GDScriptLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
-
String _template = _get_processed_template(p_script->get_source_code(), p_base_class_name);
p_script->set_source_code(_template);
}
-bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
+static void get_function_names_recursively(const GDScriptParser::ClassNode *p_class, const String &p_prefix, Map<int, String> &r_funcs) {
+ for (int i = 0; i < p_class->members.size(); i++) {
+ if (p_class->members[i].type == GDScriptParser::ClassNode::Member::FUNCTION) {
+ const GDScriptParser::FunctionNode *function = p_class->members[i].function;
+ r_funcs[function->start_line] = p_prefix.is_empty() ? String(function->identifier->name) : p_prefix + "." + String(function->identifier->name);
+ } else if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
+ String new_prefix = p_class->members[i].m_class->identifier->name;
+ get_function_names_recursively(p_class->members[i].m_class, p_prefix.is_empty() ? new_prefix : p_prefix + "." + new_prefix, r_funcs);
+ }
+ }
+}
+bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
GDScriptParser parser;
+ GDScriptAnalyzer analyzer(&parser);
- Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path, false, r_safe_lines);
+ Error err = parser.parse(p_script, p_path, false);
+ if (err == OK) {
+ err = analyzer.analyze();
+ }
#ifdef DEBUG_ENABLED
if (r_warnings) {
for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E; E = E->next()) {
const GDScriptWarning &warn = E->get();
ScriptLanguage::Warning w;
- w.line = warn.line;
+ w.start_line = warn.start_line;
+ w.end_line = warn.end_line;
+ w.leftmost_column = warn.leftmost_column;
+ w.rightmost_column = warn.rightmost_column;
w.code = (int)warn.code;
w.string_code = GDScriptWarning::get_name_from_code(warn.code);
w.message = warn.get_message();
@@ -138,81 +156,74 @@ bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &
}
#endif
if (err) {
- r_line_error = parser.get_error_line();
- r_col_error = parser.get_error_column();
- r_test_error = parser.get_error();
+ GDScriptParser::ParserError parse_error = parser.get_errors().front()->get();
+ r_line_error = parse_error.line;
+ r_col_error = parse_error.column;
+ r_test_error = parse_error.message;
return false;
} else {
-
- const GDScriptParser::Node *root = parser.get_parse_tree();
- ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, false);
-
- const GDScriptParser::ClassNode *cl = static_cast<const GDScriptParser::ClassNode *>(root);
+ const GDScriptParser::ClassNode *cl = parser.get_tree();
Map<int, String> funcs;
- for (int i = 0; i < cl->functions.size(); i++) {
-
- funcs[cl->functions[i]->line] = cl->functions[i]->name;
- }
- for (int i = 0; i < cl->static_functions.size(); i++) {
+ get_function_names_recursively(cl, "", funcs);
- funcs[cl->static_functions[i]->line] = cl->static_functions[i]->name;
+ for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) {
+ r_functions->push_back(E->get() + ":" + itos(E->key()));
}
+ }
- 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) + "." + 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;
+#ifdef DEBUG_ENABLED
+ if (r_safe_lines) {
+ const Set<int> &unsafe_lines = parser.get_unsafe_lines();
+ for (int i = 1; i <= parser.get_last_line_number(); i++) {
+ if (!unsafe_lines.has(i)) {
+ r_safe_lines->insert(i);
}
}
-
- for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) {
-
- r_functions->push_back(E->get() + ":" + itos(E->key()));
- }
}
+#endif
return true;
}
bool GDScriptLanguage::has_named_classes() const {
-
return false;
}
bool GDScriptLanguage::supports_builtin_mode() const {
+ return true;
+}
+bool GDScriptLanguage::supports_documentation() const {
return true;
}
int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const {
-
- GDScriptTokenizerText tokenizer;
- tokenizer.set_code(p_code);
+ GDScriptTokenizer tokenizer;
+ tokenizer.set_source_code(p_code);
int indent = 0;
- while (tokenizer.get_token() != GDScriptTokenizer::TK_EOF && tokenizer.get_token() != GDScriptTokenizer::TK_ERROR) {
-
- if (tokenizer.get_token() == GDScriptTokenizer::TK_NEWLINE) {
- indent = tokenizer.get_token_line_indent();
+ GDScriptTokenizer::Token current = tokenizer.scan();
+ while (current.type != GDScriptTokenizer::Token::TK_EOF && current.type != GDScriptTokenizer::Token::ERROR) {
+ if (current.type == GDScriptTokenizer::Token::INDENT) {
+ indent++;
+ } else if (current.type == GDScriptTokenizer::Token::DEDENT) {
+ indent--;
}
- if (indent == 0 && tokenizer.get_token() == GDScriptTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1) == GDScriptTokenizer::TK_IDENTIFIER) {
-
- String identifier = tokenizer.get_token_identifier(1);
- if (identifier == p_function) {
- return tokenizer.get_token_line();
+ if (indent == 0 && current.type == GDScriptTokenizer::Token::FUNC) {
+ current = tokenizer.scan();
+ if (current.is_identifier()) {
+ String identifier = current.get_identifier();
+ if (identifier == p_function) {
+ return current.start_line;
+ }
}
}
- tokenizer.advance();
+ current = tokenizer.scan();
}
return -1;
}
Script *GDScriptLanguage::create_script() const {
-
return memnew(GDScript);
}
@@ -222,7 +233,6 @@ bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const
//break because of parse error
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
-
_debug_parse_err_line = p_line;
_debug_parse_err_file = p_file;
_debug_error = p_error;
@@ -234,9 +244,7 @@ bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const
}
bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
-
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
-
_debug_parse_err_line = -1;
_debug_parse_err_file = "";
_debug_error = p_error;
@@ -249,21 +257,21 @@ bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue)
}
String GDScriptLanguage::debug_get_error() const {
-
return _debug_error;
}
int GDScriptLanguage::debug_get_stack_level_count() const {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return 1;
+ }
return _debug_call_stack_pos;
}
-int GDScriptLanguage::debug_get_stack_level_line(int p_level) const {
- if (_debug_parse_err_line >= 0)
+int GDScriptLanguage::debug_get_stack_level_line(int p_level) const {
+ if (_debug_parse_err_line >= 0) {
return _debug_parse_err_line;
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
@@ -271,28 +279,31 @@ int GDScriptLanguage::debug_get_stack_level_line(int p_level) const {
return *(_call_stack[l].line);
}
-String GDScriptLanguage::debug_get_stack_level_function(int p_level) const {
- if (_debug_parse_err_line >= 0)
+String GDScriptLanguage::debug_get_stack_level_function(int p_level) const {
+ if (_debug_parse_err_line >= 0) {
return "";
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
int l = _debug_call_stack_pos - p_level - 1;
return _call_stack[l].function->get_name();
}
-String GDScriptLanguage::debug_get_stack_level_source(int p_level) const {
- if (_debug_parse_err_line >= 0)
+String GDScriptLanguage::debug_get_stack_level_source(int p_level) const {
+ if (_debug_parse_err_line >= 0) {
return _debug_parse_err_file;
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
int l = _debug_call_stack_pos - p_level - 1;
return _call_stack[l].function->get_source();
}
-void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
- if (_debug_parse_err_line >= 0)
+void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
+ if (_debug_parse_err_line >= 0) {
return;
+ }
ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
int l = _debug_call_stack_pos - p_level - 1;
@@ -303,23 +314,24 @@ void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p
f->debug_get_stack_member_state(*_call_stack[l].line, &locals);
for (List<Pair<StringName, int>>::Element *E = locals.front(); E; E = E->next()) {
-
p_locals->push_back(E->get().first);
p_values->push_back(_call_stack[l].stack[E->get().second]);
}
}
-void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
- if (_debug_parse_err_line >= 0)
+void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
+ if (_debug_parse_err_line >= 0) {
return;
+ }
ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
int l = _debug_call_stack_pos - p_level - 1;
GDScriptInstance *instance = _call_stack[l].instance;
- if (!instance)
+ if (!instance) {
return;
+ }
Ref<GDScript> script = instance->get_script();
ERR_FAIL_COND(script.is_null());
@@ -327,16 +339,15 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *
const Map<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices();
for (const Map<StringName, GDScript::MemberInfo>::Element *E = mi.front(); E; E = E->next()) {
-
p_members->push_back(E->key());
p_values->push_back(instance->debug_get_member_by_index(E->get().index));
}
}
ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return nullptr;
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, nullptr);
@@ -347,7 +358,6 @@ ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) {
}
void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
-
const Map<StringName, int> &name_idx = GDScriptLanguage::get_singleton()->get_global_map();
const Variant *globals = GDScriptLanguage::get_singleton()->get_global_array();
@@ -355,9 +365,9 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant>
get_public_constants(&cinfo);
for (const Map<StringName, int>::Element *E = name_idx.front(); E; E = E->next()) {
-
- if (ClassDB::class_exists(E->key()) || Engine::get_singleton()->has_singleton(E->key()))
+ if (ClassDB::class_exists(E->key()) || Engine::get_singleton()->has_singleton(E->key())) {
continue;
+ }
bool is_script_constant = false;
for (List<Pair<String, Variant>>::Element *CE = cinfo.front(); CE; CE = CE->next()) {
@@ -366,24 +376,27 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant>
break;
}
}
- if (is_script_constant)
+ if (is_script_constant) {
continue;
+ }
const Variant &var = globals[E->value()];
if (Object *obj = var) {
- if (Object::cast_to<GDScriptNativeClass>(obj))
+ if (Object::cast_to<GDScriptNativeClass>(obj)) {
continue;
+ }
}
bool skip = false;
- for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
- if (E->key() == GlobalConstants::get_global_constant_name(i)) {
+ for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
+ if (E->key() == CoreConstants::get_global_constant_name(i)) {
skip = true;
break;
}
}
- if (skip)
+ if (skip) {
continue;
+ }
p_globals->push_back(E->key());
p_values->push_back(var);
@@ -391,23 +404,22 @@ void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant>
}
String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
-
return "";
}
void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("gd");
}
void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
+ List<StringName> functions;
+ GDScriptUtilityFunctions::get_function_list(&functions);
- for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
-
- p_functions->push_back(GDScriptFunctions::get_info(GDScriptFunctions::Function(i)));
+ for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) {
+ p_functions->push_back(GDScriptUtilityFunctions::get_function_info(E->get()));
}
- //not really "functions", but..
+ // Not really "functions", but show in documentation.
{
MethodInfo mi;
mi.name = "preload";
@@ -417,16 +429,6 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const
}
{
MethodInfo mi;
- mi.name = "yield";
- mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
- mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal"));
- mi.default_arguments.push_back(Variant());
- mi.default_arguments.push_back(String());
- mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "GDScriptFunctionState");
- p_functions->push_back(mi);
- }
- {
- MethodInfo mi;
mi.name = "assert";
mi.return_val.type = Variant::NIL;
mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition"));
@@ -437,7 +439,6 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const
}
void GDScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const {
-
Pair<String, Variant> pi;
pi.first = "PI";
pi.second = Math_PI;
@@ -460,7 +461,6 @@ void GDScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_const
}
String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
-
#ifdef TOOLS_ENABLED
bool th = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints");
#else
@@ -470,12 +470,13 @@ String GDScriptLanguage::make_function(const String &p_class, const String &p_na
String s = "func " + p_name + "(";
if (p_args.size()) {
for (int i = 0; i < p_args.size(); i++) {
- if (i > 0)
+ if (i > 0) {
s += ", ";
+ }
s += p_args[i].get_slice(":", 0);
if (th) {
String type = p_args[i].get_slice(":", 1);
- if (!type.empty() && type != "var") {
+ if (!type.is_empty() && type != "var") {
s += ": " + type;
}
}
@@ -488,54 +489,48 @@ String GDScriptLanguage::make_function(const String &p_class, const String &p_na
//////// COMPLETION //////////
-#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
-
-struct GDScriptCompletionContext {
-
- const GDScriptParser::ClassNode *_class;
- const GDScriptParser::FunctionNode *function;
- const GDScriptParser::BlockNode *block;
- Object *base;
- String base_path;
- int line;
- uint32_t depth;
-
- GDScriptCompletionContext() :
- _class(nullptr),
- function(nullptr),
- block(nullptr),
- base(nullptr),
- line(0),
- depth(0) {}
-};
+#ifdef TOOLS_ENABLED
+
+#define COMPLETION_RECURSION_LIMIT 200
struct GDScriptCompletionIdentifier {
GDScriptParser::DataType type;
String enumeration;
Variant value;
- const GDScriptParser::Node *assigned_expression;
-
- GDScriptCompletionIdentifier() :
- assigned_expression(nullptr) {}
+ const GDScriptParser::ExpressionNode *assigned_expression = nullptr;
};
-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++) {
- 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++) {
- _get_directory_contents(p_dir->get_subdir(i), r_list);
+// TODO: Move this to a central location (maybe core?).
+static const char *underscore_classes[] = {
+ "ClassDB",
+ "Directory",
+ "Engine",
+ "File",
+ "Geometry",
+ "GodotSharp",
+ "JSON",
+ "Marshalls",
+ "Mutex",
+ "OS",
+ "ResourceLoader",
+ "ResourceSaver",
+ "Semaphore",
+ "Thread",
+ "VisualScriptEditor",
+ nullptr,
+};
+static StringName _get_real_class_name(const StringName &p_source) {
+ const char **class_name = underscore_classes;
+ while (*class_name != nullptr) {
+ if (p_source == *class_name) {
+ return String("_") + p_source;
+ }
+ class_name++;
}
+ return p_source;
}
-static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) {
-
+static String _get_visual_datatype(const PropertyInfo &p_info, bool p_is_arg = true) {
if (p_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
String enum_name = p_info.class_name;
if (enum_name.find(".") == -1) {
@@ -558,7 +553,7 @@ static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = tr
}
}
if (p_info.type == Variant::NIL) {
- if (p_isarg || (p_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
+ if (p_is_arg || (p_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
return "Variant";
} else {
return "void";
@@ -568,11 +563,573 @@ static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = tr
return Variant::get_type_name(p_info.type);
}
+static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx, bool p_is_annotation = false) {
+ String arghint;
+ if (!p_is_annotation) {
+ arghint += _get_visual_datatype(p_info.return_val, false) + " ";
+ }
+ arghint += p_info.name + "(";
+
+ int def_args = p_info.arguments.size() - p_info.default_arguments.size();
+ int i = 0;
+ for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E; E = E->next()) {
+ if (i > 0) {
+ arghint += ", ";
+ }
+
+ if (i == p_arg_idx) {
+ arghint += String::chr(0xFFFF);
+ }
+ arghint += E->get().name + ": " + _get_visual_datatype(E->get(), true);
+
+ if (i - def_args >= 0) {
+ arghint += String(" = ") + p_info.default_arguments[i - def_args].get_construct_string();
+ }
+
+ if (i == p_arg_idx) {
+ arghint += String::chr(0xFFFF);
+ }
+
+ i++;
+ }
+
+ if (p_info.flags & METHOD_FLAG_VARARG) {
+ if (p_info.arguments.size() > 0) {
+ arghint += ", ";
+ }
+ if (p_arg_idx >= p_info.arguments.size()) {
+ arghint += String::chr(0xFFFF);
+ }
+ arghint += "...";
+ if (p_arg_idx >= p_info.arguments.size()) {
+ arghint += String::chr(0xFFFF);
+ }
+ }
+
+ arghint += ")";
+
+ return arghint;
+}
+
+static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_function, int p_arg_idx) {
+ String arghint = p_function->get_datatype().to_string() + " " + p_function->identifier->name.operator String() + "(";
+
+ for (int i = 0; i < p_function->parameters.size(); i++) {
+ if (i > 0) {
+ arghint += ", ";
+ }
+
+ if (i == p_arg_idx) {
+ arghint += String::chr(0xFFFF);
+ }
+ const GDScriptParser::ParameterNode *par = p_function->parameters[i];
+ arghint += par->identifier->name.operator String() + ": " + par->get_datatype().to_string();
+
+ if (par->default_value) {
+ String def_val = "<unknown>";
+ if (par->default_value->type == GDScriptParser::Node::LITERAL) {
+ const GDScriptParser::LiteralNode *literal = static_cast<const GDScriptParser::LiteralNode *>(par->default_value);
+ def_val = literal->value.get_construct_string();
+ } else if (par->default_value->type == GDScriptParser::Node::IDENTIFIER) {
+ const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(par->default_value);
+ def_val = id->name.operator String();
+ }
+ arghint += " = " + def_val;
+ }
+ if (i == p_arg_idx) {
+ arghint += String::chr(0xFFFF);
+ }
+ }
+
+ arghint += ")";
+
+ return arghint;
+}
+
+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++) {
+ 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++) {
+ _get_directory_contents(p_dir->get_subdir(i), r_list);
+ }
+}
+
+static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_annotation, int p_argument, const String p_quote_style, Map<String, ScriptCodeCompletionOption> &r_result) {
+ if (p_annotation->name == "@export_range" || p_annotation->name == "@export_exp_range") {
+ if (p_argument == 3 || p_argument == 4) {
+ // Slider hint.
+ ScriptCodeCompletionOption slider1("or_greater", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ slider1.insert_text = p_quote_style + slider1.display + p_quote_style;
+ r_result.insert(slider1.display, slider1);
+ ScriptCodeCompletionOption slider2("or_lesser", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ slider2.insert_text = p_quote_style + slider2.display + p_quote_style;
+ r_result.insert(slider2.display, slider2);
+ }
+ } else if (p_annotation->name == "@export_exp_easing") {
+ if (p_argument == 0 || p_argument == 1) {
+ // Easing hint.
+ ScriptCodeCompletionOption hint1("attenuation", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ hint1.insert_text = p_quote_style + hint1.display + p_quote_style;
+ r_result.insert(hint1.display, hint1);
+ ScriptCodeCompletionOption hint2("inout", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ hint2.insert_text = p_quote_style + hint2.display + p_quote_style;
+ r_result.insert(hint2.display, hint2);
+ }
+ } else if (p_annotation->name == "@export_node_path") {
+ ScriptCodeCompletionOption node("Node", ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(node.display, node);
+ List<StringName> node_types;
+ ClassDB::get_inheriters_from_class("Node", &node_types);
+ for (const List<StringName>::Element *E = node_types.front(); E != nullptr; E = E->next()) {
+ if (!ClassDB::is_class_exposed(E->get())) {
+ continue;
+ }
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+ }
+}
+
+static void _list_available_types(bool p_inherit_only, GDScriptParser::CompletionContext &p_context, Map<String, ScriptCodeCompletionOption> &r_result) {
+ List<StringName> native_types;
+ ClassDB::get_class_list(&native_types);
+ for (const List<StringName>::Element *E = native_types.front(); E != nullptr; E = E->next()) {
+ if (ClassDB::is_class_exposed(E->get()) && !Engine::get_singleton()->has_singleton(E->get())) {
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+ }
+
+ if (p_context.current_class) {
+ if (!p_inherit_only && p_context.current_class->base_type.is_set()) {
+ // Native enums from base class
+ List<StringName> enums;
+ ClassDB::get_enum_list(p_context.current_class->base_type.native_type, &enums);
+ for (const List<StringName>::Element *E = enums.front(); E != nullptr; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_ENUM);
+ r_result.insert(option.display, option);
+ }
+ }
+ // Check current class for potential types
+ const GDScriptParser::ClassNode *current = p_context.current_class;
+ while (current) {
+ for (int i = 0; i < current->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = current->members[i];
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::CLASS: {
+ ScriptCodeCompletionOption option(member.m_class->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ } break;
+ case GDScriptParser::ClassNode::Member::ENUM: {
+ if (!p_inherit_only) {
+ ScriptCodeCompletionOption option(member.m_enum->identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
+ r_result.insert(option.display, option);
+ }
+ } break;
+ case GDScriptParser::ClassNode::Member::CONSTANT: {
+ if (member.constant->get_datatype().is_meta_type && p_context.current_class->outer != nullptr) {
+ ScriptCodeCompletionOption option(member.constant->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+ } break;
+ default:
+ break;
+ }
+ }
+ current = current->outer;
+ }
+ }
+
+ // Global scripts
+ List<StringName> global_classes;
+ ScriptServer::get_global_class_list(&global_classes);
+ for (const List<StringName>::Element *E = global_classes.front(); E != nullptr; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+
+ // Autoload singletons
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+ for (const Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E != nullptr; E = E->next()) {
+ const ProjectSettings::AutoloadInfo &info = E->get();
+ if (!info.is_singleton || info.path.get_extension().to_lower() != "gd") {
+ continue;
+ }
+ ScriptCodeCompletionOption option(info.name, ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+}
+
+static void _find_identifiers_in_suite(const GDScriptParser::SuiteNode *p_suite, Map<String, ScriptCodeCompletionOption> &r_result) {
+ for (int i = 0; i < p_suite->locals.size(); i++) {
+ ScriptCodeCompletionOption option(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_VARIABLE);
+ r_result.insert(option.display, option);
+ }
+ if (p_suite->parent_block) {
+ _find_identifiers_in_suite(p_suite->parent_block, r_result);
+ }
+}
+
+static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth);
+
+static void _find_identifiers_in_class(const GDScriptParser::ClassNode *p_class, bool p_only_functions, bool p_static, bool p_parent_only, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
+ ERR_FAIL_COND(p_recursion_depth > COMPLETION_RECURSION_LIMIT);
+
+ if (!p_parent_only) {
+ bool outer = false;
+ const GDScriptParser::ClassNode *clss = p_class;
+ while (clss) {
+ for (int i = 0; i < clss->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = clss->members[i];
+ ScriptCodeCompletionOption option;
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::VARIABLE:
+ if (p_only_functions || outer || (p_static)) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.variable->identifier->name, ScriptCodeCompletionOption::KIND_MEMBER);
+ break;
+ case GDScriptParser::ClassNode::Member::CONSTANT:
+ if (p_only_functions) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.constant->identifier->name, ScriptCodeCompletionOption::KIND_CONSTANT);
+ if (member.constant->initializer) {
+ option.default_value = member.constant->initializer->reduced_value;
+ }
+ break;
+ case GDScriptParser::ClassNode::Member::CLASS:
+ if (p_only_functions) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.m_class->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
+ break;
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE:
+ if (p_only_functions) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.enum_value.identifier->name, ScriptCodeCompletionOption::KIND_CONSTANT);
+ break;
+ case GDScriptParser::ClassNode::Member::ENUM:
+ if (p_only_functions) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.m_enum->identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
+ break;
+ case GDScriptParser::ClassNode::Member::FUNCTION:
+ if (outer || (p_static && !member.function->is_static) || member.function->identifier->name.operator String().begins_with("@")) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.function->identifier->name, ScriptCodeCompletionOption::KIND_FUNCTION);
+ if (member.function->parameters.size() > 0) {
+ option.insert_text += "(";
+ } else {
+ option.insert_text += "()";
+ }
+ break;
+ case GDScriptParser::ClassNode::Member::SIGNAL:
+ if (p_only_functions || outer) {
+ continue;
+ }
+ option = ScriptCodeCompletionOption(member.signal->identifier->name, ScriptCodeCompletionOption::KIND_SIGNAL);
+ break;
+ case GDScriptParser::ClassNode::Member::UNDEFINED:
+ break;
+ }
+ r_result.insert(option.display, option);
+ }
+ outer = true;
+ clss = clss->outer;
+ }
+ }
+
+ // Parents.
+ GDScriptCompletionIdentifier base_type;
+ base_type.type = p_class->base_type;
+ base_type.type.is_meta_type = p_static;
+
+ _find_identifiers_in_base(base_type, p_only_functions, r_result, p_recursion_depth + 1);
+}
+
+static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
+ ERR_FAIL_COND(p_recursion_depth > COMPLETION_RECURSION_LIMIT);
+
+ GDScriptParser::DataType base_type = p_base.type;
+ bool _static = base_type.is_meta_type;
+
+ if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) {
+ ScriptCodeCompletionOption option("new", ScriptCodeCompletionOption::KIND_FUNCTION);
+ option.insert_text += "(";
+ r_result.insert(option.display, option);
+ }
+
+ while (!base_type.has_no_type()) {
+ switch (base_type.kind) {
+ case GDScriptParser::DataType::CLASS: {
+ _find_identifiers_in_class(base_type.class_type, p_only_functions, _static, false, r_result, p_recursion_depth + 1);
+ // This already finds all parent identifiers, so we are done.
+ base_type = GDScriptParser::DataType();
+ } break;
+ case GDScriptParser::DataType::SCRIPT: {
+ Ref<Script> scr = base_type.script_type;
+ if (scr.is_valid()) {
+ if (!p_only_functions) {
+ if (!_static) {
+ List<PropertyInfo> members;
+ scr->get_script_property_list(&members);
+ for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
+ }
+ }
+ Map<StringName, Variant> constants;
+ scr->get_constants(&constants);
+ for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
+ }
+
+ List<MethodInfo> signals;
+ scr->get_script_signal_list(&signals);
+ for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL);
+ 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()) {
+ if (E->get().name.begins_with("@")) {
+ continue;
+ }
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
+ if (E->get().arguments.size()) {
+ option.insert_text += "(";
+ } else {
+ option.insert_text += "()";
+ }
+ r_result.insert(option.display, option);
+ }
+
+ Ref<Script> base_script = scr->get_base_script();
+ if (base_script.is_valid()) {
+ base_type.script_type = base_script;
+ } else {
+ base_type.kind = GDScriptParser::DataType::NATIVE;
+ base_type.native_type = scr->get_instance_base_type();
+ }
+ } else {
+ return;
+ }
+ } break;
+ case GDScriptParser::DataType::NATIVE: {
+ StringName type = _get_real_class_name(base_type.native_type);
+ if (!ClassDB::class_exists(type)) {
+ return;
+ }
+
+ if (!p_only_functions) {
+ List<String> constants;
+ ClassDB::get_integer_constant_list(type, &constants);
+ for (List<String>::Element *E = constants.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
+ }
+
+ if (!_static || Engine::get_singleton()->has_singleton(type)) {
+ List<PropertyInfo> pinfo;
+ ClassDB::get_property_list(type, &pinfo);
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) {
+ continue;
+ }
+ if (E->get().name.find("/") != -1) {
+ continue;
+ }
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
+ }
+ }
+ }
+
+ if (!_static || Engine::get_singleton()->has_singleton(type)) {
+ List<MethodInfo> methods;
+ bool is_autocompleting_getters = GLOBAL_GET("debug/gdscript/completion/autocomplete_setters_and_getters").booleanize();
+ ClassDB::get_method_list(type, &methods, false, !is_autocompleting_getters);
+ for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
+ if (E->get().name.begins_with("_")) {
+ continue;
+ }
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
+ if (E->get().arguments.size()) {
+ option.insert_text += "(";
+ } else {
+ option.insert_text += "()";
+ }
+ r_result.insert(option.display, option);
+ }
+ }
+
+ return;
+ } break;
+ case GDScriptParser::DataType::BUILTIN: {
+ Callable::CallError err;
+ Variant tmp;
+ Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
+ if (err.error != Callable::CallError::CALL_OK) {
+ return;
+ }
+
+ if (!p_only_functions) {
+ List<PropertyInfo> members;
+ if (p_base.value.get_type() != Variant::NIL) {
+ p_base.value.get_property_list(&members);
+ } else {
+ tmp.get_property_list(&members);
+ }
+
+ for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
+ if (String(E->get().name).find("/") == -1) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
+ }
+ }
+ }
+
+ List<MethodInfo> methods;
+ tmp.get_method_list(&methods);
+ for (const List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
+ if (E->get().arguments.size()) {
+ option.insert_text += "(";
+ } else {
+ option.insert_text += "()";
+ }
+ r_result.insert(option.display, option);
+ }
+
+ return;
+ } break;
+ default: {
+ return;
+ } break;
+ }
+ }
+}
+
+static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
+ if (!p_only_functions && p_context.current_suite) {
+ // This includes function parameters, since they are also locals.
+ _find_identifiers_in_suite(p_context.current_suite, r_result);
+ }
+
+ if (p_context.current_class) {
+ _find_identifiers_in_class(p_context.current_class, p_only_functions, (!p_context.current_function || p_context.current_function->is_static), false, r_result, p_recursion_depth + 1);
+ }
+
+ List<StringName> functions;
+ GDScriptUtilityFunctions::get_function_list(&functions);
+
+ for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) {
+ MethodInfo function = GDScriptUtilityFunctions::get_function_info(E->get());
+ ScriptCodeCompletionOption option(String(E->get()), ScriptCodeCompletionOption::KIND_FUNCTION);
+ if (function.arguments.size() || (function.flags & METHOD_FLAG_VARARG)) {
+ option.insert_text += "(";
+ } else {
+ option.insert_text += "()";
+ }
+ r_result.insert(option.display, option);
+ }
+
+ if (p_only_functions) {
+ return;
+ }
+
+ static const char *_type_names[Variant::VARIANT_MAX] = {
+ "null", "bool", "int", "float", "String", "StringName", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quat", "AABB", "Basis", "Transform",
+ "Color", "NodePath", "RID", "Signal", "Callable", "Object", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray",
+ "PackedVector2Array", "PackedVector3Array", "PackedColorArray"
+ };
+ static_assert((sizeof(_type_names) / sizeof(*_type_names)) == Variant::VARIANT_MAX, "Completion for builtin types is incomplete");
+
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ ScriptCodeCompletionOption option(_type_names[i], ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
+ }
+
+ static const char *_keywords[] = {
+ "false", "PI", "TAU", "INF", "NAN", "self", "true", "breakpoint", "tool", "super",
+ "break", "continue", "pass", "return",
+ 0
+ };
+
+ const char **kw = _keywords;
+ while (*kw) {
+ ScriptCodeCompletionOption option(*kw, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ r_result.insert(option.display, option);
+ kw++;
+ }
+
+ static const char *_keywords_with_space[] = {
+ "and", "in", "not", "or", "as", "class", "extends", "is", "func", "signal", "await",
+ "const", "enum", "static", "var", "if", "elif", "else", "for", "match", "while",
+ 0
+ };
+
+ const char **kws = _keywords_with_space;
+ while (*kws) {
+ ScriptCodeCompletionOption option(*kws, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ option.insert_text += " ";
+ r_result.insert(option.display, option);
+ kws++;
+ }
+
+ static const char *_keywords_with_args[] = {
+ "assert", "preload",
+ 0
+ };
+
+ const char **kwa = _keywords_with_args;
+ while (*kwa) {
+ ScriptCodeCompletionOption option(*kwa, ScriptCodeCompletionOption::KIND_FUNCTION);
+ option.insert_text += "(";
+ r_result.insert(option.display, option);
+ kwa++;
+ }
+
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+ for (const Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E != nullptr; E = E->next()) {
+ if (!E->value().is_singleton) {
+ continue;
+ }
+ ScriptCodeCompletionOption option(E->key(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
+ }
+
+ // Native classes and global constants.
+ for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option;
+ if (ClassDB::class_exists(E->key()) || Engine::get_singleton()->has_singleton(E->key())) {
+ option = ScriptCodeCompletionOption(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ } else {
+ option = ScriptCodeCompletionOption(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ }
+ r_result.insert(option.display, option);
+ }
+}
+
static GDScriptCompletionIdentifier _type_from_variant(const Variant &p_value) {
GDScriptCompletionIdentifier ci;
ci.value = p_value;
ci.type.is_constant = true;
- ci.type.has_type = true;
+ ci.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
ci.type.kind = GDScriptParser::DataType::BUILTIN;
ci.type.builtin_type = p_value.get_type();
@@ -591,12 +1148,7 @@ static GDScriptCompletionIdentifier _type_from_variant(const Variant &p_value) {
}
if (scr.is_valid()) {
ci.type.script_type = scr;
- Ref<GDScript> gds = scr;
- if (gds.is_valid()) {
- ci.type.kind = GDScriptParser::DataType::GDSCRIPT;
- } else {
- ci.type.kind = GDScriptParser::DataType::SCRIPT;
- }
+ ci.type.kind = GDScriptParser::DataType::SCRIPT;
ci.type.native_type = scr->get_instance_base_type();
} else {
ci.type.kind = GDScriptParser::DataType::NATIVE;
@@ -618,7 +1170,7 @@ static GDScriptCompletionIdentifier _type_from_property(const PropertyInfo &p_pr
ci.enumeration = p_property.class_name;
}
- ci.type.has_type = true;
+ ci.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
ci.type.builtin_type = p_property.type;
if (p_property.type == Variant::OBJECT) {
ci.type.kind = GDScriptParser::DataType::NATIVE;
@@ -629,346 +1181,292 @@ static GDScriptCompletionIdentifier _type_from_property(const PropertyInfo &p_pr
return ci;
}
-static GDScriptCompletionIdentifier _type_from_gdtype(const GDScriptDataType &p_gdtype) {
- GDScriptCompletionIdentifier ci;
- if (!p_gdtype.has_type) {
- return ci;
- }
-
- ci.type.has_type = true;
- ci.type.builtin_type = p_gdtype.builtin_type;
- ci.type.native_type = p_gdtype.native_type;
- ci.type.script_type = p_gdtype.script_type;
+static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
+static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
+static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type);
- switch (p_gdtype.kind) {
- case GDScriptDataType::UNINITIALIZED: {
- ERR_PRINT("Uninitialized completion. Please report a bug.");
- } break;
- case GDScriptDataType::BUILTIN: {
- ci.type.kind = GDScriptParser::DataType::BUILTIN;
- } break;
- case GDScriptDataType::NATIVE: {
- ci.type.kind = GDScriptParser::DataType::NATIVE;
- } break;
- case GDScriptDataType::GDSCRIPT: {
- ci.type.kind = GDScriptParser::DataType::GDSCRIPT;
- } break;
- case GDScriptDataType::SCRIPT: {
- ci.type.kind = GDScriptParser::DataType::SCRIPT;
- } break;
- }
- return ci;
-}
-
-static bool _guess_identifier_type(GDScriptCompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
-static bool _guess_identifier_type_from_base(GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
-static bool _guess_method_return_type_from_base(GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type);
-
-static bool _guess_expression_type(GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_expression, GDScriptCompletionIdentifier &r_type) {
+static bool _guess_expression_type(GDScriptParser::CompletionContext &p_context, const GDScriptParser::ExpressionNode *p_expression, GDScriptCompletionIdentifier &r_type) {
bool found = false;
- if (++p_context.depth > 100) {
- print_error("Maximum _guess_expression_type depth limit reached. Please file a bugreport.");
- return false;
- }
-
- switch (p_expression->type) {
- case GDScriptParser::Node::TYPE_CONSTANT: {
- const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(p_expression);
- r_type = _type_from_variant(cn->value);
- found = true;
- } break;
- case GDScriptParser::Node::TYPE_SELF: {
- if (p_context._class) {
- r_type.type.has_type = true;
- r_type.type.kind = GDScriptParser::DataType::CLASS;
- r_type.type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class);
- r_type.type.is_constant = true;
- r_type.value = p_context.base;
+ if (p_expression->is_constant) {
+ // Already has a value, so just use that.
+ r_type = _type_from_variant(p_expression->reduced_value);
+ found = true;
+ } else {
+ switch (p_expression->type) {
+ case GDScriptParser::Node::LITERAL: {
+ const GDScriptParser::LiteralNode *literal = static_cast<const GDScriptParser::LiteralNode *>(p_expression);
+ r_type = _type_from_variant(literal->value);
found = true;
- }
- } break;
- case GDScriptParser::Node::TYPE_IDENTIFIER: {
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
- found = _guess_identifier_type(p_context, id->name, r_type);
- } break;
- case GDScriptParser::Node::TYPE_DICTIONARY: {
- // Try to recreate the dictionary
- const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
- Dictionary d;
- bool full = true;
- for (int i = 0; i < dn->elements.size(); i++) {
- GDScriptCompletionIdentifier key;
- if (_guess_expression_type(p_context, dn->elements[i].key, key)) {
- GDScriptCompletionIdentifier value;
- if (_guess_expression_type(p_context, dn->elements[i].value, value)) {
- if (!value.type.is_constant) {
+ } break;
+ case GDScriptParser::Node::SELF: {
+ if (p_context.current_class) {
+ r_type.type.kind = GDScriptParser::DataType::CLASS;
+ r_type.type.type_source = GDScriptParser::DataType::INFERRED;
+ r_type.type.is_constant = true;
+ r_type.type.class_type = p_context.current_class;
+ r_type.value = p_context.base;
+ found = true;
+ }
+ } break;
+ case GDScriptParser::Node::IDENTIFIER: {
+ const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
+ found = _guess_identifier_type(p_context, id->name, r_type);
+ } break;
+ case GDScriptParser::Node::DICTIONARY: {
+ // Try to recreate the dictionary.
+ const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
+ Dictionary d;
+ bool full = true;
+ for (int i = 0; i < dn->elements.size(); i++) {
+ GDScriptCompletionIdentifier key;
+ if (_guess_expression_type(p_context, dn->elements[i].key, key)) {
+ if (!key.type.is_constant) {
+ full = false;
+ break;
+ }
+ GDScriptCompletionIdentifier value;
+ if (_guess_expression_type(p_context, dn->elements[i].value, value)) {
+ if (!value.type.is_constant) {
+ full = false;
+ break;
+ }
+ d[key.value] = value.value;
+ } else {
full = false;
break;
}
- d[key.value] = value.value;
} else {
full = false;
break;
}
- } else {
- full = false;
- break;
}
- }
- if (full) {
- // If not fully constant, setting this value is detrimental to the inference
- r_type.value = d;
- r_type.type.is_constant = true;
- }
- r_type.type.has_type = true;
- r_type.type.kind = GDScriptParser::DataType::BUILTIN;
- r_type.type.builtin_type = Variant::DICTIONARY;
- } break;
- case GDScriptParser::Node::TYPE_ARRAY: {
- // Try to recreate the array
- const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
- Array a;
- bool full = true;
- a.resize(an->elements.size());
- for (int i = 0; i < an->elements.size(); i++) {
- GDScriptCompletionIdentifier value;
- if (_guess_expression_type(p_context, an->elements[i], value)) {
- a[i] = value.value;
- } else {
- full = false;
- break;
+ if (full) {
+ r_type.value = d;
+ r_type.type.is_constant = true;
}
- }
- if (full) {
- // If not fully constant, setting this value is detrimental to the inference
- r_type.value = a;
- }
- r_type.type.has_type = true;
- r_type.type.kind = GDScriptParser::DataType::BUILTIN;
- r_type.type.builtin_type = Variant::ARRAY;
- } break;
- case GDScriptParser::Node::TYPE_CAST: {
- const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
- GDScriptCompletionIdentifier value;
- if (_guess_expression_type(p_context, cn->source_node, r_type)) {
- r_type.type = cn->get_datatype();
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::BUILTIN;
+ r_type.type.builtin_type = Variant::DICTIONARY;
found = true;
- }
- } break;
- case GDScriptParser::Node::TYPE_OPERATOR: {
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_expression);
- switch (op->op) {
- case GDScriptParser::OperatorNode::OP_CALL: {
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) {
- const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]);
- r_type.type.has_type = true;
- r_type.type.kind = GDScriptParser::DataType::BUILTIN;
- r_type.type.builtin_type = tn->vtype;
- found = true;
- break;
- } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) {
- const GDScriptParser::BuiltInFunctionNode *bin = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]);
- MethodInfo mi = GDScriptFunctions::get_info(bin->function);
- r_type = _type_from_property(mi.return_val);
- found = true;
+ } break;
+ case GDScriptParser::Node::ARRAY: {
+ // Try to recreate the array
+ const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
+ Array a;
+ bool full = true;
+ a.resize(an->elements.size());
+ for (int i = 0; i < an->elements.size(); i++) {
+ GDScriptCompletionIdentifier value;
+ if (_guess_expression_type(p_context, an->elements[i], value)) {
+ if (value.type.is_constant) {
+ a[i] = value.value;
+ } else {
+ full = false;
+ break;
+ }
+ } else {
+ full = false;
break;
- } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) {
- StringName id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name;
+ }
+ }
+ if (full) {
+ // If not fully constant, setting this value is detrimental to the inference.
+ r_type.value = a;
+ }
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::BUILTIN;
+ r_type.type.builtin_type = Variant::ARRAY;
+ found = true;
+ } break;
+ case GDScriptParser::Node::CAST: {
+ const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
+ GDScriptCompletionIdentifier value;
+ if (_guess_expression_type(p_context, cn->operand, r_type)) {
+ r_type.type = cn->get_datatype();
+ found = true;
+ }
+ } break;
+ case GDScriptParser::Node::CALL: {
+ const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);
+ if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) {
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::BUILTIN;
+ r_type.type.builtin_type = GDScriptParser::get_builtin_type(call->function_name);
+ found = true;
+ break;
+ } else if (GDScriptUtilityFunctions::function_exists(call->function_name)) {
+ MethodInfo mi = GDScriptUtilityFunctions::get_function_info(call->function_name);
+ r_type = _type_from_property(mi.return_val);
+ found = true;
+ break;
+ } else {
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_line = call->start_line;
- GDScriptCompletionContext c = p_context;
- c.line = op->line;
+ GDScriptParser::Node::Type callee_type = call->get_callee_type();
- GDScriptCompletionIdentifier base;
- if (!_guess_expression_type(c, op->arguments[0], base)) {
+ GDScriptCompletionIdentifier base;
+ if (callee_type == GDScriptParser::Node::IDENTIFIER || call->is_super) {
+ // Simple call, so base is 'self'.
+ if (p_context.current_class) {
+ base.type.kind = GDScriptParser::DataType::CLASS;
+ base.type.type_source = GDScriptParser::DataType::INFERRED;
+ base.type.is_constant = true;
+ base.type.class_type = p_context.current_class;
+ base.value = p_context.base;
+ } else {
+ break;
+ }
+ } else if (callee_type == GDScriptParser::Node::SUBSCRIPT && static_cast<const GDScriptParser::SubscriptNode *>(call->callee)->is_attribute) {
+ if (!_guess_expression_type(c, static_cast<const GDScriptParser::SubscriptNode *>(call->callee)->base, base)) {
found = false;
break;
}
+ } else {
+ break;
+ }
- // Try call if constant methods with constant arguments
- if (base.type.is_constant && base.value.get_type() == Variant::OBJECT) {
- GDScriptParser::DataType native_type = base.type;
+ // Try call if constant methods with constant arguments
+ if (base.type.is_constant && base.value.get_type() == Variant::OBJECT) {
+ GDScriptParser::DataType native_type = base.type;
- while (native_type.kind == GDScriptParser::DataType::CLASS) {
- native_type = native_type.class_type->base_type;
- }
+ while (native_type.kind == GDScriptParser::DataType::CLASS) {
+ native_type = native_type.class_type->base_type;
+ }
- while (native_type.kind == GDScriptParser::DataType::GDSCRIPT || native_type.kind == GDScriptParser::DataType::SCRIPT) {
- if (native_type.script_type.is_valid()) {
- Ref<Script> parent = native_type.script_type->get_base_script();
- if (parent.is_valid()) {
- native_type.script_type = parent;
- } else {
- native_type.kind = GDScriptParser::DataType::NATIVE;
- native_type.native_type = native_type.script_type->get_instance_base_type();
+ while (native_type.kind == GDScriptParser::DataType::SCRIPT) {
+ if (native_type.script_type.is_valid()) {
+ Ref<Script> parent = native_type.script_type->get_base_script();
+ if (parent.is_valid()) {
+ native_type.script_type = parent;
+ } else {
+ native_type.kind = GDScriptParser::DataType::NATIVE;
+ native_type.native_type = native_type.script_type->get_instance_base_type();
+ if (!ClassDB::class_exists(native_type.native_type)) {
+ native_type.native_type = String("_") + native_type.native_type;
if (!ClassDB::class_exists(native_type.native_type)) {
- native_type.native_type = String("_") + native_type.native_type;
- if (!ClassDB::class_exists(native_type.native_type)) {
- native_type.has_type = false;
- }
+ native_type.kind = GDScriptParser::DataType::UNRESOLVED;
}
}
}
}
+ }
- if (native_type.has_type && native_type.kind == GDScriptParser::DataType::NATIVE) {
- MethodBind *mb = ClassDB::get_method(native_type.native_type, id);
- if (mb && mb->is_const()) {
- bool all_is_const = true;
- Vector<Variant> args;
- GDScriptCompletionContext c2 = p_context;
- c2.line = op->line;
- for (int i = 2; all_is_const && i < op->arguments.size(); i++) {
- GDScriptCompletionIdentifier arg;
-
- if (_guess_expression_type(c2, op->arguments[i], arg)) {
- if (arg.type.has_type && arg.type.is_constant && arg.value.get_type() != Variant::OBJECT) {
- args.push_back(arg.value);
- } else {
- all_is_const = false;
- }
- } else {
- all_is_const = false;
- }
+ if (native_type.kind == GDScriptParser::DataType::NATIVE) {
+ MethodBind *mb = ClassDB::get_method(native_type.native_type, call->function_name);
+ if (mb && mb->is_const()) {
+ bool all_is_const = true;
+ Vector<Variant> args;
+ GDScriptParser::CompletionContext c2 = p_context;
+ c2.current_line = call->start_line;
+ for (int i = 0; all_is_const && i < call->arguments.size(); i++) {
+ GDScriptCompletionIdentifier arg;
+
+ if (!call->arguments[i]->is_constant) {
+ all_is_const = false;
}
+ }
- Object *baseptr = base.value;
-
- if (all_is_const && String(id) == "get_node" && ClassDB::is_parent_class(native_type.native_type, "Node") && args.size()) {
+ Object *baseptr = base.value;
- String arg1 = args[0];
- if (arg1.begins_with("/root/")) {
- String which = arg1.get_slice("/", 2);
- if (which != "") {
- // Try singletons first
- if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(which)) {
- r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[which]);
- found = true;
- } else {
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
+ if (all_is_const && String(call->function_name) == "get_node" && ClassDB::is_parent_class(native_type.native_type, "Node") && args.size()) {
+ String arg1 = args[0];
+ if (arg1.begins_with("/root/")) {
+ String which = arg1.get_slice("/", 2);
+ if (which != "") {
+ // Try singletons first
+ if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(which)) {
+ r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[which]);
+ found = true;
+ } else {
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ String name = E->key();
+ if (name == which) {
+ String script = E->value().path;
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
+ if (!script.begins_with("res://")) {
+ script = "res://" + script;
}
- String name = s.get_slice("/", 1);
- if (name == which) {
- String script = ProjectSettings::get_singleton()->get(s);
-
- if (script.begins_with("*")) {
- script = script.right(1);
- }
- if (!script.begins_with("res://")) {
- script = "res://" + script;
- }
-
- if (!script.ends_with(".gd")) {
- //not a script, try find the script anyway,
- //may have some success
- script = script.get_basename() + ".gd";
- }
+ if (!script.ends_with(".gd")) {
+ //not a script, try find the script anyway,
+ //may have some success
+ script = script.get_basename() + ".gd";
+ }
- if (FileAccess::exists(script)) {
- Ref<Script> scr;
- if (ScriptCodeCompletionCache::get_singleton()) {
- scr = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(script);
- } else {
- scr = ResourceLoader::load(script);
- }
- if (scr.is_valid()) {
- r_type.type.has_type = true;
- r_type.type.script_type = scr;
- r_type.type.is_constant = false;
- Ref<GDScript> gds = scr;
- if (gds.is_valid()) {
- r_type.type.kind = GDScriptParser::DataType::GDSCRIPT;
- } else {
- r_type.type.kind = GDScriptParser::DataType::SCRIPT;
- }
- r_type.value = Variant();
- found = true;
- }
+ if (FileAccess::exists(script)) {
+ Error err = OK;
+ Ref<GDScriptParserRef> parser = GDScriptCache::get_parser(script, GDScriptParserRef::INTERFACE_SOLVED, err);
+ if (err == OK) {
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.script_path = script;
+ r_type.type.class_type = parser->get_parser()->get_tree();
+ r_type.type.is_constant = false;
+ r_type.type.kind = GDScriptParser::DataType::CLASS;
+ r_type.value = Variant();
+ p_context.dependent_parsers.push_back(parser);
+ found = true;
}
- break;
}
+ break;
}
}
}
}
}
+ }
- if (!found && all_is_const && baseptr) {
- Vector<const Variant *> argptr;
- for (int i = 0; i < args.size(); i++) {
- argptr.push_back(&args[i]);
- }
+ if (!found && all_is_const && baseptr) {
+ Vector<const Variant *> argptr;
+ for (int i = 0; i < args.size(); i++) {
+ argptr.push_back(&args[i]);
+ }
- Callable::CallError ce;
- Variant ret = mb->call(baseptr, (const Variant **)argptr.ptr(), argptr.size(), ce);
+ Callable::CallError ce;
+ Variant ret = mb->call(baseptr, (const Variant **)argptr.ptr(), argptr.size(), ce);
- if (ce.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
- if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != nullptr) {
- r_type = _type_from_variant(ret);
- found = true;
- }
+ if (ce.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
+ if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != nullptr) {
+ r_type = _type_from_variant(ret);
+ found = true;
}
}
}
}
}
-
- if (!found) {
- found = _guess_method_return_type_from_base(c, base, id, r_type);
- }
}
- } break;
- case GDScriptParser::OperatorNode::OP_PARENT_CALL: {
- if (!p_context._class || !op->arguments.size() || op->arguments[0]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- break;
- }
-
- StringName id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name;
-
- GDScriptCompletionIdentifier base;
- base.value = p_context.base;
- base.type = p_context._class->base_type;
- GDScriptCompletionContext c = p_context;
- c.line = op->line;
-
- found = _guess_method_return_type_from_base(c, base, id, r_type);
- } break;
- case GDScriptParser::OperatorNode::OP_INDEX_NAMED: {
- if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- found = false;
- break;
+ if (!found) {
+ found = _guess_method_return_type_from_base(c, base, call->function_name, r_type);
}
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]);
-
- GDScriptCompletionContext c = p_context;
- c.line = op->line;
+ }
+ } break;
+ case GDScriptParser::Node::SUBSCRIPT: {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
+ if (subscript->is_attribute) {
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_line = subscript->start_line;
GDScriptCompletionIdentifier base;
- if (!_guess_expression_type(c, op->arguments[0], base)) {
+ if (!_guess_expression_type(c, subscript->base, base)) {
found = false;
break;
}
- if (base.value.get_type() == Variant::DICTIONARY && base.value.operator Dictionary().has(String(id->name))) {
- Variant value = base.value.operator Dictionary()[String(id->name)];
+ if (base.value.get_type() == Variant::DICTIONARY && base.value.operator Dictionary().has(String(subscript->attribute->name))) {
+ Variant value = base.value.operator Dictionary()[String(subscript->attribute->name)];
r_type = _type_from_variant(value);
found = true;
break;
}
const GDScriptParser::DictionaryNode *dn = nullptr;
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_DICTIONARY) {
- dn = static_cast<const GDScriptParser::DictionaryNode *>(op->arguments[0]);
- } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_DICTIONARY) {
+ if (subscript->base->type == GDScriptParser::Node::DICTIONARY) {
+ dn = static_cast<const GDScriptParser::DictionaryNode *>(subscript->base);
+ } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::DICTIONARY) {
dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression);
}
@@ -978,7 +1476,7 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
if (!_guess_expression_type(c, dn->elements[i].key, key)) {
continue;
}
- if (key.value == String(id->name)) {
+ if (key.value == String(subscript->attribute->name)) {
r_type.assigned_expression = dn->elements[i].value;
found = _guess_expression_type(c, dn->elements[i].value, r_type);
break;
@@ -987,26 +1485,25 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
}
if (!found) {
- found = _guess_identifier_type_from_base(c, base, id->name, r_type);
+ found = _guess_identifier_type_from_base(c, base, subscript->attribute->name, r_type);
}
- } break;
- case GDScriptParser::OperatorNode::OP_INDEX: {
- if (op->arguments.size() < 2) {
+ } else {
+ if (subscript->index == nullptr) {
found = false;
break;
}
- GDScriptCompletionContext c = p_context;
- c.line = op->line;
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_line = subscript->start_line;
GDScriptCompletionIdentifier base;
- if (!_guess_expression_type(c, op->arguments[0], base)) {
+ if (!_guess_expression_type(c, subscript->base, base)) {
found = false;
break;
}
GDScriptCompletionIdentifier index;
- if (!_guess_expression_type(c, op->arguments[1], index)) {
+ if (!_guess_expression_type(c, subscript->index, index)) {
found = false;
break;
}
@@ -1018,11 +1515,11 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
break;
}
- // Look if it is a dictionary node
+ // Look if it is a dictionary node.
const GDScriptParser::DictionaryNode *dn = nullptr;
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_DICTIONARY) {
- dn = static_cast<const GDScriptParser::DictionaryNode *>(op->arguments[0]);
- } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_DICTIONARY) {
+ if (subscript->base->type == GDScriptParser::Node::DICTIONARY) {
+ dn = static_cast<const GDScriptParser::DictionaryNode *>(subscript->base);
+ } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::DICTIONARY) {
dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression);
}
@@ -1040,13 +1537,13 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
}
}
- // Look if it is an array node
+ // Look if it is an array node.
if (!found && index.value.is_num()) {
int idx = index.value;
const GDScriptParser::ArrayNode *an = nullptr;
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_ARRAY) {
- an = static_cast<const GDScriptParser::ArrayNode *>(op->arguments[0]);
- } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::TYPE_ARRAY) {
+ if (subscript->base->type == GDScriptParser::Node::ARRAY) {
+ an = static_cast<const GDScriptParser::ArrayNode *>(subscript->base);
+ } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::ARRAY) {
an = static_cast<const GDScriptParser::ArrayNode *>(base.assigned_expression);
}
@@ -1063,7 +1560,8 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
found = _guess_identifier_type_from_base(c, base, id, r_type);
} else if (!found && index.type.kind == GDScriptParser::DataType::BUILTIN) {
Callable::CallError err;
- Variant base_val = Variant::construct(base.type.builtin_type, nullptr, 0, err);
+ Variant base_val;
+ Variant::construct(base.type.builtin_type, base_val, nullptr, 0, err);
bool valid = false;
Variant res = base_val.get(index.value, &valid);
if (valid) {
@@ -1073,93 +1571,79 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
found = true;
}
}
- } break;
- default: {
- if (op->arguments.size() < 2) {
- found = false;
- break;
- }
+ }
+ } break;
+ case GDScriptParser::Node::BINARY_OPERATOR: {
+ const GDScriptParser::BinaryOpNode *op = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
- Variant::Operator vop = Variant::OP_MAX;
- switch (op->op) {
- case GDScriptParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break;
- case GDScriptParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBTRACT; break;
- case GDScriptParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break;
- case GDScriptParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break;
- case GDScriptParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break;
- case GDScriptParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break;
- case GDScriptParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break;
- case GDScriptParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break;
- case GDScriptParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break;
- case GDScriptParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break;
- default: {
- }
- }
+ if (op->variant_op == Variant::OP_MAX) {
+ break;
+ }
- if (vop == Variant::OP_MAX) {
- break;
- }
+ GDScriptParser::CompletionContext context = p_context;
+ context.current_line = op->start_line;
- GDScriptCompletionContext context = p_context;
- context.line = op->line;
+ GDScriptCompletionIdentifier p1;
+ GDScriptCompletionIdentifier p2;
- GDScriptCompletionIdentifier p1;
- GDScriptCompletionIdentifier p2;
+ if (!_guess_expression_type(context, op->left_operand, p1)) {
+ found = false;
+ break;
+ }
- if (!_guess_expression_type(context, op->arguments[0], p1)) {
- found = false;
- break;
- }
+ if (!_guess_expression_type(context, op->right_operand, p2)) {
+ found = false;
+ break;
+ }
- if (!_guess_expression_type(context, op->arguments[1], p2)) {
- found = false;
- break;
- }
+ Callable::CallError ce;
+ bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT;
+ Variant d1;
+ Variant::construct(p1.type.builtin_type, d1, nullptr, 0, ce);
+ Variant d2;
+ Variant::construct(p2.type.builtin_type, d2, nullptr, 0, ce);
- Callable::CallError ce;
- bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT;
- Variant v1 = (v1_use_value) ? p1.value : Variant::construct(p1.type.builtin_type, nullptr, 0, ce);
- bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT;
- Variant v2 = (v2_use_value) ? p2.value : Variant::construct(p2.type.builtin_type, nullptr, 0, ce);
- // avoid potential invalid ops
- if ((vop == Variant::OP_DIVIDE || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) {
- v2 = 1;
- v2_use_value = false;
- }
- if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::FLOAT) {
- v2 = 1.0;
- v2_use_value = false;
- }
+ Variant v1 = (v1_use_value) ? p1.value : d1;
+ bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT;
+ Variant v2 = (v2_use_value) ? p2.value : d2;
+ // avoid potential invalid ops
+ if ((op->variant_op == Variant::OP_DIVIDE || op->variant_op == Variant::OP_MODULE) && v2.get_type() == Variant::INT) {
+ v2 = 1;
+ v2_use_value = false;
+ }
+ if (op->variant_op == Variant::OP_DIVIDE && v2.get_type() == Variant::FLOAT) {
+ v2 = 1.0;
+ v2_use_value = false;
+ }
- Variant res;
- bool valid;
- Variant::evaluate(vop, v1, v2, res, valid);
- if (!valid) {
- found = false;
- break;
- }
- r_type = _type_from_variant(res);
- if (!v1_use_value || !v2_use_value) {
- r_type.value = Variant();
- r_type.type.is_constant = false;
- }
+ Variant res;
+ bool valid;
+ Variant::evaluate(op->variant_op, v1, v2, res, valid);
+ if (!valid) {
+ found = false;
+ break;
+ }
+ r_type = _type_from_variant(res);
+ if (!v1_use_value || !v2_use_value) {
+ r_type.value = Variant();
+ r_type.type.is_constant = false;
+ }
- found = true;
- } break;
- }
- } break;
- default: {
+ found = true;
+ } break;
+ default:
+ break;
}
}
// It may have found a null, but that's never useful
- if (found && r_type.type.has_type && r_type.type.kind == GDScriptParser::DataType::BUILTIN && r_type.type.builtin_type == Variant::NIL) {
+ if (found && r_type.type.kind == GDScriptParser::DataType::BUILTIN && r_type.type.builtin_type == Variant::NIL) {
found = false;
}
// Check type hint last. For collections we want chance to get the actual value first
// This way we can detect types from the content of dictionaries and arrays
- if (!found && p_expression->get_datatype().has_type) {
+ if (!found && p_expression->get_datatype().is_hard_type()) {
r_type.type = p_expression->get_datatype();
if (!r_type.assigned_expression) {
r_type.assigned_expression = p_expression;
@@ -1170,307 +1654,289 @@ static bool _guess_expression_type(GDScriptCompletionContext &p_context, const G
return found;
}
-static bool _guess_identifier_type(GDScriptCompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
-
- // Look in blocks first
- const GDScriptParser::BlockNode *blk = p_context.block;
+static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
+ // Look in blocks first.
int last_assign_line = -1;
- const GDScriptParser::Node *last_assigned_expression = nullptr;
- GDScriptParser::DataType var_type;
- while (blk) {
- if (blk->variables.has(p_identifier)) {
- if (blk->variables[p_identifier]->line > p_context.line) {
- return false;
- }
+ const GDScriptParser::ExpressionNode *last_assigned_expression = nullptr;
+ GDScriptParser::DataType id_type;
+ GDScriptParser::SuiteNode *suite = p_context.current_suite;
+ bool is_function_parameter = false;
- var_type = blk->variables[p_identifier]->datatype;
+ if (suite) {
+ if (suite->has_local(p_identifier)) {
+ const GDScriptParser::SuiteNode::Local &local = suite->get_local(p_identifier);
- if (!last_assigned_expression && blk->variables[p_identifier]->assign && blk->variables[p_identifier]->assign->type == GDScriptParser::Node::TYPE_OPERATOR) {
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(blk->variables[p_identifier]->assign);
- if (op->op == GDScriptParser::OperatorNode::OP_ASSIGN && op->arguments.size() >= 2) {
- last_assign_line = op->line;
- last_assigned_expression = op->arguments[1];
- }
- }
- }
+ id_type = local.get_datatype();
- for (const List<GDScriptParser::Node *>::Element *E = blk->statements.front(); E; E = E->next()) {
- const GDScriptParser::Node *expr = E->get();
- if (expr->line > p_context.line || expr->type != GDScriptParser::Node::TYPE_OPERATOR) {
- continue;
+ // Check initializer as the first assignment.
+ switch (local.type) {
+ case GDScriptParser::SuiteNode::Local::VARIABLE:
+ if (local.variable->initializer) {
+ last_assign_line = local.variable->initializer->end_line;
+ last_assigned_expression = local.variable->initializer;
+ }
+ break;
+ case GDScriptParser::SuiteNode::Local::CONSTANT:
+ if (local.constant->initializer) {
+ last_assign_line = local.constant->initializer->end_line;
+ last_assigned_expression = local.constant->initializer;
+ }
+ break;
+ case GDScriptParser::SuiteNode::Local::PARAMETER:
+ if (local.parameter->default_value) {
+ last_assign_line = local.parameter->default_value->end_line;
+ last_assigned_expression = local.parameter->default_value;
+ }
+ is_function_parameter = true;
+ break;
+ default:
+ break;
}
+ }
+ }
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(expr);
- if (op->op != GDScriptParser::OperatorNode::OP_ASSIGN || op->line < last_assign_line) {
- continue;
+ while (suite) {
+ for (int i = 0; i < suite->statements.size(); i++) {
+ if (suite->statements[i]->start_line > p_context.current_line) {
+ break;
}
- if (op->arguments.size() >= 2 && op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER) {
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0]);
- if (id->name == p_identifier) {
- last_assign_line = op->line;
- last_assigned_expression = op->arguments[1];
- }
+ switch (suite->statements[i]->type) {
+ case GDScriptParser::Node::ASSIGNMENT: {
+ const GDScriptParser::AssignmentNode *assign = static_cast<const GDScriptParser::AssignmentNode *>(suite->statements[i]);
+ if (assign->end_line > last_assign_line && assign->assignee && assign->assigned_value && assign->assignee->type == GDScriptParser::Node::IDENTIFIER) {
+ const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(assign->assignee);
+ if (id->name == p_identifier) {
+ last_assign_line = assign->assigned_value->end_line;
+ last_assigned_expression = assign->assigned_value;
+ }
+ }
+ } break;
+ default:
+ // TODO: Check sub blocks (control flow statements) as they might also reassign stuff.
+ break;
}
}
- if (blk->if_condition && blk->if_condition->type == GDScriptParser::Node::TYPE_OPERATOR && static_cast<const GDScriptParser::OperatorNode *>(blk->if_condition)->op == GDScriptParser::OperatorNode::OP_IS) {
- //is used, check if identifier is in there! this helps resolve in blocks that are (if (identifier is value)): which are very common..
- //super dirty hack, but very useful
- //credit: Zylann
- //TODO: this could be hacked to detect ANDed conditions too..
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(blk->if_condition);
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_IDENTIFIER && static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name == p_identifier) {
- //bingo
- GDScriptCompletionContext c = p_context;
- c.line = op->line;
- c.block = blk;
- if (_guess_expression_type(p_context, op->arguments[1], r_type)) {
- r_type.type.is_meta_type = false; // Right-hand of `is` will be a meta type, but the left-hand value is not
- // Not an assignment, it shouldn't carry any value
- r_type.value = Variant();
- r_type.assigned_expression = nullptr;
-
- return true;
+ if (suite->parent_if && suite->parent_if->condition && suite->parent_if->condition->type == GDScriptParser::Node::BINARY_OPERATOR && static_cast<const GDScriptParser::BinaryOpNode *>(suite->parent_if->condition)->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
+ // Operator `is` used, check if identifier is in there! this helps resolve in blocks that are (if (identifier is value)): which are very common..
+ // Super dirty hack, but very useful.
+ // Credit: Zylann.
+ // TODO: this could be hacked to detect ANDed conditions too...
+ const GDScriptParser::BinaryOpNode *op = static_cast<const GDScriptParser::BinaryOpNode *>(suite->parent_if->condition);
+ if (op->left_operand && op->right_operand && op->left_operand->type == GDScriptParser::Node::IDENTIFIER && static_cast<const GDScriptParser::IdentifierNode *>(op->left_operand)->name == p_identifier) {
+ // Bingo.
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_line = op->left_operand->start_line;
+ c.current_suite = suite;
+ GDScriptCompletionIdentifier is_type;
+ if (_guess_expression_type(c, op->right_operand, is_type)) {
+ id_type = is_type.type;
+ id_type.is_meta_type = false;
+ if (last_assign_line < c.current_line) {
+ // Override last assignment.
+ last_assign_line = c.current_line;
+ last_assigned_expression = nullptr;
+ }
}
}
}
- blk = blk->parent_block;
+ suite = suite->parent_block;
}
- if (last_assigned_expression && last_assign_line != p_context.line) {
- GDScriptCompletionContext c = p_context;
- c.line = last_assign_line;
+ if (last_assigned_expression && last_assign_line != p_context.current_line) {
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_line = last_assign_line;
r_type.assigned_expression = last_assigned_expression;
if (_guess_expression_type(c, last_assigned_expression, r_type)) {
- if (var_type.has_type) {
- r_type.type = var_type;
- }
return true;
}
}
- if (var_type.has_type) {
- r_type.type = var_type;
- return true;
- }
-
- if (p_context.function) {
- for (int i = 0; i < p_context.function->arguments.size(); i++) {
- if (p_context.function->arguments[i] == p_identifier) {
- if (p_context.function->argument_types[i].has_type) {
- r_type.type = p_context.function->argument_types[i];
- return true;
- }
-
- int def_from = p_context.function->arguments.size() - p_context.function->default_values.size();
- if (i >= def_from) {
- int def_idx = i - def_from;
- if (p_context.function->default_values[def_idx]->type == GDScriptParser::Node::TYPE_OPERATOR) {
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_context.function->default_values[def_idx]);
- if (op->arguments.size() < 2) {
- return false;
- }
- GDScriptCompletionContext c = p_context;
- c.function = nullptr;
- c.block = nullptr;
- return _guess_expression_type(c, op->arguments[1], r_type);
- }
- }
- break;
- }
- }
-
- GDScriptParser::DataType base_type = p_context._class->base_type;
- while (base_type.has_type) {
+ if (is_function_parameter && p_context.current_function && p_context.current_class) {
+ // Check if it's override of native function, then we can assume the type from the signature.
+ GDScriptParser::DataType base_type = p_context.current_class->base_type;
+ while (base_type.is_set()) {
switch (base_type.kind) {
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> gds = base_type.script_type;
- if (gds.is_valid() && gds->has_method(p_context.function->name)) {
- GDScriptFunction *func = gds->get_member_functions()[p_context.function->name];
- if (func) {
- for (int i = 0; i < func->get_argument_count(); i++) {
- if (func->get_argument_name(i) == p_identifier) {
- r_type = _type_from_gdtype(func->get_argument_type(i));
- return true;
- }
- }
+ case GDScriptParser::DataType::CLASS:
+ if (base_type.class_type->has_function(p_context.current_function->identifier->name)) {
+ GDScriptParser::FunctionNode *parent_function = base_type.class_type->get_member(p_context.current_function->identifier->name).function;
+ const GDScriptParser::ParameterNode *parameter = parent_function->parameters[parent_function->parameters_indices[p_identifier]];
+ if ((!id_type.is_set() || id_type.is_variant()) && parameter->get_datatype().is_hard_type()) {
+ id_type = parameter->get_datatype();
}
- Ref<GDScript> base_gds = gds->get_base_script();
- if (base_gds.is_valid()) {
- base_type.kind = GDScriptParser::DataType::GDSCRIPT;
- base_type.script_type = base_gds;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = gds->get_instance_base_type();
+ if (parameter->default_value) {
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_function = parent_function;
+ c.current_class = base_type.class_type;
+ c.base = nullptr;
+ if (_guess_expression_type(c, parameter->default_value, r_type)) {
+ return true;
+ }
}
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = gds->get_instance_base_type();
+ base_type = base_type.class_type->base_type;
}
- } break;
+ break;
case GDScriptParser::DataType::NATIVE: {
- List<MethodInfo> methods;
- ClassDB::get_method_list(base_type.native_type, &methods);
- ClassDB::get_virtual_methods(base_type.native_type, &methods);
-
- for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().name == p_context.function->name) {
- MethodInfo &mi = E->get();
- for (List<PropertyInfo>::Element *F = mi.arguments.front(); F; F = F->next()) {
- if (F->get().name == p_identifier) {
- r_type = _type_from_property(F->get());
- return true;
- }
+ if (id_type.is_set() && !id_type.is_variant()) {
+ base_type = GDScriptParser::DataType();
+ break;
+ }
+ StringName real_native = _get_real_class_name(base_type.native_type);
+ MethodInfo info;
+ if (ClassDB::get_method_info(real_native, p_context.current_function->identifier->name, &info)) {
+ for (const List<PropertyInfo>::Element *E = info.arguments.front(); E; E = E->next()) {
+ if (E->get().name == p_identifier) {
+ r_type = _type_from_property(E->get());
+ return true;
}
}
}
- base_type.has_type = false;
- } break;
- default: {
- base_type.has_type = false;
+ base_type = GDScriptParser::DataType();
} break;
+ default:
+ break;
}
}
}
- // Check current class (including inheritance)
- if (p_context._class) {
- GDScriptCompletionIdentifier context_base;
- context_base.value = p_context.base;
- context_base.type.has_type = true;
- context_base.type.kind = GDScriptParser::DataType::CLASS;
- context_base.type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class);
- context_base.type.is_meta_type = p_context.function && p_context.function->_static;
-
- if (_guess_identifier_type_from_base(p_context, context_base, p_identifier, r_type)) {
- return true;
- }
+ if (id_type.is_set() && !id_type.is_variant()) {
+ r_type.type = id_type;
+ return true;
}
- // Check named scripts
- if (ScriptServer::is_global_class(p_identifier)) {
- Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier));
- if (scr.is_valid()) {
- r_type = _type_from_variant(scr);
- r_type.type.is_meta_type = true;
+ // Check current class (including inheritance).
+ if (p_context.current_class) {
+ GDScriptCompletionIdentifier base;
+ base.value = p_context.base;
+ base.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ base.type.kind = GDScriptParser::DataType::CLASS;
+ base.type.class_type = p_context.current_class;
+ base.type.is_meta_type = p_context.current_function && p_context.current_function->is_static;
+
+ if (_guess_identifier_type_from_base(p_context, base, p_identifier, r_type)) {
return true;
}
- return false;
}
- for (int i = 0; i < 2; i++) {
- StringName target_id;
- switch (i) {
- case 0:
- // Check ClassDB
- target_id = p_identifier;
- break;
- case 1:
- // ClassDB again for underscore-prefixed classes
- target_id = String("_") + p_identifier;
- break;
- }
-
- if (ClassDB::class_exists(target_id)) {
- r_type.type.has_type = true;
- r_type.type.kind = GDScriptParser::DataType::NATIVE;
- r_type.type.native_type = target_id;
- if (Engine::get_singleton()->has_singleton(target_id)) {
- r_type.type.is_meta_type = false;
- r_type.value = Engine::get_singleton()->get_singleton_object(target_id);
- } else {
+ // Check global scripts.
+ if (ScriptServer::is_global_class(p_identifier)) {
+ String script = ScriptServer::get_global_class_path(p_identifier);
+ if (script.to_lower().ends_with(".gd")) {
+ Error err = OK;
+ Ref<GDScriptParserRef> parser = GDScriptCache::get_parser(script, GDScriptParserRef::INTERFACE_SOLVED, err);
+ if (err == OK) {
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.script_path = script;
+ r_type.type.class_type = parser->get_parser()->get_tree();
+ r_type.type.is_constant = false;
+ r_type.type.kind = GDScriptParser::DataType::CLASS;
+ r_type.value = Variant();
+ p_context.dependent_parsers.push_back(parser);
+ return true;
+ }
+ } else {
+ Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier));
+ if (scr.is_valid()) {
+ r_type = _type_from_variant(scr);
r_type.type.is_meta_type = true;
- const Map<StringName, int>::Element *target_elem = GDScriptLanguage::get_singleton()->get_global_map().find(target_id);
- // Check because classes like EditorNode are in ClassDB by now, but unknown to GDScript
- if (!target_elem) {
- return false;
- }
- int idx = target_elem->get();
- r_type.value = GDScriptLanguage::get_singleton()->get_global_array()[idx];
+ return true;
}
- return true;
}
+ return false;
}
- // Check autoload singletons
- if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) {
+ // Check autoloads.
+ if (ProjectSettings::get_singleton()->has_autoload(p_identifier)) {
r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]);
return true;
}
+ // Check ClassDB.
+ StringName class_name = _get_real_class_name(p_identifier);
+ if (ClassDB::class_exists(class_name) && ClassDB::is_class_exposed(class_name)) {
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::NATIVE;
+ r_type.type.native_type = p_identifier;
+ r_type.type.is_constant = true;
+ r_type.type.is_meta_type = !Engine::get_singleton()->has_singleton(class_name);
+ r_type.value = Variant();
+ }
+
return false;
}
-static bool _guess_identifier_type_from_base(GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
+static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
GDScriptParser::DataType base_type = p_base.type;
- bool _static = base_type.is_meta_type;
- while (base_type.has_type) {
+ bool is_static = base_type.is_meta_type;
+ while (base_type.is_set()) {
switch (base_type.kind) {
- case GDScriptParser::DataType::CLASS: {
- if (base_type.class_type->constant_expressions.has(p_identifier)) {
- GDScriptParser::ClassNode::Constant c = base_type.class_type->constant_expressions[p_identifier];
- r_type.type = c.type;
- if (c.expression->type == GDScriptParser::Node::TYPE_CONSTANT) {
- r_type.value = static_cast<const GDScriptParser::ConstantNode *>(c.expression)->value;
- }
- return true;
- }
-
- if (!_static) {
- for (int i = 0; i < base_type.class_type->variables.size(); i++) {
- GDScriptParser::ClassNode::Member m = base_type.class_type->variables[i];
- if (m.identifier == p_identifier) {
- if (m.expression) {
- if (p_context.line == m.expression->line) {
- // Variable used in the same expression
- return false;
- }
-
- if (_guess_expression_type(p_context, m.expression, r_type)) {
- return true;
- }
- if (m.expression->get_datatype().has_type) {
- r_type.type = m.expression->get_datatype();
+ case GDScriptParser::DataType::CLASS:
+ if (base_type.class_type->has_member(p_identifier)) {
+ const GDScriptParser::ClassNode::Member &member = base_type.class_type->get_member(p_identifier);
+ switch (member.type) {
+ case GDScriptParser::ClassNode::Member::CONSTANT:
+ r_type.type = member.constant->get_datatype();
+ if (member.constant->initializer && member.constant->initializer->is_constant) {
+ r_type.value = member.constant->initializer->reduced_value;
+ }
+ return true;
+ case GDScriptParser::ClassNode::Member::VARIABLE:
+ if (!is_static) {
+ if (member.variable->initializer) {
+ const GDScriptParser::ExpressionNode *init = member.variable->initializer;
+ if (init->is_constant) {
+ r_type.value = init->reduced_value;
+ r_type = _type_from_variant(init->reduced_value);
+ return true;
+ } else if (init->start_line == p_context.current_line) {
+ return false;
+ } else if (_guess_expression_type(p_context, init, r_type)) {
+ return true;
+ } else if (init->get_datatype().is_set() && !init->get_datatype().is_variant()) {
+ r_type.type = init->get_datatype();
+ return true;
+ }
+ } else if (member.variable->get_datatype().is_set() && !member.variable->get_datatype().is_variant()) {
+ r_type.type = member.variable->get_datatype();
return true;
}
}
- if (m.data_type.has_type) {
- r_type.type = m.data_type;
- return true;
- }
+ // TODO: Check assignments in constructor.
return false;
- }
- }
- }
- base_type = base_type.class_type->base_type;
- } break;
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> gds = base_type.script_type;
- if (gds.is_valid()) {
- if (gds->get_constants().has(p_identifier)) {
- r_type = _type_from_variant(gds->get_constants()[p_identifier]);
- return true;
- }
- if (!_static) {
- const Set<StringName>::Element *m = gds->get_members().find(p_identifier);
- if (m) {
- r_type = _type_from_gdtype(gds->get_member_type(p_identifier));
+ case GDScriptParser::ClassNode::Member::ENUM:
+ r_type.type = member.m_enum->get_datatype();
+ r_type.enumeration = member.m_enum->identifier->name;
return true;
- }
- }
- Ref<GDScript> parent = gds->get_base_script();
- if (parent.is_valid()) {
- base_type.script_type = parent;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = gds->get_instance_base_type();
+ case GDScriptParser::ClassNode::Member::ENUM_VALUE:
+ r_type = _type_from_variant(member.enum_value.value);
+ return true;
+ case GDScriptParser::ClassNode::Member::SIGNAL:
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::BUILTIN;
+ r_type.type.builtin_type = Variant::SIGNAL;
+ return true;
+ case GDScriptParser::ClassNode::Member::FUNCTION:
+ if (is_static && !member.function->is_static) {
+ return false;
+ }
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::BUILTIN;
+ r_type.type.builtin_type = Variant::CALLABLE;
+ return true;
+ case GDScriptParser::ClassNode::Member::CLASS:
+ r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
+ r_type.type.kind = GDScriptParser::DataType::CLASS;
+ r_type.type.class_type = member.m_class;
+ return true;
+ case GDScriptParser::ClassNode::Member::UNDEFINED:
+ return false; // Unreachable.
}
- } else {
return false;
}
- } break;
+ base_type = base_type.class_type->base_type;
+ break;
case GDScriptParser::DataType::SCRIPT: {
Ref<Script> scr = base_type.script_type;
if (scr.is_valid()) {
@@ -1481,7 +1947,7 @@ static bool _guess_identifier_type_from_base(GDScriptCompletionContext &p_contex
return true;
}
- if (!_static) {
+ if (!is_static) {
List<PropertyInfo> members;
scr->get_script_property_list(&members);
for (const List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
@@ -1504,40 +1970,33 @@ static bool _guess_identifier_type_from_base(GDScriptCompletionContext &p_contex
}
} break;
case GDScriptParser::DataType::NATIVE: {
- StringName class_name = base_type.native_type;
+ StringName class_name = _get_real_class_name(base_type.native_type);
if (!ClassDB::class_exists(class_name)) {
- class_name = String("_") + class_name;
- if (!ClassDB::class_exists(class_name)) {
- return false;
- }
+ return false;
}
- // Skip constants since they're all integers. Type does not matter because int has no members
+ // Skip constants since they're all integers. Type does not matter because int has no members.
- List<PropertyInfo> props;
- ClassDB::get_property_list(class_name, &props);
- for (const List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- const PropertyInfo &prop = E->get();
- if (prop.name == p_identifier) {
- StringName getter = ClassDB::get_property_getter(class_name, p_identifier);
- if (getter != StringName()) {
- MethodBind *g = ClassDB::get_method(class_name, getter);
- if (g) {
- r_type = _type_from_property(g->get_return_info());
- return true;
- }
- } else {
- r_type = _type_from_property(prop);
+ PropertyInfo prop;
+ if (ClassDB::get_property_info(class_name, p_identifier, &prop)) {
+ StringName getter = ClassDB::get_property_getter(class_name, p_identifier);
+ if (getter != StringName()) {
+ MethodBind *g = ClassDB::get_method(class_name, getter);
+ if (g) {
+ r_type = _type_from_property(g->get_return_info());
return true;
}
- break;
+ } else {
+ r_type = _type_from_property(prop);
+ return true;
}
}
return false;
} break;
case GDScriptParser::DataType::BUILTIN: {
Callable::CallError err;
- Variant tmp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
+ Variant tmp;
+ Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
if (err.error != Callable::CallError::CALL_OK) {
return false;
@@ -1557,116 +2016,99 @@ static bool _guess_identifier_type_from_base(GDScriptCompletionContext &p_contex
} break;
}
}
-
return false;
}
-static bool _find_last_return_in_block(const GDScriptCompletionContext &p_context, int &r_last_return_line, const GDScriptParser::Node **r_last_returned_value) {
- if (!p_context.block) {
- return false;
+static void _find_last_return_in_block(GDScriptParser::CompletionContext &p_context, int &r_last_return_line, const GDScriptParser::ExpressionNode **r_last_returned_value) {
+ if (!p_context.current_suite) {
+ return;
}
- for (int i = 0; i < p_context.block->statements.size(); i++) {
- if (p_context.block->statements[i]->line < r_last_return_line) {
- continue;
- }
- if (p_context.block->statements[i]->type != GDScriptParser::Node::TYPE_CONTROL_FLOW) {
- continue;
+ for (int i = 0; i < p_context.current_suite->statements.size(); i++) {
+ if (p_context.current_suite->statements[i]->start_line < r_last_return_line) {
+ break;
}
- const GDScriptParser::ControlFlowNode *cf = static_cast<const GDScriptParser::ControlFlowNode *>(p_context.block->statements[i]);
- if (cf->cf_type == GDScriptParser::ControlFlowNode::CF_RETURN && cf->arguments.size() > 0) {
- if (cf->line > r_last_return_line) {
- r_last_return_line = cf->line;
- *r_last_returned_value = cf->arguments[0];
- }
+ GDScriptParser::CompletionContext c = p_context;
+ switch (p_context.current_suite->statements[i]->type) {
+ case GDScriptParser::Node::FOR:
+ c.current_suite = static_cast<const GDScriptParser::ForNode *>(p_context.current_suite->statements[i])->loop;
+ _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
+ break;
+ case GDScriptParser::Node::WHILE:
+ c.current_suite = static_cast<const GDScriptParser::WhileNode *>(p_context.current_suite->statements[i])->loop;
+ _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
+ break;
+ case GDScriptParser::Node::IF: {
+ const GDScriptParser::IfNode *_if = static_cast<const GDScriptParser::IfNode *>(p_context.current_suite->statements[i]);
+ c.current_suite = _if->true_block;
+ _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
+ if (_if->false_block) {
+ c.current_suite = _if->false_block;
+ _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
+ }
+ } break;
+ case GDScriptParser::Node::MATCH: {
+ const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(p_context.current_suite->statements[i]);
+ for (int j = 0; j < match->branches.size(); j++) {
+ c.current_suite = match->branches[j]->block;
+ _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
+ }
+ } break;
+ case GDScriptParser::Node::RETURN: {
+ const GDScriptParser::ReturnNode *ret = static_cast<const GDScriptParser::ReturnNode *>(p_context.current_suite->statements[i]);
+ if (ret->return_value) {
+ if (ret->start_line > r_last_return_line) {
+ r_last_return_line = ret->start_line;
+ *r_last_returned_value = ret->return_value;
+ }
+ }
+ } break;
+ default:
+ break;
}
}
-
- // Recurse into subblocks
- for (int i = 0; i < p_context.block->sub_blocks.size(); i++) {
- GDScriptCompletionContext c = p_context;
- c.block = p_context.block->sub_blocks[i];
- _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
- }
-
- return false;
}
-static bool _guess_method_return_type_from_base(GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type) {
+static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type) {
GDScriptParser::DataType base_type = p_base.type;
- bool _static = base_type.is_meta_type;
+ bool is_static = base_type.is_meta_type;
- if (_static && p_method == "new") {
+ if (is_static && p_method == "new") {
r_type.type = base_type;
r_type.type.is_meta_type = false;
r_type.type.is_constant = false;
return true;
}
- while (base_type.has_type) {
+ while (base_type.is_set() && !base_type.is_variant()) {
switch (base_type.kind) {
- case GDScriptParser::DataType::CLASS: {
- if (!base_type.class_type) {
- base_type.has_type = false;
- break;
- }
-
- for (int i = 0; i < base_type.class_type->static_functions.size(); i++) {
- if (base_type.class_type->static_functions[i]->name == p_method) {
+ case GDScriptParser::DataType::CLASS:
+ if (base_type.class_type->has_function(p_method)) {
+ const GDScriptParser::FunctionNode *method = base_type.class_type->get_member(p_method).function;
+ if (!is_static || method->is_static) {
int last_return_line = -1;
- const GDScriptParser::Node *last_returned_value = nullptr;
- GDScriptCompletionContext c = p_context;
- c._class = base_type.class_type;
- c.function = base_type.class_type->static_functions[i];
- c.block = c.function->body;
+ const GDScriptParser::ExpressionNode *last_returned_value = nullptr;
+ GDScriptParser::CompletionContext c = p_context;
+ c.current_class = base_type.class_type;
+ c.current_function = const_cast<GDScriptParser::FunctionNode *>(method);
+ c.current_suite = method->body;
_find_last_return_in_block(c, last_return_line, &last_returned_value);
if (last_returned_value) {
- c.line = c.block->end_line;
- return _guess_expression_type(c, last_returned_value, r_type);
- }
- }
- }
- if (!_static) {
- for (int i = 0; i < base_type.class_type->functions.size(); i++) {
- if (base_type.class_type->functions[i]->name == p_method) {
- int last_return_line = -1;
- const GDScriptParser::Node *last_returned_value = nullptr;
- GDScriptCompletionContext c = p_context;
- c._class = base_type.class_type;
- c.function = base_type.class_type->functions[i];
- c.block = c.function->body;
-
- _find_last_return_in_block(c, last_return_line, &last_returned_value);
- if (last_returned_value) {
- c.line = c.block->end_line;
- return _guess_expression_type(c, last_returned_value, r_type);
+ c.current_line = c.current_suite->end_line;
+ if (_guess_expression_type(c, last_returned_value, r_type)) {
+ return true;
+ }
+ if (method->get_datatype().is_set() && !method->get_datatype().is_variant()) {
+ r_type.type = method->get_datatype();
+ return true;
}
}
}
}
-
base_type = base_type.class_type->base_type;
- } break;
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> gds = base_type.script_type;
- if (gds.is_valid()) {
- if (gds->get_member_functions().has(p_method)) {
- r_type = _type_from_gdtype(gds->get_member_functions()[p_method]->get_return_type());
- return true;
- }
- Ref<GDScript> base_script = gds->get_base_script();
- if (base_script.is_valid()) {
- base_type.script_type = base_script;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = gds->get_instance_base_type();
- }
- } else {
- return false;
- }
- } break;
+ break;
case GDScriptParser::DataType::SCRIPT: {
Ref<Script> scr = base_type.script_type;
if (scr.is_valid()) {
@@ -1691,12 +2133,9 @@ static bool _guess_method_return_type_from_base(GDScriptCompletionContext &p_con
}
} break;
case GDScriptParser::DataType::NATIVE: {
- StringName native = base_type.native_type;
+ StringName native = _get_real_class_name(base_type.native_type);
if (!ClassDB::class_exists(native)) {
- native = String("_") + native;
- if (!ClassDB::class_exists(native)) {
- return false;
- }
+ return false;
}
MethodBind *mb = ClassDB::get_method(native, p_method);
if (mb) {
@@ -1707,7 +2146,8 @@ static bool _guess_method_return_type_from_base(GDScriptCompletionContext &p_con
} break;
case GDScriptParser::DataType::BUILTIN: {
Callable::CallError err;
- Variant tmp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
+ Variant tmp;
+ Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
if (err.error != Callable::CallError::CALL_OK) {
return false;
}
@@ -1729,106 +2169,27 @@ static bool _guess_method_return_type_from_base(GDScriptCompletionContext &p_con
}
}
}
- return false;
-}
-
-static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx) {
-
- String arghint = _get_visual_datatype(p_info.return_val, false) + " " + p_info.name + "(";
-
- int def_args = p_info.arguments.size() - p_info.default_arguments.size();
- int i = 0;
- for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E; E = E->next()) {
- if (i > 0) {
- arghint += ", ";
- }
-
- if (i == p_arg_idx) {
- arghint += String::chr(0xFFFF);
- }
- arghint += E->get().name + ": " + _get_visual_datatype(E->get(), true);
-
- if (i - def_args >= 0) {
- arghint += String(" = ") + p_info.default_arguments[i - def_args].get_construct_string();
- }
-
- if (i == p_arg_idx) {
- arghint += String::chr(0xFFFF);
- }
-
- i++;
- }
- if (p_info.flags & METHOD_FLAG_VARARG) {
- if (p_info.arguments.size() > 0) {
- arghint += ", ";
- }
- if (p_arg_idx >= p_info.arguments.size()) {
- arghint += String::chr(0xFFFF);
- }
- arghint += "...";
- if (p_arg_idx >= p_info.arguments.size()) {
- arghint += String::chr(0xFFFF);
- }
- }
-
- arghint += ")";
-
- return arghint;
-}
-
-static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_function, int p_arg_idx) {
-
- String arghint = p_function->return_type.to_string() + " " + p_function->name.operator String() + "(";
-
- int def_args = p_function->arguments.size() - p_function->default_values.size();
- for (int i = 0; i < p_function->arguments.size(); i++) {
- if (i > 0) {
- arghint += ", ";
- }
-
- if (i == p_arg_idx) {
- arghint += String::chr(0xFFFF);
- }
- arghint += p_function->arguments[i].operator String() + ": " + p_function->argument_types[i].to_string();
-
- if (i - def_args >= 0) {
- String def_val = "<unknown>";
- if (p_function->default_values[i - def_args] && p_function->default_values[i - def_args]->type == GDScriptParser::Node::TYPE_OPERATOR) {
- const GDScriptParser::OperatorNode *assign = static_cast<const GDScriptParser::OperatorNode *>(p_function->default_values[i - def_args]);
-
- if (assign->arguments.size() >= 2) {
- if (assign->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT) {
- const GDScriptParser::ConstantNode *cn = static_cast<const GDScriptParser::ConstantNode *>(assign->arguments[1]);
- def_val = cn->value.get_construct_string();
- } else if (assign->arguments[1]->type == GDScriptParser::Node::TYPE_IDENTIFIER) {
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(assign->arguments[1]);
- def_val = id->name.operator String();
- }
- }
- }
- arghint += " = " + def_val;
- }
- if (i == p_arg_idx) {
- arghint += String::chr(0xFFFF);
- }
- }
-
- arghint += ")";
-
- return arghint;
+ return false;
}
-static void _find_enumeration_candidates(const String p_enum_hint, Map<String, ScriptCodeCompletionOption> &r_result) {
-
+static void _find_enumeration_candidates(GDScriptParser::CompletionContext &p_context, const String &p_enum_hint, Map<String, ScriptCodeCompletionOption> &r_result) {
if (p_enum_hint.find(".") == -1) {
- // Global constant
+ // Global constant or in the current class.
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) {
- ScriptCodeCompletionOption option(GlobalConstants::get_global_constant_name(i), ScriptCodeCompletionOption::KIND_ENUM);
+ if (p_context.current_class && p_context.current_class->has_member(current_enum) && p_context.current_class->get_member(current_enum).type == GDScriptParser::ClassNode::Member::ENUM) {
+ const GDScriptParser::EnumNode *_enum = p_context.current_class->get_member(current_enum).m_enum;
+ for (int i = 0; i < _enum->values.size(); i++) {
+ ScriptCodeCompletionOption option(_enum->values[i].identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
r_result.insert(option.display, option);
}
+ } else {
+ for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
+ if (CoreConstants::get_global_constant_enum(i) == current_enum) {
+ ScriptCodeCompletionOption option(CoreConstants::get_global_constant_name(i), ScriptCodeCompletionOption::KIND_ENUM);
+ r_result.insert(option.display, option);
+ }
+ }
}
} else {
String class_name = p_enum_hint.get_slice(".", 0);
@@ -1848,498 +2209,60 @@ static void _find_enumeration_candidates(const String p_enum_hint, Map<String, S
}
}
-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) {
- ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_VARIABLE);
- r_result.insert(option.display, option);
- }
- }
- if (p_context.block->parent_block) {
- GDScriptCompletionContext c = p_context;
- c.block = p_context.block->parent_block;
- _find_identifiers_in_block(c, 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, 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++) {
- 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()) {
- ScriptCodeCompletionOption option(E->key(), ScriptCodeCompletionOption::KIND_CONSTANT);
- r_result.insert(option.display, option);
- }
- for (int i = 0; i < p_context._class->subclasses.size(); i++) {
- 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()) {
- option.insert_text += "(";
- } else {
- 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()) {
- option.insert_text += "(";
- } else {
- option.insert_text += "()";
- }
- r_result.insert(option.display, option);
- }
- }
- }
-
- // Parents
- GDScriptCompletionIdentifier base_type;
- base_type.type = p_context._class->base_type;
- base_type.type.is_meta_type = p_static;
- base_type.value = p_context.base;
-
- GDScriptCompletionContext c = p_context;
- c.block = nullptr;
- c.function = nullptr;
-
- _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, 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) {
- ScriptCodeCompletionOption option("new", ScriptCodeCompletionOption::KIND_FUNCTION);
- option.insert_text += "(";
- r_result.insert(option.display, option);
- }
-
- while (base_type.has_type) {
- switch (base_type.kind) {
- case GDScriptParser::DataType::CLASS: {
- GDScriptCompletionContext c = p_context;
- c._class = base_type.class_type;
- c.block = nullptr;
- c.function = nullptr;
- _find_identifiers_in_class(c, _static, p_only_functions, false, r_result);
- base_type = base_type.class_type->base_type;
- } break;
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> script = base_type.script_type;
- if (script.is_valid()) {
- if (!_static && !p_only_functions) {
- if (p_context.base && p_context.base->get_script_instance()) {
- List<PropertyInfo> members;
- p_context.base->get_script_instance()->get_property_list(&members);
- for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
- ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
- r_result.insert(option.display, option);
- }
- }
- for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) {
- 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()) {
- 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()) {
- option.insert_text += "(";
- } else {
- 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()) {
- ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
- r_result.insert(option.display, option);
- }
- }
- base_type = GDScriptParser::DataType();
- if (script->get_base().is_valid()) {
- base_type.has_type = true;
- base_type.kind = GDScriptParser::DataType::GDSCRIPT;
- base_type.script_type = script->get_base();
- } else {
- base_type.has_type = script->get_instance_base_type() != StringName();
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = script->get_instance_base_type();
- }
- } else {
- return;
- }
- } break;
- case GDScriptParser::DataType::SCRIPT: {
- Ref<Script> scr = base_type.script_type;
- if (scr.is_valid()) {
- if (!_static && !p_only_functions) {
- List<PropertyInfo> members;
- scr->get_script_property_list(&members);
- for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
- 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()) {
- 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()) {
- option.insert_text += "(";
- } else {
- option.insert_text += "()";
- }
- r_result.insert(option.display, option);
- }
-
- Ref<Script> base_script = scr->get_base_script();
- if (base_script.is_valid()) {
- base_type.script_type = base_script;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = scr->get_instance_base_type();
- }
- } else {
- return;
- }
- } break;
- case GDScriptParser::DataType::NATIVE: {
- StringName type = base_type.native_type;
- if (!ClassDB::class_exists(type)) {
- type = String("_") + type;
- if (!ClassDB::class_exists(type)) {
- return;
- }
- }
-
- if (!p_only_functions) {
- List<String> constants;
- ClassDB::get_integer_constant_list(type, &constants);
- for (List<String>::Element *E = constants.front(); E; E = E->next()) {
- ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT);
- r_result.insert(option.display, option);
- }
-
- if (!_static) {
- List<PropertyInfo> pinfo;
- ClassDB::get_property_list(type, &pinfo);
- for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP | PROPERTY_USAGE_CATEGORY)) {
- continue;
- }
- if (E->get().name.find("/") != -1) {
- continue;
- }
- ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
- r_result.insert(option.display, option);
- }
- }
- }
-
- if (!_static) {
- List<MethodInfo> methods;
- bool is_autocompleting_getters = GLOBAL_GET("debug/gdscript/completion/autocomplete_setters_and_getters").booleanize();
- ClassDB::get_method_list(type, &methods, false, !is_autocompleting_getters);
- for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().name.begins_with("_")) {
- continue;
- }
- ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
- if (E->get().arguments.size()) {
- option.insert_text += "(";
- } else {
- option.insert_text += "()";
- }
- r_result.insert(option.display, option);
- }
- }
-
- return;
- } break;
- case GDScriptParser::DataType::BUILTIN: {
- Callable::CallError err;
- Variant tmp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
- if (err.error != Callable::CallError::CALL_OK) {
- return;
- }
-
- if (!p_only_functions) {
- List<PropertyInfo> members;
- tmp.get_property_list(&members);
-
- for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
- if (String(E->get().name).find("/") == -1) {
- ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
- r_result.insert(option.display, option);
- }
- }
- }
-
- 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()) {
- option.insert_text += "(";
- } else {
- option.insert_text += "()";
- }
- r_result.insert(option.display, option);
- }
-
- return;
- } break;
- default: {
- return;
- } break;
- }
- }
-}
-
-static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result) {
-
- const GDScriptParser::BlockNode *block = p_context.block;
-
- if (p_context.function) {
-
- const GDScriptParser::FunctionNode *f = p_context.function;
-
- for (int i = 0; i < f->arguments.size(); i++) {
- ScriptCodeCompletionOption option(f->arguments[i].operator String(), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
- r_result.insert(option.display, option);
- }
- }
-
- if (!p_only_functions && block) {
- GDScriptCompletionContext c = p_context;
- c.block = block;
- _find_identifiers_in_block(c, r_result);
- }
-
- const GDScriptParser::ClassNode *clss = p_context._class;
- bool _static = p_context.function && p_context.function->_static;
-
- while (clss) {
- GDScriptCompletionContext c = p_context;
- c._class = clss;
- c.block = nullptr;
- c.function = nullptr;
- _find_identifiers_in_class(c, _static, p_only_functions, false, r_result);
- _static = true;
- clss = clss->owner;
- }
-
- 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)) {
- option.insert_text += "(";
- } else {
- option.insert_text += "()";
- }
- r_result.insert(option.display, option);
- }
-
- static const char *_type_names[Variant::VARIANT_MAX] = {
- "null", "bool", "int", "float", "String", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quat", "AABB", "Basis", "Transform",
- "Color", "StringName", "NodePath", "RID", "Object", "Callable", "Signal", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray",
- "PackedVector2Array", "PackedVector3Array", "PackedColorArray"
- };
-
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- ScriptCodeCompletionOption option(_type_names[i], ScriptCodeCompletionOption::KIND_CLASS);
- r_result.insert(option.display, option);
- }
-
- static const char *_keywords[] = {
- "and", "in", "not", "or", "false", "PI", "TAU", "INF", "NAN", "self", "true", "as", "assert",
- "breakpoint", "class", "extends", "is", "func", "preload", "setget", "signal", "tool", "yield",
- "const", "enum", "export", "onready", "static", "var", "break", "continue", "if", "elif",
- "else", "for", "pass", "return", "match", "while", "remote", "master", "puppet",
- "remotesync", "mastersync", "puppetsync",
- nullptr
- };
-
- const char **kw = _keywords;
- while (*kw) {
- ScriptCodeCompletionOption option(*kw, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
- r_result.insert(option.display, option);
- kw++;
- }
-
- // Autoload singletons
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
- }
- String path = ProjectSettings::get_singleton()->get(s);
- if (path.begins_with("*")) {
- ScriptCodeCompletionOption option(s.get_slice("/", 1), ScriptCodeCompletionOption::KIND_CONSTANT);
- r_result.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()) {
- 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()) {
- 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, Map<String, ScriptCodeCompletionOption> &r_result, String &r_arghint) {
+static void _find_call_arguments(GDScriptParser::CompletionContext &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;
const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\"";
-#define IS_METHOD_SIGNAL(m_method) (m_method == "connect" || m_method == "disconnect" || m_method == "is_connected" || m_method == "emit_signal")
-
- while (base_type.has_type) {
+ while (base_type.is_set() && !base_type.is_variant()) {
switch (base_type.kind) {
case GDScriptParser::DataType::CLASS: {
- for (int i = 0; i < base_type.class_type->static_functions.size(); i++) {
- if (base_type.class_type->static_functions[i]->name == p_method) {
- r_arghint = _make_arguments_hint(base_type.class_type->static_functions[i], p_argidx);
- return;
- }
- }
- for (int i = 0; i < base_type.class_type->functions.size(); i++) {
- if (base_type.class_type->functions[i]->name == p_method) {
- r_arghint = _make_arguments_hint(base_type.class_type->functions[i], p_argidx);
- return;
- }
- }
+ if (base_type.class_type->has_member(p_method)) {
+ const GDScriptParser::ClassNode::Member &member = base_type.class_type->get_member(p_method);
- if (IS_METHOD_SIGNAL(p_method) && p_argidx == 0) {
- for (int i = 0; i < base_type.class_type->_signals.size(); i++) {
- 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);
+ if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
+ r_arghint = _make_arguments_hint(member.function, p_argidx);
+ return;
}
}
base_type = base_type.class_type->base_type;
} break;
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> gds = base_type.script_type;
- if (gds.is_valid()) {
- if (IS_METHOD_SIGNAL(p_method) && p_argidx == 0) {
- List<MethodInfo> signals;
- gds->get_script_signal_list(&signals);
- for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- 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();
- if (base_script.is_valid()) {
- base_type.script_type = base_script;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = gds->get_instance_base_type();
- }
- } else {
- return;
- }
- } break;
case GDScriptParser::DataType::NATIVE: {
- StringName class_name = base_type.native_type;
+ StringName class_name = _get_real_class_name(base_type.native_type);
if (!ClassDB::class_exists(class_name)) {
- class_name = String("_") + class_name;
- if (!ClassDB::class_exists(class_name)) {
- base_type.has_type = false;
- break;
- }
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
+ break;
}
- List<MethodInfo> methods;
- ClassDB::get_method_list(class_name, &methods);
- ClassDB::get_virtual_methods(class_name, &methods);
+ MethodInfo info;
int method_args = 0;
- for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().name == p_method) {
- method_args = E->get().arguments.size();
- if (base.get_type() == Variant::OBJECT) {
- Object *obj = base.operator Object *();
- if (obj) {
- List<String> options;
- obj->get_argument_options(p_method, p_argidx, &options);
- for (List<String>::Element *F = options.front(); F; F = F->next()) {
- ScriptCodeCompletionOption option(F->get(), ScriptCodeCompletionOption::KIND_FUNCTION);
- r_result.insert(option.display, option);
- }
+ if (ClassDB::get_method_info(class_name, p_method, &info)) {
+ method_args = info.arguments.size();
+ if (base.get_type() == Variant::OBJECT) {
+ Object *obj = base.operator Object *();
+ if (obj) {
+ List<String> options;
+ obj->get_argument_options(p_method, p_argidx, &options);
+ for (List<String>::Element *F = options.front(); F; F = F->next()) {
+ ScriptCodeCompletionOption option(F->get(), ScriptCodeCompletionOption::KIND_FUNCTION);
+ r_result.insert(option.display, option);
}
}
+ }
- if (p_argidx < method_args) {
- PropertyInfo arg_info = E->get().arguments[p_argidx];
- if (arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
- _find_enumeration_candidates(arg_info.class_name, r_result);
- }
+ if (p_argidx < method_args) {
+ PropertyInfo arg_info = info.arguments[p_argidx];
+ if (arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
+ _find_enumeration_candidates(p_context, arg_info.class_name, r_result);
}
-
- r_arghint = _make_arguments_hint(E->get(), p_argidx);
- break;
}
- }
- if (IS_METHOD_SIGNAL(p_method) && p_argidx == 0) {
- List<MethodInfo> signals;
- ClassDB::get_signal_list(class_name, &signals);
- for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL);
- option.insert_text = quote_style + option.display + quote_style;
- r_result.insert(option.display, option);
- }
+ r_arghint = _make_arguments_hint(info, p_argidx);
+ return;
}
-#undef IS_METHOD_SIGNAL
if (ClassDB::is_parent_class(class_name, "Node") && (p_method == "get_node" || p_method == "has_node") && p_argidx == 0) {
// Get autoloads
@@ -2374,12 +2297,12 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
}
}
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
} break;
case GDScriptParser::DataType::BUILTIN: {
if (base.get_type() == Variant::NIL) {
Callable::CallError err;
- base = Variant::construct(base_type.builtin_type, nullptr, 0, err);
+ Variant::construct(base_type.builtin_type, base, nullptr, 0, err);
if (err.error != Callable::CallError::CALL_OK) {
return;
}
@@ -2394,295 +2317,308 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
}
}
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
} break;
default: {
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
} break;
}
}
}
-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) {
-
+static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, const GDScriptParser::Node *p_call, 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) ? "'" : "\"";
- if (!p_node || p_node->type != GDScriptParser::Node::TYPE_OPERATOR) {
+ if (p_call->type == GDScriptParser::Node::PRELOAD) {
+ if (p_argidx == 0 && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) {
+ _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), r_result);
+ }
+
+ MethodInfo mi(PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), "preload", PropertyInfo(Variant::STRING, "path"));
+ r_arghint = _make_arguments_hint(mi, p_argidx);
+ return;
+ } else if (p_call->type != GDScriptParser::Node::CALL) {
return;
}
Variant base;
GDScriptParser::DataType base_type;
- StringName function;
bool _static = false;
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(p_node);
+ const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_call);
+ GDScriptParser::Node::Type callee_type = call->get_callee_type();
GDScriptCompletionIdentifier connect_base;
- if (op->op != GDScriptParser::OperatorNode::OP_CALL && op->op != GDScriptParser::OperatorNode::OP_PARENT_CALL) {
- return;
- }
-
- if (!op->arguments.size()) {
+ if (GDScriptUtilityFunctions::function_exists(call->function_name)) {
+ MethodInfo info = GDScriptUtilityFunctions::get_function_info(call->function_name);
+ r_arghint = _make_arguments_hint(info, p_argidx);
return;
- }
-
- if (op->op == GDScriptParser::OperatorNode::OP_CALL) {
- if (op->arguments[0]->type == GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION) {
- // Complete built-in function
- const GDScriptParser::BuiltInFunctionNode *fn = static_cast<const GDScriptParser::BuiltInFunctionNode *>(op->arguments[0]);
- MethodInfo mi = GDScriptFunctions::get_info(fn->function);
-
- if ((mi.name == "load" || mi.name == "preload") && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) {
- _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), r_result);
- }
-
- r_arghint = _make_arguments_hint(mi, p_argidx);
- return;
-
- } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_TYPE) {
- // Complete constructor
- const GDScriptParser::TypeNode *tn = static_cast<const GDScriptParser::TypeNode *>(op->arguments[0]);
-
- List<MethodInfo> constructors;
- Variant::get_constructor_list(tn->vtype, &constructors);
-
- int i = 0;
- for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) {
- if (p_argidx >= E->get().arguments.size()) {
- continue;
- }
- if (i > 0) {
- r_arghint += "\n";
- }
- r_arghint += _make_arguments_hint(E->get(), p_argidx);
- i++;
+ } else if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) {
+ // Complete constructor
+ List<MethodInfo> constructors;
+ Variant::get_constructor_list(GDScriptParser::get_builtin_type(call->function_name), &constructors);
+
+ int i = 0;
+ for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) {
+ if (p_argidx >= E->get().arguments.size()) {
+ continue;
}
- return;
- } else if (op->arguments[0]->type == GDScriptParser::Node::TYPE_SELF) {
-
- if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- return;
- }
-
- base = p_context.base;
-
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]);
- function = id->name;
- base_type.has_type = true;
- base_type.kind = GDScriptParser::DataType::CLASS;
- base_type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class);
- _static = p_context.function && p_context.function->_static;
-
- if (function == "connect" && op->arguments.size() >= 4) {
- _guess_expression_type(p_context, op->arguments[3], connect_base);
+ if (i > 0) {
+ r_arghint += "\n";
}
+ r_arghint += _make_arguments_hint(E->get(), p_argidx);
+ i++;
+ }
+ return;
+ } else if (call->is_super || callee_type == GDScriptParser::Node::IDENTIFIER) {
+ base = p_context.base;
- } else {
- if (op->arguments.size() < 2 || op->arguments[1]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- return;
- }
- const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1]);
- function = id->name;
+ if (p_context.current_class) {
+ base_type = p_context.current_class->get_datatype();
+ _static = !p_context.current_function || p_context.current_function->is_static;
+ }
+ } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);
+ if (subscript->is_attribute) {
GDScriptCompletionIdentifier ci;
- if (_guess_expression_type(p_context, op->arguments[0], ci)) {
+ if (_guess_expression_type(p_context, subscript->base, ci)) {
base_type = ci.type;
base = ci.value;
} else {
return;
}
- _static = ci.type.is_meta_type;
- if (function == "connect" && op->arguments.size() >= 4) {
- _guess_expression_type(p_context, op->arguments[3], connect_base);
- }
+ _static = base_type.is_meta_type;
}
} else {
- if (!p_context._class || op->arguments.size() < 1 || op->arguments[0]->type != GDScriptParser::Node::TYPE_IDENTIFIER) {
- return;
- }
- base_type.has_type = true;
- base_type.kind = GDScriptParser::DataType::CLASS;
- base_type.class_type = const_cast<GDScriptParser::ClassNode *>(p_context._class);
- base_type.is_meta_type = p_context.function && p_context.function->_static;
- base = p_context.base;
-
- function = static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[0])->name;
-
- if (function == "connect" && op->arguments.size() >= 4) {
- _guess_expression_type(p_context, op->arguments[3], connect_base);
- }
+ return;
}
GDScriptCompletionIdentifier ci;
ci.type = base_type;
ci.value = base;
- _find_call_arguments(p_context, ci, function, p_argidx, _static, r_result, r_arghint);
-
- if (function == "connect" && p_argidx == 2) {
- Map<String, ScriptCodeCompletionOption> methods;
- _find_identifiers_in_base(p_context, connect_base, true, methods);
- 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);
- }
- }
+ _find_call_arguments(p_context, ci, call->function_name, p_argidx, _static, r_result, r_arghint);
r_forced = r_result.size() > 0;
}
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;
+ GDScriptAnalyzer analyzer(&parser);
+
+ parser.parse(p_code, p_path, true);
+ analyzer.analyze();
- parser.parse(p_code, p_path.get_base_dir(), false, p_path, true);
r_forced = false;
Map<String, ScriptCodeCompletionOption> options;
- GDScriptCompletionContext context;
- context._class = parser.get_completion_class();
- context.block = parser.get_completion_block();
- context.function = parser.get_completion_function();
- context.line = parser.get_completion_line();
-
- if (!context._class || context._class->owner == nullptr) {
- context.base = p_owner;
- context.base_path = p_path.get_base_dir();
- }
+ GDScriptParser::CompletionContext completion_context = parser.get_completion_context();
+ completion_context.base = p_owner;
bool is_function = false;
- switch (parser.get_completion_type()) {
- case GDScriptParser::COMPLETION_NONE: {
+ switch (completion_context.type) {
+ case GDScriptParser::COMPLETION_NONE:
+ break;
+ case GDScriptParser::COMPLETION_ANNOTATION: {
+ List<MethodInfo> annotations;
+ parser.get_annotation_list(&annotations);
+ for (const List<MethodInfo>::Element *E = annotations.front(); E != nullptr; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name.substr(1), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ if (E->get().arguments.size() > 0) {
+ option.insert_text += "(";
+ }
+ options.insert(option.display, option);
+ }
+ r_forced = true;
+ } break;
+ case GDScriptParser::COMPLETION_ANNOTATION_ARGUMENTS: {
+ if (completion_context.node == nullptr || completion_context.node->type != GDScriptParser::Node::ANNOTATION) {
+ break;
+ }
+ const GDScriptParser::AnnotationNode *annotation = static_cast<const GDScriptParser::AnnotationNode *>(completion_context.node);
+ _find_annotation_arguments(annotation, completion_context.current_argument, quote_style, options);
+ r_forced = true;
} break;
case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
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()) {
- ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ Variant::get_constants_for_type(completion_context.builtin_type, &constants);
+ for (const List<StringName>::Element *E = constants.front(); E != nullptr; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ bool valid = false;
+ Variant default_value = Variant::get_constant_value(completion_context.builtin_type, E->get(), &valid);
+ if (valid) {
+ option.default_value = default_value;
+ }
options.insert(option.display, option);
}
} break;
- case GDScriptParser::COMPLETION_PARENT_FUNCTION: {
- _find_identifiers_in_class(context, !context.function || context.function->_static, true, true, options);
+ case GDScriptParser::COMPLETION_INHERIT_TYPE: {
+ _list_available_types(true, completion_context, options);
+ r_forced = true;
} break;
- case GDScriptParser::COMPLETION_FUNCTION: {
- is_function = true;
- [[fallthrough]];
+ case GDScriptParser::COMPLETION_TYPE_NAME_OR_VOID: {
+ ScriptCodeCompletionOption option("void", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(option.display, option);
}
- case GDScriptParser::COMPLETION_IDENTIFIER: {
- _find_identifiers(context, is_function, options);
+ [[fallthrough]];
+ case GDScriptParser::COMPLETION_TYPE_NAME: {
+ _list_available_types(false, completion_context, options);
+ r_forced = true;
} break;
- case GDScriptParser::COMPLETION_GET_NODE: {
- if (p_owner) {
- List<String> opts;
- p_owner->get_argument_options("get_node", 0, &opts);
-
- for (List<String>::Element *E = opts.front(); E; E = E->next()) {
-
- String opt = E->get().strip_edges();
- if (opt.is_quoted()) {
- r_forced = true;
- String idopt = opt.unquote();
- if (idopt.replace("/", "_").is_valid_identifier()) {
- ScriptCodeCompletionOption option(idopt, ScriptCodeCompletionOption::KIND_NODE_PATH);
- options.insert(option.display, option);
- } else {
- ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH);
- options.insert(option.display, option);
- }
- }
+ case GDScriptParser::COMPLETION_PROPERTY_DECLARATION_OR_TYPE: {
+ _list_available_types(false, completion_context, options);
+ ScriptCodeCompletionOption get("get", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(get.display, get);
+ ScriptCodeCompletionOption set("set", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(set.display, set);
+ r_forced = true;
+ } break;
+ case GDScriptParser::COMPLETION_PROPERTY_DECLARATION: {
+ ScriptCodeCompletionOption get("get", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(get.display, get);
+ ScriptCodeCompletionOption set("set", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(set.display, set);
+ r_forced = true;
+ } break;
+ case GDScriptParser::COMPLETION_PROPERTY_METHOD: {
+ if (!completion_context.current_class) {
+ break;
+ }
+ for (int i = 0; i < completion_context.current_class->members.size(); i++) {
+ const GDScriptParser::ClassNode::Member &member = completion_context.current_class->members[i];
+ if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
+ continue;
}
-
- // Get autoloads
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
-
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
- }
- String name = s.get_slice("/", 1);
- ScriptCodeCompletionOption option(quote_style + "/root/" + name + quote_style, ScriptCodeCompletionOption::KIND_NODE_PATH);
- options.insert(option.display, option);
+ if (member.function->is_static) {
+ continue;
}
+ ScriptCodeCompletionOption option(member.function->identifier->name, ScriptCodeCompletionOption::KIND_FUNCTION);
+ options.insert(option.display, option);
}
+ r_forced = true;
} break;
- case GDScriptParser::COMPLETION_METHOD: {
- is_function = true;
- [[fallthrough]];
- }
- case GDScriptParser::COMPLETION_INDEX: {
- const GDScriptParser::Node *node = parser.get_completion_node();
- if (node->type != GDScriptParser::Node::TYPE_OPERATOR) {
+ case GDScriptParser::COMPLETION_ASSIGN: {
+ GDScriptCompletionIdentifier type;
+ if (!completion_context.node || completion_context.node->type != GDScriptParser::Node::ASSIGNMENT) {
break;
}
- const GDScriptParser::OperatorNode *op = static_cast<const GDScriptParser::OperatorNode *>(node);
- if (op->arguments.size() < 1) {
+ if (!_guess_expression_type(completion_context, static_cast<const GDScriptParser::AssignmentNode *>(completion_context.node)->assignee, type)) {
+ _find_identifiers(completion_context, false, options, 0);
+ r_forced = true;
break;
}
+ if (!type.enumeration.is_empty()) {
+ _find_enumeration_candidates(completion_context, type.enumeration, options);
+ r_forced = options.size() > 0;
+ } else {
+ _find_identifiers(completion_context, false, options, 0);
+ r_forced = true;
+ }
+ } break;
+ case GDScriptParser::COMPLETION_METHOD:
+ is_function = true;
+ [[fallthrough]];
+ case GDScriptParser::COMPLETION_IDENTIFIER: {
+ _find_identifiers(completion_context, is_function, options, 0);
+ } break;
+ case GDScriptParser::COMPLETION_ATTRIBUTE_METHOD:
+ is_function = true;
+ [[fallthrough]];
+ case GDScriptParser::COMPLETION_ATTRIBUTE: {
+ r_forced = true;
+ const GDScriptParser::SubscriptNode *attr = static_cast<const GDScriptParser::SubscriptNode *>(completion_context.node);
+ if (attr->base) {
+ GDScriptCompletionIdentifier base;
+ if (!_guess_expression_type(completion_context, attr->base, base)) {
+ break;
+ }
+
+ _find_identifiers_in_base(base, is_function, options, 0);
+ }
+ } break;
+ case GDScriptParser::COMPLETION_SUBSCRIPT: {
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(completion_context.node);
GDScriptCompletionIdentifier base;
- if (!_guess_expression_type(context, op->arguments[0], base)) {
+ if (!_guess_expression_type(completion_context, subscript->base, base)) {
break;
}
- GDScriptCompletionContext c = context;
- c.function = nullptr;
- c.block = nullptr;
+ GDScriptParser::CompletionContext c = completion_context;
+ c.current_function = nullptr;
+ c.current_suite = nullptr;
c.base = base.value.get_type() == Variant::OBJECT ? base.value.operator Object *() : nullptr;
if (base.type.kind == GDScriptParser::DataType::CLASS) {
- c._class = base.type.class_type;
+ c.current_class = base.type.class_type;
} else {
- c._class = nullptr;
+ c.current_class = nullptr;
+ }
+
+ _find_identifiers_in_base(base, false, options, 0);
+ } break;
+ case GDScriptParser::COMPLETION_TYPE_ATTRIBUTE: {
+ if (!completion_context.current_class) {
+ break;
+ }
+ const GDScriptParser::TypeNode *type = static_cast<const GDScriptParser::TypeNode *>(completion_context.node);
+ bool found = true;
+ GDScriptCompletionIdentifier base;
+ base.type.kind = GDScriptParser::DataType::CLASS;
+ base.type.type_source = GDScriptParser::DataType::INFERRED;
+ base.type.is_constant = true;
+ base.type.class_type = completion_context.current_class;
+ base.value = completion_context.base;
+
+ for (int i = 0; i < completion_context.current_argument; i++) {
+ GDScriptCompletionIdentifier ci;
+ if (!_guess_identifier_type_from_base(completion_context, base, type->type_chain[i]->name, ci)) {
+ found = false;
+ break;
+ }
+ base = ci;
}
- _find_identifiers_in_base(c, base, is_function, options);
+ // TODO: Improve this to only list types.
+ if (found) {
+ _find_identifiers_in_base(base, false, options, 0);
+ }
+ r_forced = true;
+ } break;
+ case GDScriptParser::COMPLETION_RESOURCE_PATH: {
+ if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) {
+ _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options);
+ r_forced = true;
+ }
} break;
case GDScriptParser::COMPLETION_CALL_ARGUMENTS: {
- _find_call_arguments(context, parser.get_completion_node(), parser.get_completion_argument_index(), options, r_forced, r_call_hint);
+ if (!completion_context.node) {
+ break;
+ }
+ _find_call_arguments(completion_context, completion_context.node, completion_context.current_argument, options, r_forced, r_call_hint);
} break;
- case GDScriptParser::COMPLETION_VIRTUAL_FUNC: {
- GDScriptParser::DataType native_type = context._class->base_type;
- while (native_type.has_type && native_type.kind != GDScriptParser::DataType::NATIVE) {
+ case GDScriptParser::COMPLETION_OVERRIDE_METHOD: {
+ GDScriptParser::DataType native_type = completion_context.current_class->base_type;
+ while (native_type.is_set() && native_type.kind != GDScriptParser::DataType::NATIVE) {
switch (native_type.kind) {
case GDScriptParser::DataType::CLASS: {
native_type = native_type.class_type->base_type;
} break;
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<GDScript> gds = native_type.script_type;
- if (gds.is_valid()) {
- Ref<GDScript> base = gds->get_base_script();
- if (base.is_valid()) {
- native_type.script_type = base;
- } else {
- native_type.native_type = gds->get_instance_base_type();
- native_type.kind = GDScriptParser::DataType::NATIVE;
- }
- } else {
- native_type.has_type = false;
- }
- } break;
default: {
- native_type.has_type = false;
+ native_type.kind = GDScriptParser::DataType::UNRESOLVED;
} break;
}
}
- if (!native_type.has_type) {
+ if (!native_type.is_set()) {
break;
}
- StringName class_name = native_type.native_type;
+ StringName class_name = _get_real_class_name(native_type.native_type);
if (!ClassDB::class_exists(class_name)) {
- class_name = String("_") + class_name;
- if (!ClassDB::class_exists(class_name)) {
- break;
- }
+ break;
}
bool use_type_hint = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints").operator bool();
@@ -2690,7 +2626,6 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path
List<MethodInfo> virtual_methods;
ClassDB::get_virtual_methods(class_name, &virtual_methods);
for (List<MethodInfo>::Element *E = virtual_methods.front(); E; E = E->next()) {
-
MethodInfo &mi = E->get();
String method_hint = mi.name;
if (method_hint.find(":") != -1) {
@@ -2735,245 +2670,41 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path
options.insert(option.display, option);
}
} break;
- case GDScriptParser::COMPLETION_YIELD: {
- const GDScriptParser::Node *node = parser.get_completion_node();
-
- GDScriptCompletionContext c = context;
- c.line = node->line;
- GDScriptCompletionIdentifier type;
- if (!_guess_expression_type(c, node, type)) {
- break;
- }
+ case GDScriptParser::COMPLETION_GET_NODE: {
+ if (p_owner) {
+ List<String> opts;
+ p_owner->get_argument_options("get_node", 0, &opts);
- GDScriptParser::DataType base_type = type.type;
- while (base_type.has_type) {
- switch (base_type.kind) {
- case GDScriptParser::DataType::CLASS: {
- for (int i = 0; i < base_type.class_type->_signals.size(); i++) {
- ScriptCodeCompletionOption option(base_type.class_type->_signals[i].name.operator String(), ScriptCodeCompletionOption::KIND_SIGNAL);
- option.insert_text = quote_style + option.display + quote_style;
+ for (List<String>::Element *E = opts.front(); E; E = E->next()) {
+ String opt = E->get().strip_edges();
+ if (opt.is_quoted()) {
+ r_forced = true;
+ String idopt = opt.unquote();
+ if (idopt.replace("/", "_").is_valid_identifier()) {
+ ScriptCodeCompletionOption option(idopt, ScriptCodeCompletionOption::KIND_NODE_PATH);
options.insert(option.display, option);
- }
- base_type = base_type.class_type->base_type;
- } break;
- case GDScriptParser::DataType::SCRIPT:
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<Script> scr = base_type.script_type;
- if (scr.is_valid()) {
- List<MethodInfo> signals;
- scr->get_script_signal_list(&signals);
- for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- 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()) {
- base_type.script_type = base_script;
- } else {
- base_type.kind = GDScriptParser::DataType::NATIVE;
- base_type.native_type = scr->get_instance_base_type();
- }
} else {
- base_type.has_type = false;
- }
- } break;
- case GDScriptParser::DataType::NATIVE: {
- base_type.has_type = false;
-
- StringName class_name = base_type.native_type;
- if (!ClassDB::class_exists(class_name)) {
- class_name = String("_") + class_name;
- if (!ClassDB::class_exists(class_name)) {
- break;
- }
- }
-
- List<MethodInfo> signals;
- ClassDB::get_signal_list(class_name, &signals);
- for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- ScriptCodeCompletionOption option(quote_style + E->get().name + quote_style, ScriptCodeCompletionOption::KIND_SIGNAL);
+ ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH);
options.insert(option.display, option);
}
- } break;
- default: {
- base_type.has_type = false;
}
}
- }
- } break;
- case GDScriptParser::COMPLETION_RESOURCE_PATH: {
- if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) {
- _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options);
- r_forced = true;
- }
- } break;
- case GDScriptParser::COMPLETION_ASSIGN: {
- GDScriptCompletionIdentifier type;
- if (!_guess_expression_type(context, parser.get_completion_node(), type)) {
- break;
- }
- if (!type.enumeration.empty()) {
- _find_enumeration_candidates(type.enumeration, options);
- r_forced = options.size() > 0;
- }
- } break;
- case GDScriptParser::COMPLETION_TYPE_HINT: {
- const GDScriptParser::ClassNode *clss = context._class;
- while (clss) {
- for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = clss->constant_expressions.front(); E; E = E->next()) {
- GDScriptCompletionIdentifier constant;
- GDScriptCompletionContext c = context;
- c.function = nullptr;
- c.block = nullptr;
- 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) {
- 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()) {
- 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++) {
- ScriptCodeCompletionOption option(Variant::get_type_name((Variant::Type)i), ScriptCodeCompletionOption::KIND_CLASS);
- options.insert(option.display, option);
- }
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
- }
- ScriptCodeCompletionOption option(s.get_slice("/", 1), ScriptCodeCompletionOption::KIND_CLASS);
- options.insert(option.display, option);
- }
- }
+ // Get autoloads.
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
- List<StringName> native_classes;
- ClassDB::get_class_list(&native_classes);
- for (List<StringName>::Element *E = native_classes.front(); E; E = E->next()) {
- String class_name = E->get().operator String();
- if (class_name.begins_with("_")) {
- class_name = class_name.right(1);
- }
- if (Engine::get_singleton()->has_singleton(class_name)) {
- continue;
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ String name = E->key();
+ ScriptCodeCompletionOption option(quote_style + "/root/" + name + quote_style, ScriptCodeCompletionOption::KIND_NODE_PATH);
+ options.insert(option.display, option);
}
- 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()) {
- ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
- options.insert(option.display, option);
- }
-
- if (parser.get_completion_identifier_is_function()) {
- ScriptCodeCompletionOption option("void", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
- options.insert(option.display, option);
}
- r_forced = true;
} break;
- case GDScriptParser::COMPLETION_TYPE_HINT_INDEX: {
- GDScriptCompletionIdentifier base;
- String index = parser.get_completion_cursor().operator String();
- if (!_guess_identifier_type(context, index.get_slice(".", 0), base)) {
- break;
- }
-
- GDScriptCompletionContext c = context;
- c._class = nullptr;
- c.function = nullptr;
- c.block = nullptr;
- bool finding = true;
- index = index.right(index.find(".") + 1);
- while (index.find(".") != -1) {
- String id = index.get_slice(".", 0);
-
- GDScriptCompletionIdentifier sub_base;
- if (!_guess_identifier_type_from_base(c, base, id, sub_base)) {
- finding = false;
- break;
- }
- index = index.right(index.find(".") + 1);
- base = sub_base;
- }
-
- if (!finding) {
+ case GDScriptParser::COMPLETION_SUPER_METHOD: {
+ if (!completion_context.current_class) {
break;
}
-
- GDScriptParser::DataType base_type = base.type;
- while (base_type.has_type) {
- switch (base_type.kind) {
- case GDScriptParser::DataType::CLASS: {
- if (base_type.class_type) {
- for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = base_type.class_type->constant_expressions.front(); E; E = E->next()) {
- GDScriptCompletionIdentifier constant;
- GDScriptCompletionContext c2 = context;
- c2._class = base_type.class_type;
- c2.function = nullptr;
- c2.block = nullptr;
- 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) {
- 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()) {
- ScriptCodeCompletionOption option(base_type.class_type->subclasses[i]->name.operator String(), ScriptCodeCompletionOption::KIND_CLASS);
- options.insert(option.display, option);
- }
- }
-
- base_type = base_type.class_type->base_type;
- } else {
- base_type.has_type = false;
- }
- } break;
- case GDScriptParser::DataType::SCRIPT:
- case GDScriptParser::DataType::GDSCRIPT: {
- Ref<Script> scr = base_type.script_type;
- if (scr.is_valid()) {
- Map<StringName, Variant> constants;
- scr->get_constants(&constants);
- for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
- Ref<Script> const_scr = E->value();
- if (const_scr.is_valid()) {
- ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
- options.insert(option.display, option);
- }
- }
- Ref<Script> base_script = scr->get_base_script();
- if (base_script.is_valid()) {
- base_type.script_type = base_script;
- } else {
- base_type.has_type = false;
- }
- } else {
- base_type.has_type = false;
- }
- } break;
- default: {
- base_type.has_type = false;
- } break;
- }
- }
- r_forced = options.size() > 0;
+ _find_identifiers_in_class(completion_context.current_class, true, false, true, options, 0);
} break;
}
@@ -3014,19 +2745,16 @@ String GDScriptLanguage::_get_indentation() const {
}
void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
-
String indent = _get_indentation();
Vector<String> lines = p_code.split("\n");
List<int> indent_stack;
for (int i = 0; i < lines.size(); i++) {
-
String l = lines[i];
int tc = 0;
for (int j = 0; j < l.length(); j++) {
if (l[j] == ' ' || l[j] == '\t') {
-
tc++;
} else {
break;
@@ -3034,8 +2762,9 @@ void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_t
}
String st = l.substr(tc, l.length()).strip_edges();
- if (st == "" || st.begins_with("#"))
+ if (st == "" || st.begins_with("#")) {
continue; //ignore!
+ }
int ilevel = 0;
if (indent_stack.size()) {
@@ -3049,12 +2778,12 @@ void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_t
indent_stack.pop_back();
}
- if (indent_stack.size() && indent_stack.back()->get() != tc)
+ if (indent_stack.size() && indent_stack.back()->get() != tc) {
indent_stack.push_back(tc); //this is not right but gets the job done
+ }
}
if (i >= p_from_line) {
-
l = "";
for (int j = 0; j < indent_stack.size(); j++) {
l += indent;
@@ -3070,8 +2799,9 @@ void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_t
p_code = "";
for (int i = 0; i < lines.size(); i++) {
- if (i > 0)
+ if (i > 0) {
p_code += "\n";
+ }
p_code += lines[i];
}
}
@@ -3081,45 +2811,19 @@ void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_t
static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, const String &p_symbol, bool p_is_function, GDScriptLanguage::LookupResult &r_result) {
GDScriptParser::DataType base_type = p_base;
- while (base_type.has_type) {
+ while (base_type.is_set()) {
switch (base_type.kind) {
case GDScriptParser::DataType::CLASS: {
if (base_type.class_type) {
- if (p_is_function) {
- for (int i = 0; i < base_type.class_type->functions.size(); i++) {
- if (base_type.class_type->functions[i]->name == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = base_type.class_type->functions[i]->line;
- return OK;
- }
- }
- for (int i = 0; i < base_type.class_type->static_functions.size(); i++) {
- if (base_type.class_type->static_functions[i]->name == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = base_type.class_type->static_functions[i]->line;
- return OK;
- }
- }
- } else {
- if (base_type.class_type->constant_expressions.has(p_symbol)) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = base_type.class_type->constant_expressions[p_symbol].expression->line;
- return OK;
- }
-
- for (int i = 0; i < base_type.class_type->variables.size(); i++) {
- if (base_type.class_type->variables[i].identifier == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = base_type.class_type->variables[i].line;
- return OK;
- }
- }
+ if (base_type.class_type->has_member(p_symbol)) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = base_type.class_type->get_member(p_symbol).get_line();
+ return OK;
}
base_type = base_type.class_type->base_type;
}
} break;
- case GDScriptParser::DataType::SCRIPT:
- case GDScriptParser::DataType::GDSCRIPT: {
+ case GDScriptParser::DataType::SCRIPT: {
Ref<Script> scr = base_type.script_type;
if (scr.is_valid()) {
int line = scr->get_member_line(p_symbol);
@@ -3137,17 +2841,14 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
base_type.native_type = scr->get_instance_base_type();
}
} else {
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
}
} break;
case GDScriptParser::DataType::NATIVE: {
- StringName class_name = base_type.native_type;
+ StringName class_name = _get_real_class_name(base_type.native_type);
if (!ClassDB::class_exists(class_name)) {
- class_name = String("_") + class_name;
- if (!ClassDB::class_exists(class_name)) {
- base_type.has_type = false;
- break;
- }
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
+ break;
}
if (ClassDB::has_method(class_name, p_symbol, true)) {
@@ -3187,15 +2888,11 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
}
}
- List<PropertyInfo> properties;
- ClassDB::get_property_list(class_name, &properties, true);
- for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().name == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
- r_result.class_name = base_type.native_type;
- r_result.class_member = p_symbol;
- return OK;
- }
+ if (ClassDB::has_property(class_name, p_symbol, true)) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
+ r_result.class_name = base_type.native_type;
+ r_result.class_member = p_symbol;
+ return OK;
}
StringName parent = ClassDB::get_parent_class(class_name);
@@ -3206,11 +2903,11 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
base_type.native_type = parent;
}
} else {
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
}
} break;
case GDScriptParser::DataType::BUILTIN: {
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
if (Variant::has_constant(base_type.builtin_type, p_symbol)) {
r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
@@ -3226,7 +2923,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
v = v_ref;
} else {
Callable::CallError err;
- v = Variant::construct(base_type.builtin_type, nullptr, 0, err);
+ Variant::construct(base_type.builtin_type, v, NULL, 0, err);
if (err.error != Callable::CallError::CALL_OK) {
break;
}
@@ -3249,7 +2946,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
}
} break;
default: {
- base_type.has_type = false;
+ base_type.kind = GDScriptParser::DataType::UNRESOLVED;
} break;
}
}
@@ -3258,7 +2955,6 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
}
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)) {
r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
@@ -3282,13 +2978,11 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
}
}
- for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
- if (GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i)) == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name = "@GDScript";
- r_result.class_member = p_symbol;
- return OK;
- }
+ if (GDScriptUtilityFunctions::function_exists(p_symbol)) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = "@GDScript";
+ r_result.class_member = p_symbol;
+ return OK;
}
if ("PI" == p_symbol || "TAU" == p_symbol || "INF" == p_symbol || "NAN" == p_symbol) {
@@ -3299,26 +2993,18 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
}
GDScriptParser parser;
- parser.parse(p_code, p_path.get_base_dir(), false, p_path, true);
+ parser.parse(p_code, p_path, true);
+ GDScriptAnalyzer analyzer(&parser);
+ analyzer.analyze();
- if (parser.get_completion_type() == GDScriptParser::COMPLETION_NONE) {
- return ERR_CANT_RESOLVE;
- }
-
- GDScriptCompletionContext context;
- context._class = parser.get_completion_class();
- context.function = parser.get_completion_function();
- context.block = parser.get_completion_block();
- context.line = parser.get_completion_line();
- context.base = p_owner;
- context.base_path = p_path.get_base_dir();
+ GDScriptParser::CompletionContext context = parser.get_completion_context();
- if (context._class && context._class->extends_class.size() > 0) {
+ if (context.current_class && context.current_class->extends.size() > 0) {
bool success = false;
- ClassDB::get_integer_constant(context._class->extends_class[0], p_symbol, &success);
+ ClassDB::get_integer_constant(context.current_class->extends[0], p_symbol, &success);
if (success) {
r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name = context._class->extends_class[0];
+ r_result.class_name = context.current_class->extends[0];
r_result.class_member = p_symbol;
return OK;
}
@@ -3326,58 +3012,40 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
bool is_function = false;
- switch (parser.get_completion_type()) {
+ switch (context.type) {
case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name = Variant::get_type_name(parser.get_completion_built_in_constant());
+ r_result.class_name = Variant::get_type_name(context.builtin_type);
r_result.class_member = p_symbol;
return OK;
} break;
- case GDScriptParser::COMPLETION_PARENT_FUNCTION:
- case GDScriptParser::COMPLETION_FUNCTION: {
+ case GDScriptParser::COMPLETION_SUPER_METHOD:
+ case GDScriptParser::COMPLETION_METHOD: {
is_function = true;
[[fallthrough]];
}
case GDScriptParser::COMPLETION_IDENTIFIER: {
-
- if (!is_function) {
- is_function = parser.get_completion_identifier_is_function();
- }
-
GDScriptParser::DataType base_type;
- if (context._class) {
- if (parser.get_completion_type() != GDScriptParser::COMPLETION_PARENT_FUNCTION) {
- base_type.has_type = true;
- base_type.kind = GDScriptParser::DataType::CLASS;
- base_type.class_type = const_cast<GDScriptParser::ClassNode *>(context._class);
+ if (context.current_class) {
+ if (context.type != GDScriptParser::COMPLETION_SUPER_METHOD) {
+ base_type = context.current_class->get_datatype();
} else {
- base_type = context._class->base_type;
+ base_type = context.current_class->base_type;
}
} else {
break;
}
- if (!is_function && context.block) {
- // Lookup local variables
- const GDScriptParser::BlockNode *block = context.block;
- while (block) {
- if (block->variables.has(p_symbol)) {
+ if (!is_function && context.current_suite) {
+ // Lookup local variables.
+ const GDScriptParser::SuiteNode *suite = context.current_suite;
+ while (suite) {
+ if (suite->has_local(p_symbol)) {
r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = block->variables[p_symbol]->line;
- return OK;
- }
- block = block->parent_block;
- }
- }
-
- if (context.function && context.function->name != StringName()) {
- // Lookup function arguments
- for (int i = 0; i < context.function->arguments.size(); i++) {
- if (context.function->arguments[i] == p_symbol) {
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = context.function->line;
+ r_result.location = suite->get_local(p_symbol).start_line;
return OK;
}
+ suite = suite->parent_block;
}
}
@@ -3386,40 +3054,27 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
}
if (!is_function) {
- // Guess in autoloads as singletons
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
-
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
-
- String s = E->get().name;
- if (!s.begins_with("autoload/"))
- continue;
- String name = s.get_slice("/", 1);
- if (name == String(p_symbol)) {
-
- String path = ProjectSettings::get_singleton()->get(s);
- if (path.begins_with("*")) {
- String script = path.substr(1, path.length());
-
- if (!script.ends_with(".gd")) {
- // Not a script, try find the script anyway,
- // may have some success
- script = script.get_basename() + ".gd";
- }
-
- if (FileAccess::exists(script)) {
+ // Guess in autoloads as singletons.
+ if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) {
+ const ProjectSettings::AutoloadInfo &singleton = ProjectSettings::get_singleton()->get_autoload(p_symbol);
+ if (singleton.is_singleton) {
+ String script = singleton.path;
+ if (!script.ends_with(".gd")) {
+ // Not a script, try find the script anyway,
+ // may have some success.
+ script = script.get_basename() + ".gd";
+ }
- r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location = 0;
- r_result.script = ResourceLoader::load(script);
- return OK;
- }
+ if (FileAccess::exists(script)) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = 0;
+ r_result.script = ResourceLoader::load(script);
+ return OK;
}
}
}
- // Global
+ // Global.
Map<StringName, int> classes = GDScriptLanguage::get_singleton()->get_global_map();
if (classes.has(p_symbol)) {
Variant value = GDScriptLanguage::get_singleton()->get_global_array()[classes[p_symbol]];
@@ -3446,7 +3101,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
// We cannot determine the exact nature of the identifier here
// Otherwise these codes would work
StringName enumName = ClassDB::get_integer_constant_enum("@GlobalScope", p_symbol, true);
- if (enumName != nullptr) {
+ if (enumName != NULL) {
r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM;
r_result.class_name = "@GlobalScope";
r_result.class_member = enumName;
@@ -3466,17 +3121,20 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
}
}
} break;
- case GDScriptParser::COMPLETION_METHOD: {
+ case GDScriptParser::COMPLETION_ATTRIBUTE_METHOD: {
is_function = true;
[[fallthrough]];
}
- case GDScriptParser::COMPLETION_INDEX: {
- const GDScriptParser::Node *node = parser.get_completion_node();
- if (node->type != GDScriptParser::Node::TYPE_OPERATOR) {
+ case GDScriptParser::COMPLETION_ATTRIBUTE: {
+ if (context.node->type != GDScriptParser::Node::SUBSCRIPT) {
+ break;
+ }
+ const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(context.node);
+ if (!subscript->is_attribute) {
break;
}
GDScriptCompletionIdentifier base;
- if (!_guess_expression_type(context, static_cast<const GDScriptParser::OperatorNode *>(node)->arguments[0], base)) {
+ if (!_guess_expression_type(context, subscript->base, base)) {
break;
}
@@ -3484,19 +3142,16 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
return OK;
}
} break;
- case GDScriptParser::COMPLETION_VIRTUAL_FUNC: {
- GDScriptParser::DataType base_type = context._class->base_type;
+ case GDScriptParser::COMPLETION_OVERRIDE_METHOD: {
+ GDScriptParser::DataType base_type = context.current_class->base_type;
if (_lookup_symbol_from_base(base_type, p_symbol, true, r_result) == OK) {
return OK;
}
} break;
- case GDScriptParser::COMPLETION_TYPE_HINT: {
-
- GDScriptParser::DataType base_type = context._class->base_type;
- base_type.has_type = true;
- base_type.kind = GDScriptParser::DataType::CLASS;
- base_type.class_type = const_cast<GDScriptParser::ClassNode *>(context._class);
+ case GDScriptParser::COMPLETION_TYPE_NAME_OR_VOID:
+ case GDScriptParser::COMPLETION_TYPE_NAME: {
+ GDScriptParser::DataType base_type = context.current_class->get_datatype();
if (_lookup_symbol_from_base(base_type, p_symbol, false, r_result) == OK) {
return OK;
diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp
index 44640411bb..2171426e6f 100644
--- a/modules/gdscript/gdscript_function.cpp
+++ b/modules/gdscript/gdscript_function.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,1637 +30,31 @@
#include "gdscript_function.h"
-#include "core/os/os.h"
#include "gdscript.h"
-#include "gdscript_functions.h"
-
-Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_instance, GDScript *p_script, Variant &self, Variant &static_ref, Variant *p_stack, String &r_error) const {
-
- int address = p_address & ADDR_MASK;
-
- //sequential table (jump table generated by compiler)
- switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) {
-
- case ADDR_TYPE_SELF: {
-#ifdef DEBUG_ENABLED
- if (unlikely(!p_instance)) {
- r_error = "Cannot access self without instance.";
- return nullptr;
- }
-#endif
- return &self;
- } break;
- case ADDR_TYPE_CLASS: {
-
- return &static_ref;
- } break;
- case ADDR_TYPE_MEMBER: {
-#ifdef DEBUG_ENABLED
- if (unlikely(!p_instance)) {
- r_error = "Cannot access member without instance.";
- return nullptr;
- }
-#endif
- //member indexing is O(1)
- return &p_instance->members.write[address];
- } break;
- case ADDR_TYPE_CLASS_CONSTANT: {
-
- //todo change to index!
- GDScript *s = p_script;
-#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V(address, _global_names_count, nullptr);
-#endif
- const StringName *sn = &_global_names_ptr[address];
-
- while (s) {
- GDScript *o = s;
- while (o) {
-
- Map<StringName, Variant>::Element *E = o->constants.find(*sn);
- if (E) {
- return &E->get();
- }
- o = o->_owner;
- }
- s = s->_base;
- }
-
- ERR_FAIL_V_MSG(nullptr, "GDScriptCompiler bug.");
- } break;
- case ADDR_TYPE_LOCAL_CONSTANT: {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V(address, _constant_count, nullptr);
-#endif
- return &_constants_ptr[address];
- } break;
- case ADDR_TYPE_STACK:
- case ADDR_TYPE_STACK_VARIABLE: {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V(address, _stack_size, nullptr);
-#endif
- return &p_stack[address];
- } break;
- case ADDR_TYPE_GLOBAL: {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), nullptr);
-#endif
- return &GDScriptLanguage::get_singleton()->get_global_array()[address];
- } break;
-#ifdef TOOLS_ENABLED
- case ADDR_TYPE_NAMED_GLOBAL: {
-#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V(address, _named_globals_count, nullptr);
-#endif
- StringName id = _named_globals_ptr[address];
-
- if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(id)) {
- return (Variant *)&GDScriptLanguage::get_singleton()->get_named_globals_map()[id];
- } else {
- r_error = "Autoload singleton '" + String(id) + "' has been removed.";
- return nullptr;
- }
- } break;
-#endif
- case ADDR_TYPE_NIL: {
- return &nil;
- } break;
- }
-
- ERR_FAIL_V_MSG(nullptr, "Bad code! (unknown addressing mode).");
- return nullptr;
-}
-
-#ifdef DEBUG_ENABLED
-static String _get_var_type(const Variant *p_var) {
-
- String basestr;
-
- if (p_var->get_type() == Variant::OBJECT) {
- bool was_freed;
- Object *bobj = p_var->get_validated_object_with_check(was_freed);
- if (!bobj) {
- if (was_freed) {
- basestr = "null instance";
- } else {
- basestr = "previously freed";
- }
- } else {
- if (bobj->get_script_instance())
- basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")";
- else
- basestr = bobj->get_class();
- }
-
- } else {
- basestr = Variant::get_type_name(p_var->get_type());
- }
-
- return basestr;
-}
-#endif // DEBUG_ENABLED
-
-String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const {
-
- String err_text;
-
- if (p_err.error == Callable::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(Variant::Type(p_err.expected)) + ".";
- }
- } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
- } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
- } else if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
- err_text = "Invalid call. Nonexistent " + p_where + ".";
- } else if (p_err.error == Callable::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 \
- static const void *switch_table_ops[] = { \
- &&OPCODE_OPERATOR, \
- &&OPCODE_EXTENDS_TEST, \
- &&OPCODE_IS_BUILTIN, \
- &&OPCODE_SET, \
- &&OPCODE_GET, \
- &&OPCODE_SET_NAMED, \
- &&OPCODE_GET_NAMED, \
- &&OPCODE_SET_MEMBER, \
- &&OPCODE_GET_MEMBER, \
- &&OPCODE_ASSIGN, \
- &&OPCODE_ASSIGN_TRUE, \
- &&OPCODE_ASSIGN_FALSE, \
- &&OPCODE_ASSIGN_TYPED_BUILTIN, \
- &&OPCODE_ASSIGN_TYPED_NATIVE, \
- &&OPCODE_ASSIGN_TYPED_SCRIPT, \
- &&OPCODE_CAST_TO_BUILTIN, \
- &&OPCODE_CAST_TO_NATIVE, \
- &&OPCODE_CAST_TO_SCRIPT, \
- &&OPCODE_CONSTRUCT, \
- &&OPCODE_CONSTRUCT_ARRAY, \
- &&OPCODE_CONSTRUCT_DICTIONARY, \
- &&OPCODE_CALL, \
- &&OPCODE_CALL_RETURN, \
- &&OPCODE_CALL_BUILT_IN, \
- &&OPCODE_CALL_SELF, \
- &&OPCODE_CALL_SELF_BASE, \
- &&OPCODE_YIELD, \
- &&OPCODE_YIELD_SIGNAL, \
- &&OPCODE_YIELD_RESUME, \
- &&OPCODE_JUMP, \
- &&OPCODE_JUMP_IF, \
- &&OPCODE_JUMP_IF_NOT, \
- &&OPCODE_JUMP_TO_DEF_ARGUMENT, \
- &&OPCODE_RETURN, \
- &&OPCODE_ITERATE_BEGIN, \
- &&OPCODE_ITERATE, \
- &&OPCODE_ASSERT, \
- &&OPCODE_BREAKPOINT, \
- &&OPCODE_LINE, \
- &&OPCODE_END \
- };
-
-#define OPCODE(m_op) \
- m_op:
-#define OPCODE_WHILE(m_test)
-#define OPCODES_END \
- OPSEXIT:
-#define OPCODES_OUT \
- OPSOUT:
-#define DISPATCH_OPCODE goto *switch_table_ops[_code_ptr[ip]]
-#define OPCODE_SWITCH(m_test) DISPATCH_OPCODE;
-#define OPCODE_BREAK goto OPSEXIT
-#define OPCODE_OUT goto OPSOUT
-#else
-#define OPCODES_TABLE
-#define OPCODE(m_op) case m_op:
-#define OPCODE_WHILE(m_test) while (m_test)
-#define OPCODES_END
-#define OPCODES_OUT
-#define DISPATCH_OPCODE continue
-#define OPCODE_SWITCH(m_test) switch (m_test)
-#define OPCODE_BREAK break
-#define OPCODE_OUT break
-#endif
-
-Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_args, int p_argcount, Callable::CallError &r_err, CallState *p_state) {
-
- OPCODES_TABLE;
-
- if (!_code_ptr) {
-
- return Variant();
- }
-
- r_err.error = Callable::CallError::CALL_OK;
-
- Variant self;
- Variant static_ref;
- Variant retvalue;
- Variant *stack = nullptr;
- Variant **call_args;
- int defarg = 0;
-
-#ifdef DEBUG_ENABLED
-
- //GDScriptLanguage::get_singleton()->calls++;
-
-#endif
-
- uint32_t alloca_size = 0;
- GDScript *script;
- int ip = 0;
- int line = _initial_line;
-
- if (p_state) {
- //use existing (supplied) state (yielded)
- stack = (Variant *)p_state->stack.ptr();
- call_args = (Variant **)&p_state->stack.ptr()[sizeof(Variant) * p_state->stack_size]; //ptr() to avoid bounds check
- line = p_state->line;
- ip = p_state->ip;
- alloca_size = p_state->stack.size();
- script = static_cast<GDScript *>(ObjectDB::get_instance(p_state->script_id));
- p_instance = p_state->instance_id.is_valid() ? static_cast<GDScriptInstance *>(ObjectDB::get_instance(p_state->instance_id)->get_script_instance()) : nullptr;
- defarg = p_state->defarg;
- self = p_state->self;
-
- } else {
-
- if (p_argcount != _argument_count) {
-
- if (p_argcount > _argument_count) {
-
- r_err.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_err.argument = _argument_count;
-
- return Variant();
- } else if (p_argcount < _argument_count - _default_arg_count) {
-
- r_err.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_err.argument = _argument_count - _default_arg_count;
- return Variant();
- } else {
-
- defarg = _argument_count - p_argcount;
- }
- }
-
- alloca_size = sizeof(Variant *) * _call_size + sizeof(Variant) * _stack_size;
-
- if (alloca_size) {
-
- uint8_t *aptr = (uint8_t *)alloca(alloca_size);
-
- if (_stack_size) {
-
- stack = (Variant *)aptr;
- for (int i = 0; i < p_argcount; i++) {
- if (!argument_types[i].has_type) {
- memnew_placement(&stack[i], Variant(*p_args[i]));
- continue;
- }
-
- if (!argument_types[i].is_type(*p_args[i], true)) {
- r_err.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_err.argument = i;
- r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT;
- return Variant();
- }
- if (argument_types[i].kind == GDScriptDataType::BUILTIN) {
- Variant arg = Variant::construct(argument_types[i].builtin_type, &p_args[i], 1, r_err);
- memnew_placement(&stack[i], Variant(arg));
- } else {
- memnew_placement(&stack[i], Variant(*p_args[i]));
- }
- }
- for (int i = p_argcount; i < _stack_size; i++) {
- memnew_placement(&stack[i], Variant);
- }
- } else {
- stack = nullptr;
- }
-
- if (_call_size) {
-
- call_args = (Variant **)&aptr[sizeof(Variant) * _stack_size];
- } else {
-
- call_args = nullptr;
- }
-
- } else {
- stack = nullptr;
- call_args = nullptr;
- }
-
- if (p_instance) {
- if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) {
-
- self = REF(static_cast<Reference *>(p_instance->owner));
- } else {
- self = p_instance->owner;
- }
- script = p_instance->script.ptr();
- } else {
- script = _script;
- }
- }
-
- String err_text;
-
-#ifdef DEBUG_ENABLED
-
- if (EngineDebugger::is_active())
- GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line);
-
-#define GD_ERR_BREAK(m_cond) \
- { \
- if (unlikely(m_cond)) { \
- _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \
- OPCODE_BREAK; \
- } \
- }
-
-#define CHECK_SPACE(m_space) \
- GD_ERR_BREAK((ip + m_space) > _code_size)
-
-#define GET_VARIANT_PTR(m_v, m_code_ofs) \
- Variant *m_v; \
- m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); \
- if (unlikely(!m_v)) \
- OPCODE_BREAK;
-
-#else
-#define GD_ERR_BREAK(m_cond)
-#define CHECK_SPACE(m_space)
-#define GET_VARIANT_PTR(m_v, m_code_ofs) \
- Variant *m_v; \
- m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text);
-
-#endif
-
-#ifdef DEBUG_ENABLED
-
- uint64_t function_start_time = 0;
- uint64_t function_call_time = 0;
-
- if (GDScriptLanguage::get_singleton()->profiling) {
- function_start_time = OS::get_singleton()->get_ticks_usec();
- function_call_time = 0;
- profile.call_count++;
- profile.frame_call_count++;
- }
- bool exit_ok = false;
- bool yielded = false;
-#endif
-
-#ifdef DEBUG_ENABLED
- OPCODE_WHILE(ip < _code_size) {
- int last_opcode = _code_ptr[ip];
-#else
- OPCODE_WHILE(true) {
-#endif
-
- OPCODE_SWITCH(_code_ptr[ip]) {
-
- OPCODE(OPCODE_OPERATOR) {
-
- CHECK_SPACE(5);
-
- bool valid;
- Variant::Operator op = (Variant::Operator)_code_ptr[ip + 1];
- GD_ERR_BREAK(op >= Variant::OP_MAX);
-
- GET_VARIANT_PTR(a, 2);
- GET_VARIANT_PTR(b, 3);
- GET_VARIANT_PTR(dst, 4);
-
-#ifdef DEBUG_ENABLED
-
- Variant ret;
- Variant::evaluate(op, *a, *b, ret, valid);
-#else
- Variant::evaluate(op, *a, *b, *dst, valid);
-#endif
-#ifdef DEBUG_ENABLED
- if (!valid) {
-
- if (ret.get_type() == Variant::STRING) {
- //return a string when invalid with the error
- err_text = ret;
- err_text += " in operator '" + Variant::get_operator_name(op) + "'.";
- } else {
- err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'.";
- }
- OPCODE_BREAK;
- }
- *dst = ret;
-#endif
- ip += 5;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_EXTENDS_TEST) {
-
- CHECK_SPACE(4);
-
- GET_VARIANT_PTR(a, 1);
- GET_VARIANT_PTR(b, 2);
- GET_VARIANT_PTR(dst, 3);
-
-#ifdef DEBUG_ENABLED
- if (b->get_type() != Variant::OBJECT || b->operator Object *() == nullptr) {
-
- err_text = "Right operand of 'is' is not a class.";
- OPCODE_BREAK;
- }
-#endif
-
- bool extends_ok = false;
- if (a->get_type() == Variant::OBJECT && a->operator Object *() != nullptr) {
-
-#ifdef DEBUG_ENABLED
- bool was_freed;
- Object *obj_A = a->get_validated_object_with_check(was_freed);
-
- if (was_freed) {
- err_text = "Left operand of 'is' is a previously freed instance.";
- OPCODE_BREAK;
- }
-
- Object *obj_B = b->get_validated_object_with_check(was_freed);
-
- if (was_freed) {
- err_text = "Right operand of 'is' is a previously freed instance.";
- OPCODE_BREAK;
- }
-#else
-
- Object *obj_A = *a;
- Object *obj_B = *b;
-#endif // DEBUG_ENABLED
-
- GDScript *scr_B = Object::cast_to<GDScript>(obj_B);
-
- if (scr_B) {
- //if B is a script, the only valid condition is that A has an instance which inherits from the script
- //in other situation, this shoul return false.
-
- if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) {
-
- GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr());
- //bool found=false;
- while (cmp) {
-
- if (cmp == scr_B) {
- //inherits from script, all ok
- extends_ok = true;
- break;
- }
-
- cmp = cmp->_base;
- }
- }
-
- } else {
-
- GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(obj_B);
-
-#ifdef DEBUG_ENABLED
- if (!nc) {
-
- err_text = "Right operand of 'is' is not a class (type: '" + obj_B->get_class() + "').";
- OPCODE_BREAK;
- }
-#endif
- extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name());
- }
- }
-
- *dst = extends_ok;
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_IS_BUILTIN) {
-
- CHECK_SPACE(4);
-
- GET_VARIANT_PTR(value, 1);
- Variant::Type var_type = (Variant::Type)_code_ptr[ip + 2];
- GET_VARIANT_PTR(dst, 3);
-
- GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX);
-
- *dst = value->get_type() == var_type;
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_SET) {
-
- CHECK_SPACE(3);
-
- GET_VARIANT_PTR(dst, 1);
- GET_VARIANT_PTR(index, 2);
- GET_VARIANT_PTR(value, 3);
-
- bool valid;
- dst->set(*index, *value, &valid);
-
-#ifdef DEBUG_ENABLED
- if (!valid) {
- String v = index->operator String();
- if (v != "") {
- v = "'" + v + "'";
- } else {
- v = "of type '" + _get_var_type(index) + "'";
- }
- err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'";
- OPCODE_BREAK;
- }
-#endif
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_GET) {
-
- CHECK_SPACE(3);
-
- GET_VARIANT_PTR(src, 1);
- GET_VARIANT_PTR(index, 2);
- GET_VARIANT_PTR(dst, 3);
-
- bool valid;
-#ifdef DEBUG_ENABLED
- //allow better error message in cases where src and dst are the same stack position
- Variant ret = src->get(*index, &valid);
-#else
- *dst = src->get(*index, &valid);
-
-#endif
-#ifdef DEBUG_ENABLED
- if (!valid) {
- String v = index->operator String();
- if (v != "") {
- v = "'" + v + "'";
- } else {
- v = "of type '" + _get_var_type(index) + "'";
- }
- err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "').";
- OPCODE_BREAK;
- }
- *dst = ret;
-#endif
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_SET_NAMED) {
-
- CHECK_SPACE(3);
-
- GET_VARIANT_PTR(dst, 1);
- GET_VARIANT_PTR(value, 3);
-
- int indexname = _code_ptr[ip + 2];
-
- GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
- const StringName *index = &_global_names_ptr[indexname];
-
- bool valid;
- dst->set_named(*index, *value, &valid);
-
-#ifdef DEBUG_ENABLED
- if (!valid) {
- String err_type;
- err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'.";
- OPCODE_BREAK;
- }
-#endif
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_GET_NAMED) {
-
- CHECK_SPACE(4);
-
- GET_VARIANT_PTR(src, 1);
- GET_VARIANT_PTR(dst, 3);
-
- int indexname = _code_ptr[ip + 2];
-
- GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
- const StringName *index = &_global_names_ptr[indexname];
-
- bool valid;
-#ifdef DEBUG_ENABLED
- //allow better error message in cases where src and dst are the same stack position
- Variant ret = src->get_named(*index, &valid);
-
-#else
- *dst = src->get_named(*index, &valid);
-#endif
-#ifdef DEBUG_ENABLED
- if (!valid) {
- if (src->has_method(*index)) {
- err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' or funcref(obj, \"" + index->operator String() + "\") ?";
- } else {
- err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "').";
- }
- OPCODE_BREAK;
- }
- *dst = ret;
-#endif
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_SET_MEMBER) {
-
- CHECK_SPACE(3);
- int indexname = _code_ptr[ip + 1];
- GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
- const StringName *index = &_global_names_ptr[indexname];
- GET_VARIANT_PTR(src, 2);
-
- bool valid;
-#ifndef DEBUG_ENABLED
- ClassDB::set_property(p_instance->owner, *index, *src, &valid);
-#else
- bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid);
- if (!ok) {
- err_text = "Internal error setting property: " + String(*index);
- OPCODE_BREAK;
- } else if (!valid) {
- err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + ".";
- OPCODE_BREAK;
- }
-#endif
- ip += 3;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_GET_MEMBER) {
-
- CHECK_SPACE(3);
- int indexname = _code_ptr[ip + 1];
- GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
- const StringName *index = &_global_names_ptr[indexname];
- GET_VARIANT_PTR(dst, 2);
-
-#ifndef DEBUG_ENABLED
- ClassDB::get_property(p_instance->owner, *index, *dst);
-#else
- bool ok = ClassDB::get_property(p_instance->owner, *index, *dst);
- if (!ok) {
- err_text = "Internal error getting property: " + String(*index);
- OPCODE_BREAK;
- }
-#endif
- ip += 3;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN) {
-
- CHECK_SPACE(3);
- GET_VARIANT_PTR(dst, 1);
- GET_VARIANT_PTR(src, 2);
-
- *dst = *src;
-
- ip += 3;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN_TRUE) {
-
- CHECK_SPACE(2);
- GET_VARIANT_PTR(dst, 1);
-
- *dst = true;
-
- ip += 2;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN_FALSE) {
-
- CHECK_SPACE(2);
- GET_VARIANT_PTR(dst, 1);
-
- *dst = false;
-
- ip += 2;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN_TYPED_BUILTIN) {
-
- CHECK_SPACE(4);
- GET_VARIANT_PTR(dst, 2);
- GET_VARIANT_PTR(src, 3);
-
- Variant::Type var_type = (Variant::Type)_code_ptr[ip + 1];
- GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX);
-
- if (src->get_type() != var_type) {
-#ifdef DEBUG_ENABLED
- if (Variant::can_convert_strict(src->get_type(), var_type)) {
-#endif // DEBUG_ENABLED
- Callable::CallError ce;
- *dst = Variant::construct(var_type, const_cast<const Variant **>(&src), 1, ce);
- } else {
-#ifdef DEBUG_ENABLED
- err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) +
- "' to a variable of type '" + Variant::get_type_name(var_type) + "'.";
- OPCODE_BREAK;
- }
- } else {
-#endif // DEBUG_ENABLED
- *dst = *src;
- }
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN_TYPED_NATIVE) {
-
- CHECK_SPACE(4);
- GET_VARIANT_PTR(dst, 2);
- GET_VARIANT_PTR(src, 3);
-
-#ifdef DEBUG_ENABLED
- GET_VARIANT_PTR(type, 1);
- GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(type->operator Object *());
- GD_ERR_BREAK(!nc);
- if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
- err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) +
- "' to a variable of type '" + nc->get_name() + "'.";
- OPCODE_BREAK;
- }
- Object *src_obj = src->operator Object *();
-
- if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) {
- err_text = "Trying to assign value of type '" + src_obj->get_class_name() +
- "' to a variable of type '" + nc->get_name() + "'.";
- OPCODE_BREAK;
- }
-#endif // DEBUG_ENABLED
- *dst = *src;
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSIGN_TYPED_SCRIPT) {
-
- CHECK_SPACE(4);
- GET_VARIANT_PTR(dst, 2);
- GET_VARIANT_PTR(src, 3);
-
-#ifdef DEBUG_ENABLED
- GET_VARIANT_PTR(type, 1);
- Script *base_type = Object::cast_to<Script>(type->operator Object *());
-
- GD_ERR_BREAK(!base_type);
-
- if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
- err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'.";
- OPCODE_BREAK;
- }
-
- if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) {
-
- ScriptInstance *scr_inst = src->operator Object *()->get_script_instance();
- if (!scr_inst) {
- err_text = "Trying to assign value of type '" + src->operator Object *()->get_class_name() +
- "' to a variable of type '" + base_type->get_path().get_file() + "'.";
- OPCODE_BREAK;
- }
-
- Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr();
- bool valid = false;
-
- while (src_type) {
- if (src_type == base_type) {
- valid = true;
- break;
- }
- src_type = src_type->get_base_script().ptr();
- }
-
- if (!valid) {
- err_text = "Trying to assign value of type '" + src->operator Object *()->get_script_instance()->get_script()->get_path().get_file() +
- "' to a variable of type '" + base_type->get_path().get_file() + "'.";
- OPCODE_BREAK;
- }
- }
-#endif // DEBUG_ENABLED
-
- *dst = *src;
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CAST_TO_BUILTIN) {
-
- CHECK_SPACE(4);
- Variant::Type to_type = (Variant::Type)_code_ptr[ip + 1];
- GET_VARIANT_PTR(src, 2);
- GET_VARIANT_PTR(dst, 3);
-
- GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX);
-
- Callable::CallError err;
- *dst = Variant::construct(to_type, (const Variant **)&src, 1, err);
-
-#ifdef DEBUG_ENABLED
- if (err.error != Callable::CallError::CALL_OK) {
- err_text = "Invalid cast: could not convert value to '" + Variant::get_type_name(to_type) + "'.";
- OPCODE_BREAK;
- }
-#endif
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CAST_TO_NATIVE) {
-
- CHECK_SPACE(4);
- GET_VARIANT_PTR(to_type, 1);
- GET_VARIANT_PTR(src, 2);
- GET_VARIANT_PTR(dst, 3);
-
- GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(to_type->operator Object *());
- GD_ERR_BREAK(!nc);
-
-#ifdef DEBUG_ENABLED
- if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
- err_text = "Invalid cast: can't convert a non-object value to an object type.";
- OPCODE_BREAK;
- }
-#endif
- Object *src_obj = src->operator Object *();
-
- if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) {
- *dst = Variant(); // invalid cast, assign NULL
- } else {
- *dst = *src;
- }
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CAST_TO_SCRIPT) {
-
- CHECK_SPACE(4);
- GET_VARIANT_PTR(to_type, 1);
- GET_VARIANT_PTR(src, 2);
- GET_VARIANT_PTR(dst, 3);
-
- Script *base_type = Object::cast_to<Script>(to_type->operator Object *());
-
- GD_ERR_BREAK(!base_type);
-
-#ifdef DEBUG_ENABLED
- if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
- err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'.";
- OPCODE_BREAK;
- }
-#endif
-
- bool valid = false;
-
- if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) {
-
- ScriptInstance *scr_inst = src->operator Object *()->get_script_instance();
-
- if (scr_inst) {
-
- Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr();
-
- while (src_type) {
- if (src_type == base_type) {
- valid = true;
- break;
- }
- src_type = src_type->get_base_script().ptr();
- }
- }
- }
-
- if (valid) {
- *dst = *src; // Valid cast, copy the source object
- } else {
- *dst = Variant(); // invalid cast, assign NULL
- }
-
- ip += 4;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CONSTRUCT) {
-
- CHECK_SPACE(2);
- Variant::Type t = Variant::Type(_code_ptr[ip + 1]);
- int argc = _code_ptr[ip + 2];
- CHECK_SPACE(argc + 2);
- Variant **argptrs = call_args;
- for (int i = 0; i < argc; i++) {
- GET_VARIANT_PTR(v, 3 + i);
- argptrs[i] = v;
- }
-
- GET_VARIANT_PTR(dst, 3 + argc);
- Callable::CallError err;
- *dst = Variant::construct(t, (const Variant **)argptrs, argc, err);
-
-#ifdef DEBUG_ENABLED
- if (err.error != Callable::CallError::CALL_OK) {
-
- err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs);
- OPCODE_BREAK;
- }
-#endif
-
- ip += 4 + argc;
- //construct a basic type
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CONSTRUCT_ARRAY) {
-
- CHECK_SPACE(1);
- int argc = _code_ptr[ip + 1];
- Array array; //arrays are always shared
- array.resize(argc);
- CHECK_SPACE(argc + 2);
-
- for (int i = 0; i < argc; i++) {
- GET_VARIANT_PTR(v, 2 + i);
- array[i] = *v;
- }
-
- GET_VARIANT_PTR(dst, 2 + argc);
-
- *dst = array;
-
- ip += 3 + argc;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CONSTRUCT_DICTIONARY) {
-
- CHECK_SPACE(1);
- int argc = _code_ptr[ip + 1];
- Dictionary dict; //arrays are always shared
-
- CHECK_SPACE(argc * 2 + 2);
-
- for (int i = 0; i < argc; i++) {
-
- GET_VARIANT_PTR(k, 2 + i * 2 + 0);
- GET_VARIANT_PTR(v, 2 + i * 2 + 1);
- dict[*k] = *v;
- }
-
- GET_VARIANT_PTR(dst, 2 + argc * 2);
-
- *dst = dict;
-
- ip += 3 + argc * 2;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CALL_RETURN)
- OPCODE(OPCODE_CALL) {
-
- CHECK_SPACE(4);
- bool call_ret = _code_ptr[ip] == OPCODE_CALL_RETURN;
-
- int argc = _code_ptr[ip + 1];
- GET_VARIANT_PTR(base, 2);
- int nameg = _code_ptr[ip + 3];
-
- GD_ERR_BREAK(nameg < 0 || nameg >= _global_names_count);
- const StringName *methodname = &_global_names_ptr[nameg];
-
- GD_ERR_BREAK(argc < 0);
- ip += 4;
- CHECK_SPACE(argc + 1);
- Variant **argptrs = call_args;
-
- for (int i = 0; i < argc; i++) {
- GET_VARIANT_PTR(v, i);
- argptrs[i] = v;
- }
-
-#ifdef DEBUG_ENABLED
- uint64_t call_time = 0;
-
- if (GDScriptLanguage::get_singleton()->profiling) {
- call_time = OS::get_singleton()->get_ticks_usec();
- }
-
-#endif
- Callable::CallError err;
- if (call_ret) {
-
- GET_VARIANT_PTR(ret, argc);
- base->call_ptr(*methodname, (const Variant **)argptrs, argc, ret, err);
- } else {
-
- base->call_ptr(*methodname, (const Variant **)argptrs, argc, nullptr, err);
- }
-#ifdef DEBUG_ENABLED
- if (GDScriptLanguage::get_singleton()->profiling) {
- function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
- }
-
- if (err.error != Callable::CallError::CALL_OK) {
-
- String methodstr = *methodname;
- String basestr = _get_var_type(base);
-
- if (methodstr == "call") {
- if (argc >= 1) {
- methodstr = String(*argptrs[0]) + " (via call)";
- if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- err.argument += 1;
- }
- }
- } else if (methodstr == "free") {
-
- if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
-
- if (base->is_ref()) {
- err_text = "Attempted to free a reference.";
- OPCODE_BREAK;
- } else if (base->get_type() == Variant::OBJECT) {
-
- err_text = "Attempted to free a locked object (calling or emitting).";
- OPCODE_BREAK;
- }
- }
- }
- err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs);
- OPCODE_BREAK;
- }
-#endif
-
- //_call_func(nullptr,base,*methodname,ip,argc,p_instance,stack);
- ip += argc + 1;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CALL_BUILT_IN) {
-
- CHECK_SPACE(4);
-
- GDScriptFunctions::Function func = GDScriptFunctions::Function(_code_ptr[ip + 1]);
- int argc = _code_ptr[ip + 2];
- GD_ERR_BREAK(argc < 0);
-
- ip += 3;
- CHECK_SPACE(argc + 1);
- Variant **argptrs = call_args;
-
- for (int i = 0; i < argc; i++) {
- GET_VARIANT_PTR(v, i);
- argptrs[i] = v;
- }
-
- GET_VARIANT_PTR(dst, argc);
-
- Callable::CallError err;
-
- GDScriptFunctions::call(func, (const Variant **)argptrs, argc, *dst, err);
-
-#ifdef DEBUG_ENABLED
- if (err.error != Callable::CallError::CALL_OK) {
-
- String methodstr = GDScriptFunctions::get_func_name(func);
- if (dst->get_type() == Variant::STRING) {
- //call provided error string
- err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst);
- } else {
- err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs);
- }
- OPCODE_BREAK;
- }
-#endif
- ip += argc + 1;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_CALL_SELF) {
-
- OPCODE_BREAK;
- }
-
- OPCODE(OPCODE_CALL_SELF_BASE) {
-
- CHECK_SPACE(2);
- int self_fun = _code_ptr[ip + 1];
-
-#ifdef DEBUG_ENABLED
- if (self_fun < 0 || self_fun >= _global_names_count) {
-
- err_text = "compiler bug, function name not found";
- OPCODE_BREAK;
- }
-#endif
- const StringName *methodname = &_global_names_ptr[self_fun];
-
- int argc = _code_ptr[ip + 2];
-
- CHECK_SPACE(2 + argc + 1);
-
- Variant **argptrs = call_args;
-
- for (int i = 0; i < argc; i++) {
- GET_VARIANT_PTR(v, i + 3);
- argptrs[i] = v;
- }
-
- GET_VARIANT_PTR(dst, argc + 3);
-
- const GDScript *gds = _script;
-
- const Map<StringName, GDScriptFunction *>::Element *E = nullptr;
- while (gds->base.ptr()) {
- gds = gds->base.ptr();
- E = gds->member_functions.find(*methodname);
- if (E)
- break;
- }
-
- Callable::CallError err;
-
- if (E) {
-
- *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err);
- } else if (gds->native.ptr()) {
-
- if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
-
- MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname);
- if (!mb) {
- err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- } else {
- *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err);
- }
- } else {
- err.error = Callable::CallError::CALL_OK;
- }
- } else {
-
- if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
- err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- } else {
- err.error = Callable::CallError::CALL_OK;
- }
- }
-
- if (err.error != Callable::CallError::CALL_OK) {
-
- String methodstr = *methodname;
- err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs);
-
- OPCODE_BREAK;
- }
-
- ip += 4 + argc;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_YIELD)
- OPCODE(OPCODE_YIELD_SIGNAL) {
-
- int ipofs = 1;
- if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) {
- CHECK_SPACE(4);
- ipofs += 2;
- } else {
- CHECK_SPACE(2);
- }
-
- Ref<GDScriptFunctionState> gdfs = memnew(GDScriptFunctionState);
- gdfs->function = this;
-
- gdfs->state.stack.resize(alloca_size);
- //copy variant stack
- for (int i = 0; i < _stack_size; i++) {
- memnew_placement(&gdfs->state.stack.write[sizeof(Variant) * i], Variant(stack[i]));
- }
- gdfs->state.stack_size = _stack_size;
- gdfs->state.self = self;
- gdfs->state.alloca_size = alloca_size;
- gdfs->state.ip = ip + ipofs;
- gdfs->state.line = line;
- gdfs->state.script_id = script->get_instance_id();
-#ifdef DEBUG_ENABLED
- gdfs->state.script_path = _script->get_path();
-#endif
- gdfs->state.instance_id = (p_instance && p_instance->get_owner()) ? p_instance->get_owner()->get_instance_id() : ObjectID();
- gdfs->state.defarg = defarg;
- gdfs->function = this;
-
- retvalue = gdfs;
-
- if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) {
- //do the oneshot connect
- GET_VARIANT_PTR(argobj, 1);
- GET_VARIANT_PTR(argname, 2);
-
-#ifdef DEBUG_ENABLED
- if (argobj->get_type() != Variant::OBJECT) {
- err_text = "First argument of yield() not of type object.";
- OPCODE_BREAK;
- }
- if (argname->get_type() != Variant::STRING) {
- err_text = "Second argument of yield() not a string (for signal name).";
- OPCODE_BREAK;
- }
-#endif
-
-#ifdef DEBUG_ENABLED
- bool was_freed;
- Object *obj = argobj->get_validated_object_with_check(was_freed);
- String signal = argname->operator String();
-
- if (was_freed) {
- err_text = "First argument of yield() is a previously freed instance.";
- OPCODE_BREAK;
- }
-
- if (!obj) {
- err_text = "First argument of yield() is null.";
- OPCODE_BREAK;
- }
- if (signal.length() == 0) {
-
- err_text = "Second argument of yield() is an empty string (for signal name).";
- OPCODE_BREAK;
- }
-
- Error err = obj->connect_compat(signal, gdfs.ptr(), "_signal_callback", varray(gdfs), Object::CONNECT_ONESHOT);
- if (err != OK) {
- err_text = "Error connecting to signal: " + signal + " during yield().";
- OPCODE_BREAK;
- }
-#else
- Object *obj = argobj->operator Object *();
- String signal = argname->operator String();
-
- obj->connect_compat(signal, gdfs.ptr(), "_signal_callback", varray(gdfs), Object::CONNECT_ONESHOT);
-#endif
- }
-
-#ifdef DEBUG_ENABLED
- exit_ok = true;
- yielded = true;
-#endif
- OPCODE_BREAK;
- }
-
- OPCODE(OPCODE_YIELD_RESUME) {
-
- CHECK_SPACE(2);
-#ifdef DEBUG_ENABLED
- if (!p_state) {
- err_text = ("Invalid Resume (bug?)");
- OPCODE_BREAK;
- }
-#endif
- GET_VARIANT_PTR(result, 1);
- *result = p_state->result;
- ip += 2;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_JUMP) {
-
- CHECK_SPACE(2);
- int to = _code_ptr[ip + 1];
-
- GD_ERR_BREAK(to < 0 || to > _code_size);
- ip = to;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_JUMP_IF) {
-
- CHECK_SPACE(3);
-
- GET_VARIANT_PTR(test, 1);
-
- bool result = test->booleanize();
-
- if (result) {
- int to = _code_ptr[ip + 2];
- GD_ERR_BREAK(to < 0 || to > _code_size);
- ip = to;
- } else {
- ip += 3;
- }
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_JUMP_IF_NOT) {
-
- CHECK_SPACE(3);
-
- GET_VARIANT_PTR(test, 1);
-
- bool result = test->booleanize();
-
- if (!result) {
- int to = _code_ptr[ip + 2];
- GD_ERR_BREAK(to < 0 || to > _code_size);
- ip = to;
- } else {
- ip += 3;
- }
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_JUMP_TO_DEF_ARGUMENT) {
-
- CHECK_SPACE(2);
- ip = _default_arg_ptr[defarg];
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_RETURN) {
-
- CHECK_SPACE(2);
- GET_VARIANT_PTR(r, 1);
- retvalue = *r;
-#ifdef DEBUG_ENABLED
- exit_ok = true;
-#endif
- OPCODE_BREAK;
- }
-
- OPCODE(OPCODE_ITERATE_BEGIN) {
-
- CHECK_SPACE(8); //space for this a regular iterate
-
- GET_VARIANT_PTR(counter, 1);
- GET_VARIANT_PTR(container, 2);
-
- bool valid;
- if (!container->iter_init(*counter, valid)) {
-#ifdef DEBUG_ENABLED
- if (!valid) {
- err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "'.";
- OPCODE_BREAK;
- }
-#endif
- int jumpto = _code_ptr[ip + 3];
- GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
- ip = jumpto;
- } else {
- GET_VARIANT_PTR(iterator, 4);
-
- *iterator = container->iter_get(*counter, valid);
-#ifdef DEBUG_ENABLED
- if (!valid) {
- err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "'.";
- OPCODE_BREAK;
- }
-#endif
- ip += 5; //skip regular iterate which is always next
- }
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ITERATE) {
-
- CHECK_SPACE(4);
-
- GET_VARIANT_PTR(counter, 1);
- GET_VARIANT_PTR(container, 2);
-
- bool valid;
- if (!container->iter_next(*counter, valid)) {
-#ifdef DEBUG_ENABLED
- if (!valid) {
- err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?).";
- OPCODE_BREAK;
- }
-#endif
- int jumpto = _code_ptr[ip + 3];
- GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
- ip = jumpto;
- } else {
- GET_VARIANT_PTR(iterator, 4);
-
- *iterator = container->iter_get(*counter, valid);
-#ifdef DEBUG_ENABLED
- if (!valid) {
- err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?).";
- OPCODE_BREAK;
- }
-#endif
- ip += 5; //loop again
- }
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_ASSERT) {
- CHECK_SPACE(3);
-
-#ifdef DEBUG_ENABLED
- GET_VARIANT_PTR(test, 1);
- GET_VARIANT_PTR(message, 2);
- bool result = test->booleanize();
-
- if (!result) {
- const String &message_str = *message;
- if (message_str.empty()) {
- err_text = "Assertion failed.";
- } else {
- err_text = "Assertion failed: " + message_str;
- }
- OPCODE_BREAK;
- }
-
-#endif
- ip += 3;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_BREAKPOINT) {
-#ifdef DEBUG_ENABLED
- if (EngineDebugger::is_active()) {
- GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true);
- }
-#endif
- ip += 1;
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_LINE) {
- CHECK_SPACE(2);
-
- line = _code_ptr[ip + 1];
- ip += 2;
-
- if (EngineDebugger::is_active()) {
- // line
- bool do_break = false;
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) {
-
- if (EngineDebugger::get_script_debugger()->get_depth() <= 0)
- EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1);
- if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0)
- do_break = true;
- }
-
- if (EngineDebugger::get_script_debugger()->is_breakpoint(line, source))
- do_break = true;
-
- if (do_break) {
- GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true);
- }
-
- EngineDebugger::get_singleton()->line_poll();
- }
- }
- DISPATCH_OPCODE;
-
- OPCODE(OPCODE_END) {
-#ifdef DEBUG_ENABLED
- exit_ok = true;
-#endif
- OPCODE_BREAK;
- }
-
-#if 0 // Enable for debugging.
- default: {
- err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip);
- OPCODE_BREAK;
- }
-#endif
- }
-
- OPCODES_END
-#ifdef DEBUG_ENABLED
- if (exit_ok)
- OPCODE_OUT;
- //error
- // function, file, line, error, explanation
- String err_file;
- if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && 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 && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->name != "")
- err_func = p_instance->script->name + "." + err_func;
- int err_line = line;
- if (err_text == "") {
- err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please).";
- }
-
- if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) {
- // debugger break did not happen
-
- _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT);
- }
-
-#endif
- OPCODE_OUT;
- }
-
- OPCODES_OUT
-#ifdef DEBUG_ENABLED
- if (GDScriptLanguage::get_singleton()->profiling) {
- uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time;
- profile.total_time += time_taken;
- profile.self_time += time_taken - function_call_time;
- profile.frame_total_time += time_taken;
- profile.frame_self_time += time_taken - function_call_time;
- GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time;
- }
-
- // 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 (EngineDebugger::is_active())
- GDScriptLanguage::get_singleton()->exit_function();
-#endif
-
- if (_stack_size) {
- //free stack
- for (int i = 0; i < _stack_size; i++)
- stack[i].~Variant();
- }
-
-#ifdef DEBUG_ENABLED
- }
-#endif
-
- return retvalue;
-}
const int *GDScriptFunction::get_code() const {
-
return _code_ptr;
}
-int GDScriptFunction::get_code_size() const {
+int GDScriptFunction::get_code_size() const {
return _code_size;
}
Variant GDScriptFunction::get_constant(int p_idx) const {
-
ERR_FAIL_INDEX_V(p_idx, constants.size(), "<errconst>");
return constants[p_idx];
}
StringName GDScriptFunction::get_global_name(int p_idx) const {
-
ERR_FAIL_INDEX_V(p_idx, global_names.size(), "<errgname>");
return global_names[p_idx];
}
int GDScriptFunction::get_default_argument_count() const {
-
return _default_arg_count;
}
-int GDScriptFunction::get_default_argument_addr(int p_idx) const {
+int GDScriptFunction::get_default_argument_addr(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, default_arguments.size(), -1);
return default_arguments[p_idx];
}
@@ -1675,45 +69,38 @@ GDScriptDataType GDScriptFunction::get_argument_type(int p_idx) const {
}
StringName GDScriptFunction::get_name() const {
-
return name;
}
int GDScriptFunction::get_max_stack_size() const {
-
return _stack_size;
}
struct _GDFKC {
-
int order;
List<int> pos;
};
struct _GDFKCS {
-
int order;
StringName id;
int pos;
bool operator<(const _GDFKCS &p_r) const {
-
return order < p_r.order;
}
};
void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<StringName, int>> *r_stackvars) const {
-
int oc = 0;
Map<StringName, _GDFKC> sdmap;
for (const List<StackDebug>::Element *E = stack_debug.front(); E; E = E->next()) {
-
const StackDebug &sd = E->get();
- if (sd.line > p_line)
+ if (sd.line > p_line) {
break;
+ }
if (sd.added) {
-
if (!sdmap.has(sd.identifier)) {
_GDFKC d;
d.order = oc++;
@@ -1724,18 +111,17 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String
sdmap[sd.identifier].pos.push_back(sd.pos);
}
} else {
-
ERR_CONTINUE(!sdmap.has(sd.identifier));
sdmap[sd.identifier].pos.pop_back();
- if (sdmap[sd.identifier].pos.empty())
+ if (sdmap[sd.identifier].pos.is_empty()) {
sdmap.erase(sd.identifier);
+ }
}
}
List<_GDFKCS> stackpositions;
for (Map<StringName, _GDFKC>::Element *E = sdmap.front(); E; E = E->next()) {
-
_GDFKCS spp;
spp.id = E->key();
spp.order = E->get().order;
@@ -1746,7 +132,6 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String
stackpositions.sort();
for (List<_GDFKCS>::Element *E = stackpositions.front(); E; E = E->next()) {
-
Pair<StringName, int> p;
p.first = E->get().id;
p.second = E->get().pos;
@@ -1754,32 +139,13 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String
}
}
-GDScriptFunction::GDScriptFunction() :
- function_list(this) {
-
- _stack_size = 0;
- _call_size = 0;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+GDScriptFunction::GDScriptFunction() {
name = "<anonymous>";
#ifdef DEBUG_ENABLED
- _func_cname = nullptr;
-
{
MutexLock lock(GDScriptLanguage::get_singleton()->lock);
-
GDScriptLanguage::get_singleton()->function_list.add(&function_list);
}
-
- profile.call_count = 0;
- profile.self_time = 0;
- profile.total_time = 0;
- profile.frame_call_count = 0;
- profile.frame_self_time = 0;
- profile.frame_total_time = 0;
- profile.last_frame_call_count = 0;
- profile.last_frame_self_time = 0;
- profile.last_frame_total_time = 0;
-
#endif
}
@@ -1795,7 +161,6 @@ GDScriptFunction::~GDScriptFunction() {
/////////////////////
Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
Variant arg;
r_error.error = Callable::CallError::CALL_OK;
@@ -1828,17 +193,19 @@ Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_ar
}
bool GDScriptFunctionState::is_valid(bool p_extended_check) const {
-
- if (function == nullptr)
+ if (function == nullptr) {
return false;
+ }
if (p_extended_check) {
- // Class instance gone? (Otherwise script is valid for sure, because the instance has a ref to the script)
- if (state.instance_id.is_valid() && !ObjectDB::get_instance(state.instance_id)) {
+ MutexLock lock(GDScriptLanguage::get_singleton()->lock);
+
+ // Script gone?
+ if (!scripts_list.in_list()) {
return false;
}
- // Script gone? (Static method, so there's no instance whose ref to the script can ensure it's valid)
- if (!ObjectDB::get_instance(state.script_id)) {
+ // Class instance gone? (if not static function)
+ if (state.instance && !instances_list.in_list()) {
return false;
}
}
@@ -1847,21 +214,27 @@ bool GDScriptFunctionState::is_valid(bool p_extended_check) const {
}
Variant GDScriptFunctionState::resume(const Variant &p_arg) {
-
ERR_FAIL_COND_V(!function, Variant());
- if (state.instance_id.is_valid() && !ObjectDB::get_instance(state.instance_id)) {
+ {
+ MutexLock lock(GDScriptLanguage::singleton->lock);
+
+ if (!scripts_list.in_list()) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_V_MSG(Variant(), "Resumed function '" + String(function->get_name()) + "()' after yield, but class instance is gone. At script: " + state.script_path + ":" + itos(state.line));
+ ERR_FAIL_V_MSG(Variant(), "Resumed function '" + state.function_name + "()' after await, but script is gone. At script: " + state.script_path + ":" + itos(state.line));
#else
- return Variant();
+ return Variant();
#endif
- }
- if (!ObjectDB::get_instance(state.script_id)) {
+ }
+ if (state.instance && !instances_list.in_list()) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_V_MSG(Variant(), "Resumed function '" + String(function->get_name()) + "()' after yield, but script is gone. At script: " + state.script_path + ":" + itos(state.line));
+ ERR_FAIL_V_MSG(Variant(), "Resumed function '" + state.function_name + "()' after await, but class instance is gone. At script: " + state.script_path + ":" + itos(state.line));
#else
- return Variant();
+ return Variant();
#endif
+ }
+ // Do these now to avoid locking again after the call
+ scripts_list.remove_from_list();
+ instances_list.remove_from_list();
}
state.result = p_arg;
@@ -1871,7 +244,7 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
bool completed = true;
// If the return value is a GDScriptFunctionState reference,
- // then the function did yield again after resuming.
+ // then the function did awaited again after resuming.
if (ret.is_ref()) {
GDScriptFunctionState *gdfs = Object::cast_to<GDScriptFunctionState>(ret);
if (gdfs && gdfs->function == function) {
@@ -1891,13 +264,8 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
}
#ifdef DEBUG_ENABLED
- if (EngineDebugger::is_active())
+ if (EngineDebugger::is_active()) {
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
}
@@ -1905,8 +273,17 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
return ret;
}
-void GDScriptFunctionState::_bind_methods() {
+void GDScriptFunctionState::_clear_stack() {
+ if (state.stack_size) {
+ Variant *stack = (Variant *)state.stack.ptr();
+ for (int i = 0; i < state.stack_size; i++) {
+ stack[i].~Variant();
+ }
+ state.stack_size = 0;
+ }
+}
+void GDScriptFunctionState::_bind_methods() {
ClassDB::bind_method(D_METHOD("resume", "arg"), &GDScriptFunctionState::resume, DEFVAL(Variant()));
ClassDB::bind_method(D_METHOD("is_valid", "extended_check"), &GDScriptFunctionState::is_valid, DEFVAL(false));
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &GDScriptFunctionState::_signal_callback, MethodInfo("_signal_callback"));
@@ -1914,18 +291,18 @@ void GDScriptFunctionState::_bind_methods() {
ADD_SIGNAL(MethodInfo("completed", PropertyInfo(Variant::NIL, "result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT)));
}
-GDScriptFunctionState::GDScriptFunctionState() {
-
+GDScriptFunctionState::GDScriptFunctionState() :
+ scripts_list(this),
+ instances_list(this) {
function = nullptr;
}
GDScriptFunctionState::~GDScriptFunctionState() {
+ _clear_stack();
- if (function != nullptr) {
- //never called, deinitialize stack
- for (int i = 0; i < state.stack_size; i++) {
- Variant *v = (Variant *)&state.stack[sizeof(Variant) * i];
- v->~Variant();
- }
+ {
+ MutexLock lock(GDScriptLanguage::singleton->lock);
+ scripts_list.remove_from_list();
+ instances_list.remove_from_list();
}
}
diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h
index 9d8e23d994..6c791836b9 100644
--- a/modules/gdscript/gdscript_function.h
+++ b/modules/gdscript/gdscript_function.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,32 +31,39 @@
#ifndef GDSCRIPT_FUNCTION_H
#define GDSCRIPT_FUNCTION_H
+#include "core/object/reference.h"
+#include "core/object/script_language.h"
#include "core/os/thread.h"
-#include "core/pair.h"
-#include "core/reference.h"
-#include "core/script_language.h"
-#include "core/self_list.h"
-#include "core/string_name.h"
-#include "core/variant.h"
+#include "core/string/string_name.h"
+#include "core/templates/pair.h"
+#include "core/templates/self_list.h"
+#include "core/variant/variant.h"
+#include "gdscript_utility_functions.h"
class GDScriptInstance;
class GDScript;
struct GDScriptDataType {
- bool has_type;
- enum {
+ enum Kind {
UNINITIALIZED,
BUILTIN,
NATIVE,
SCRIPT,
GDSCRIPT,
- } kind;
- Variant::Type builtin_type;
+ };
+
+ Kind kind = UNINITIALIZED;
+
+ bool has_type = false;
+ Variant::Type builtin_type = Variant::NIL;
StringName native_type;
- Ref<Script> script_type;
+ Script *script_type = nullptr;
+ Ref<Script> script_type_ref;
bool is_type(const Variant &p_variant, bool p_allow_implicit_conversion = false) const {
- if (!has_type) return true; // Can't type check
+ if (!has_type) {
+ return true; // Can't type check
+ }
switch (kind) {
case UNINITIALIZED:
@@ -146,22 +153,26 @@ struct GDScriptDataType {
return info;
}
- GDScriptDataType() :
- has_type(false),
- kind(UNINITIALIZED),
- builtin_type(Variant::NIL) {}
+ GDScriptDataType() {}
};
class GDScriptFunction {
public:
enum Opcode {
OPCODE_OPERATOR,
+ OPCODE_OPERATOR_VALIDATED,
OPCODE_EXTENDS_TEST,
OPCODE_IS_BUILTIN,
- OPCODE_SET,
- OPCODE_GET,
+ OPCODE_SET_KEYED,
+ OPCODE_SET_KEYED_VALIDATED,
+ OPCODE_SET_INDEXED_VALIDATED,
+ OPCODE_GET_KEYED,
+ OPCODE_GET_KEYED_VALIDATED,
+ OPCODE_GET_INDEXED_VALIDATED,
OPCODE_SET_NAMED,
+ OPCODE_SET_NAMED_VALIDATED,
OPCODE_GET_NAMED,
+ OPCODE_GET_NAMED_VALIDATED,
OPCODE_SET_MEMBER,
OPCODE_GET_MEMBER,
OPCODE_ASSIGN,
@@ -173,24 +184,103 @@ public:
OPCODE_CAST_TO_BUILTIN,
OPCODE_CAST_TO_NATIVE,
OPCODE_CAST_TO_SCRIPT,
- OPCODE_CONSTRUCT, //only for basic types!!
+ OPCODE_CONSTRUCT, // Only for basic types!
+ OPCODE_CONSTRUCT_VALIDATED, // Only for basic types!
OPCODE_CONSTRUCT_ARRAY,
OPCODE_CONSTRUCT_DICTIONARY,
OPCODE_CALL,
OPCODE_CALL_RETURN,
- OPCODE_CALL_BUILT_IN,
- OPCODE_CALL_SELF,
+ OPCODE_CALL_ASYNC,
+ OPCODE_CALL_UTILITY,
+ OPCODE_CALL_UTILITY_VALIDATED,
+ OPCODE_CALL_GDSCRIPT_UTILITY,
+ OPCODE_CALL_BUILTIN_TYPE_VALIDATED,
OPCODE_CALL_SELF_BASE,
- OPCODE_YIELD,
- OPCODE_YIELD_SIGNAL,
- OPCODE_YIELD_RESUME,
+ OPCODE_CALL_METHOD_BIND,
+ OPCODE_CALL_METHOD_BIND_RET,
+ // ptrcall have one instruction per return type.
+ OPCODE_CALL_PTRCALL_NO_RETURN,
+ OPCODE_CALL_PTRCALL_BOOL,
+ OPCODE_CALL_PTRCALL_INT,
+ OPCODE_CALL_PTRCALL_FLOAT,
+ OPCODE_CALL_PTRCALL_STRING,
+ OPCODE_CALL_PTRCALL_VECTOR2,
+ OPCODE_CALL_PTRCALL_VECTOR2I,
+ OPCODE_CALL_PTRCALL_RECT2,
+ OPCODE_CALL_PTRCALL_RECT2I,
+ OPCODE_CALL_PTRCALL_VECTOR3,
+ OPCODE_CALL_PTRCALL_VECTOR3I,
+ OPCODE_CALL_PTRCALL_TRANSFORM2D,
+ OPCODE_CALL_PTRCALL_PLANE,
+ OPCODE_CALL_PTRCALL_QUAT,
+ OPCODE_CALL_PTRCALL_AABB,
+ OPCODE_CALL_PTRCALL_BASIS,
+ OPCODE_CALL_PTRCALL_TRANSFORM,
+ OPCODE_CALL_PTRCALL_COLOR,
+ OPCODE_CALL_PTRCALL_STRING_NAME,
+ OPCODE_CALL_PTRCALL_NODE_PATH,
+ OPCODE_CALL_PTRCALL_RID,
+ OPCODE_CALL_PTRCALL_OBJECT,
+ OPCODE_CALL_PTRCALL_CALLABLE,
+ OPCODE_CALL_PTRCALL_SIGNAL,
+ OPCODE_CALL_PTRCALL_DICTIONARY,
+ OPCODE_CALL_PTRCALL_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_BYTE_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_INT32_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_INT64_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_FLOAT32_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_FLOAT64_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_STRING_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_VECTOR2_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_VECTOR3_ARRAY,
+ OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY,
+ OPCODE_AWAIT,
+ OPCODE_AWAIT_RESUME,
OPCODE_JUMP,
OPCODE_JUMP_IF,
OPCODE_JUMP_IF_NOT,
OPCODE_JUMP_TO_DEF_ARGUMENT,
OPCODE_RETURN,
OPCODE_ITERATE_BEGIN,
+ OPCODE_ITERATE_BEGIN_INT,
+ OPCODE_ITERATE_BEGIN_FLOAT,
+ OPCODE_ITERATE_BEGIN_VECTOR2,
+ OPCODE_ITERATE_BEGIN_VECTOR2I,
+ OPCODE_ITERATE_BEGIN_VECTOR3,
+ OPCODE_ITERATE_BEGIN_VECTOR3I,
+ OPCODE_ITERATE_BEGIN_STRING,
+ OPCODE_ITERATE_BEGIN_DICTIONARY,
+ OPCODE_ITERATE_BEGIN_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY,
+ OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY,
+ OPCODE_ITERATE_BEGIN_OBJECT,
OPCODE_ITERATE,
+ OPCODE_ITERATE_INT,
+ OPCODE_ITERATE_FLOAT,
+ OPCODE_ITERATE_VECTOR2,
+ OPCODE_ITERATE_VECTOR2I,
+ OPCODE_ITERATE_VECTOR3,
+ OPCODE_ITERATE_VECTOR3I,
+ OPCODE_ITERATE_STRING,
+ OPCODE_ITERATE_DICTIONARY,
+ OPCODE_ITERATE_ARRAY,
+ OPCODE_ITERATE_PACKED_BYTE_ARRAY,
+ OPCODE_ITERATE_PACKED_INT32_ARRAY,
+ OPCODE_ITERATE_PACKED_INT64_ARRAY,
+ OPCODE_ITERATE_PACKED_FLOAT32_ARRAY,
+ OPCODE_ITERATE_PACKED_FLOAT64_ARRAY,
+ OPCODE_ITERATE_PACKED_STRING_ARRAY,
+ OPCODE_ITERATE_PACKED_VECTOR2_ARRAY,
+ OPCODE_ITERATE_PACKED_VECTOR3_ARRAY,
+ OPCODE_ITERATE_PACKED_COLOR_ARRAY,
+ OPCODE_ITERATE_OBJECT,
OPCODE_ASSERT,
OPCODE_BREAKPOINT,
OPCODE_LINE,
@@ -213,8 +303,13 @@ public:
ADDR_TYPE_NIL = 9
};
- struct StackDebug {
+ enum Instruction {
+ INSTR_BITS = 20,
+ INSTR_MASK = ((1 << INSTR_BITS) - 1),
+ INSTR_ARGS_MASK = ~INSTR_MASK,
+ };
+ struct StackDebug {
int line;
int pos;
bool added;
@@ -223,44 +318,77 @@ public:
private:
friend class GDScriptCompiler;
+ friend class GDScriptByteCodeGenerator;
StringName source;
mutable Variant nil;
- mutable Variant *_constants_ptr;
- int _constant_count;
- const StringName *_global_names_ptr;
- int _global_names_count;
-#ifdef TOOLS_ENABLED
- const StringName *_named_globals_ptr;
- int _named_globals_count;
-#endif
- const int *_default_arg_ptr;
- int _default_arg_count;
- const int *_code_ptr;
- int _code_size;
- int _argument_count;
- int _stack_size;
- int _call_size;
- int _initial_line;
- bool _static;
- MultiplayerAPI::RPCMode rpc_mode;
-
- GDScript *_script;
+ mutable Variant *_constants_ptr = nullptr;
+ int _constant_count = 0;
+ const StringName *_global_names_ptr = nullptr;
+ int _global_names_count = 0;
+ const int *_default_arg_ptr = nullptr;
+ int _default_arg_count = 0;
+ int _operator_funcs_count = 0;
+ const Variant::ValidatedOperatorEvaluator *_operator_funcs_ptr = nullptr;
+ int _setters_count = 0;
+ const Variant::ValidatedSetter *_setters_ptr = nullptr;
+ int _getters_count = 0;
+ const Variant::ValidatedGetter *_getters_ptr = nullptr;
+ int _keyed_setters_count = 0;
+ const Variant::ValidatedKeyedSetter *_keyed_setters_ptr = nullptr;
+ int _keyed_getters_count = 0;
+ const Variant::ValidatedKeyedGetter *_keyed_getters_ptr = nullptr;
+ int _indexed_setters_count = 0;
+ const Variant::ValidatedIndexedSetter *_indexed_setters_ptr = nullptr;
+ int _indexed_getters_count = 0;
+ const Variant::ValidatedIndexedGetter *_indexed_getters_ptr = nullptr;
+ int _builtin_methods_count = 0;
+ const Variant::ValidatedBuiltInMethod *_builtin_methods_ptr = nullptr;
+ int _constructors_count = 0;
+ const Variant::ValidatedConstructor *_constructors_ptr = nullptr;
+ int _utilities_count = 0;
+ const Variant::ValidatedUtilityFunction *_utilities_ptr = nullptr;
+ int _gds_utilities_count = 0;
+ const GDScriptUtilityFunctions::FunctionPtr *_gds_utilities_ptr = nullptr;
+ int _methods_count = 0;
+ MethodBind **_methods_ptr = nullptr;
+ const int *_code_ptr = nullptr;
+ int _code_size = 0;
+ int _argument_count = 0;
+ int _stack_size = 0;
+ int _instruction_args_size = 0;
+ int _ptrcall_args_size = 0;
+
+ int _initial_line = 0;
+ bool _static = false;
+ MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+
+ GDScript *_script = nullptr;
StringName name;
Vector<Variant> constants;
Vector<StringName> global_names;
-#ifdef TOOLS_ENABLED
- Vector<StringName> named_globals;
-#endif
Vector<int> default_arguments;
+ Vector<Variant::ValidatedOperatorEvaluator> operator_funcs;
+ Vector<Variant::ValidatedSetter> setters;
+ Vector<Variant::ValidatedGetter> getters;
+ Vector<Variant::ValidatedKeyedSetter> keyed_setters;
+ Vector<Variant::ValidatedKeyedGetter> keyed_getters;
+ Vector<Variant::ValidatedIndexedSetter> indexed_setters;
+ Vector<Variant::ValidatedIndexedGetter> indexed_getters;
+ Vector<Variant::ValidatedBuiltInMethod> builtin_methods;
+ Vector<Variant::ValidatedConstructor> constructors;
+ Vector<Variant::ValidatedUtilityFunction> utilities;
+ Vector<GDScriptUtilityFunctions::FunctionPtr> gds_utilities;
+ Vector<MethodBind *> methods;
Vector<int> code;
Vector<GDScriptDataType> argument_types;
GDScriptDataType return_type;
#ifdef TOOLS_ENABLED
Vector<StringName> arg_names;
+ Vector<Variant> default_arg_values;
#endif
List<StackDebug> stack_debug;
@@ -270,34 +398,34 @@ private:
friend class GDScriptLanguage;
- SelfList<GDScriptFunction> function_list;
+ SelfList<GDScriptFunction> function_list{ this };
#ifdef DEBUG_ENABLED
CharString func_cname;
- const char *_func_cname;
+ const char *_func_cname = nullptr;
struct Profile {
StringName signature;
- uint64_t call_count;
- uint64_t self_time;
- uint64_t total_time;
- uint64_t frame_call_count;
- uint64_t frame_self_time;
- uint64_t frame_total_time;
- uint64_t last_frame_call_count;
- uint64_t last_frame_self_time;
- uint64_t last_frame_total_time;
+ uint64_t call_count = 0;
+ uint64_t self_time = 0;
+ uint64_t total_time = 0;
+ uint64_t frame_call_count = 0;
+ uint64_t frame_self_time = 0;
+ uint64_t frame_total_time = 0;
+ uint64_t last_frame_call_count = 0;
+ uint64_t last_frame_self_time = 0;
+ uint64_t last_frame_total_time = 0;
} profile;
#endif
public:
struct CallState {
-
- ObjectID script_id;
+ GDScript *script;
+ GDScriptInstance *instance;
#ifdef DEBUG_ENABLED
+ StringName function_name;
String script_path;
#endif
- ObjectID instance_id;
Vector<uint8_t> stack;
int stack_size;
Variant self;
@@ -340,16 +468,24 @@ public:
ERR_FAIL_INDEX_V(p_idx, default_arguments.size(), Variant());
return default_arguments[p_idx];
}
+#ifdef TOOLS_ENABLED
+ const Vector<Variant> &get_default_arg_values() const {
+ return default_arg_values;
+ }
+#endif // TOOLS_ENABLED
Variant call(GDScriptInstance *p_instance, const Variant **p_args, int p_argcount, Callable::CallError &r_err, CallState *p_state = nullptr);
+#ifdef DEBUG_ENABLED
+ void disassemble(const Vector<String> &p_code_lines) const;
+#endif
+
_FORCE_INLINE_ MultiplayerAPI::RPCMode get_rpc_mode() const { return rpc_mode; }
GDScriptFunction();
~GDScriptFunction();
};
class GDScriptFunctionState : public Reference {
-
GDCLASS(GDScriptFunctionState, Reference);
friend class GDScriptFunction;
GDScriptFunction *function;
@@ -357,12 +493,18 @@ class GDScriptFunctionState : public Reference {
Variant _signal_callback(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
Ref<GDScriptFunctionState> first_state;
+ SelfList<GDScriptFunctionState> scripts_list;
+ SelfList<GDScriptFunctionState> instances_list;
+
protected:
static void _bind_methods();
public:
bool is_valid(bool p_extended_check = false) const;
Variant resume(const Variant &p_arg = Variant());
+
+ void _clear_stack();
+
GDScriptFunctionState();
~GDScriptFunctionState();
};
diff --git a/modules/gdscript/gdscript_functions.cpp b/modules/gdscript/gdscript_functions.cpp
deleted file mode 100644
index 0199af642f..0000000000
--- a/modules/gdscript/gdscript_functions.cpp
+++ /dev/null
@@ -1,2065 +0,0 @@
-/*************************************************************************/
-/* gdscript_functions.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 "gdscript_functions.h"
-
-#include "core/class_db.h"
-#include "core/func_ref.h"
-#include "core/io/json.h"
-#include "core/io/marshalls.h"
-#include "core/math/math_funcs.h"
-#include "core/os/os.h"
-#include "core/reference.h"
-#include "core/variant_parser.h"
-#include "gdscript.h"
-
-const char *GDScriptFunctions::get_func_name(Function p_func) {
-
- ERR_FAIL_INDEX_V(p_func, FUNC_MAX, "");
-
- static const char *_names[FUNC_MAX] = {
- "sin",
- "cos",
- "tan",
- "sinh",
- "cosh",
- "tanh",
- "asin",
- "acos",
- "atan",
- "atan2",
- "sqrt",
- "fmod",
- "fposmod",
- "posmod",
- "floor",
- "ceil",
- "round",
- "abs",
- "sign",
- "pow",
- "log",
- "exp",
- "is_nan",
- "is_inf",
- "is_equal_approx",
- "is_zero_approx",
- "ease",
- "step_decimals",
- "stepify",
- "lerp",
- "lerp_angle",
- "inverse_lerp",
- "range_lerp",
- "smoothstep",
- "move_toward",
- "dectime",
- "randomize",
- "randi",
- "randf",
- "rand_range",
- "seed",
- "rand_seed",
- "deg2rad",
- "rad2deg",
- "linear2db",
- "db2linear",
- "polar2cartesian",
- "cartesian2polar",
- "wrapi",
- "wrapf",
- "max",
- "min",
- "clamp",
- "nearest_po2",
- "weakref",
- "funcref",
- "convert",
- "typeof",
- "type_exists",
- "char",
- "ord",
- "str",
- "print",
- "printt",
- "prints",
- "printerr",
- "printraw",
- "print_debug",
- "push_error",
- "push_warning",
- "var2str",
- "str2var",
- "var2bytes",
- "bytes2var",
- "range",
- "load",
- "inst2dict",
- "dict2inst",
- "validate_json",
- "parse_json",
- "to_json",
- "hash",
- "Color8",
- "ColorN",
- "print_stack",
- "get_stack",
- "instance_from_id",
- "len",
- "is_instance_valid",
- };
-
- return _names[p_func];
-}
-
-void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Callable::CallError &r_error) {
-
- r_error.error = Callable::CallError::CALL_OK;
-#ifdef DEBUG_ENABLED
-
-#define VALIDATE_ARG_COUNT(m_count) \
- if (p_arg_count < m_count) { \
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; \
- r_error.argument = m_count; \
- r_ret = Variant(); \
- return; \
- } \
- if (p_arg_count > m_count) { \
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; \
- r_error.argument = m_count; \
- r_ret = Variant(); \
- return; \
- }
-
-#define VALIDATE_ARG_NUM(m_arg) \
- if (!p_args[m_arg]->is_num()) { \
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
- r_error.argument = m_arg; \
- r_error.expected = Variant::FLOAT; \
- r_ret = Variant(); \
- return; \
- }
-
-#else
-
-#define VALIDATE_ARG_COUNT(m_count)
-#define VALIDATE_ARG_NUM(m_arg)
-#endif
-
- //using a switch, so the compiler generates a jumptable
-
- switch (p_func) {
-
- case MATH_SIN: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::sin((double)*p_args[0]);
- } break;
- case MATH_COS: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::cos((double)*p_args[0]);
- } break;
- case MATH_TAN: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::tan((double)*p_args[0]);
- } break;
- case MATH_SINH: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::sinh((double)*p_args[0]);
- } break;
- case MATH_COSH: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::cosh((double)*p_args[0]);
- } break;
- case MATH_TANH: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::tanh((double)*p_args[0]);
- } break;
- case MATH_ASIN: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::asin((double)*p_args[0]);
- } break;
- case MATH_ACOS: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::acos((double)*p_args[0]);
- } break;
- case MATH_ATAN: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::atan((double)*p_args[0]);
- } break;
- case MATH_ATAN2: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::atan2((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_SQRT: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::sqrt((double)*p_args[0]);
- } break;
- case MATH_FMOD: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::fmod((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_FPOSMOD: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- 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);
- r_ret = Math::floor((double)*p_args[0]);
- } break;
- case MATH_CEIL: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::ceil((double)*p_args[0]);
- } break;
- case MATH_ROUND: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::round((double)*p_args[0]);
- } break;
- case MATH_ABS: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() == Variant::INT) {
-
- int64_t i = *p_args[0];
- r_ret = ABS(i);
- } else if (p_args[0]->get_type() == Variant::FLOAT) {
-
- double r = *p_args[0];
- r_ret = Math::abs(r);
- } else {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::FLOAT;
- r_ret = Variant();
- }
- } break;
- case MATH_SIGN: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() == Variant::INT) {
-
- int64_t i = *p_args[0];
- r_ret = i < 0 ? -1 : (i > 0 ? +1 : 0);
- } else if (p_args[0]->get_type() == Variant::FLOAT) {
-
- real_t r = *p_args[0];
- r_ret = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
- } else {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::FLOAT;
- r_ret = Variant();
- }
- } break;
- case MATH_POW: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::pow((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_LOG: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::log((double)*p_args[0]);
- } break;
- case MATH_EXP: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::exp((double)*p_args[0]);
- } break;
- case MATH_ISNAN: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::is_nan((double)*p_args[0]);
- } break;
- case MATH_ISINF: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::is_inf((double)*p_args[0]);
- } break;
- case MATH_ISEQUALAPPROX: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::is_equal_approx((real_t)*p_args[0], (real_t)*p_args[1]);
- } break;
- case MATH_ISZEROAPPROX: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::is_zero_approx((real_t)*p_args[0]);
- } break;
- case MATH_EASE: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::ease((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_STEP_DECIMALS: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::step_decimals((double)*p_args[0]);
- } break;
- case MATH_STEPIFY: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::stepify((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_LERP: {
- VALIDATE_ARG_COUNT(3);
- VALIDATE_ARG_NUM(2);
- const double t = (double)*p_args[2];
- switch (p_args[0]->get_type() == p_args[1]->get_type() ? p_args[0]->get_type() : Variant::FLOAT) {
- case Variant::VECTOR2: {
- r_ret = ((Vector2)*p_args[0]).lerp((Vector2)*p_args[1], t);
- } break;
- case Variant::VECTOR3: {
- r_ret = (p_args[0]->operator Vector3()).lerp(p_args[1]->operator Vector3(), t);
- } break;
- case Variant::COLOR: {
- r_ret = ((Color)*p_args[0]).lerp((Color)*p_args[1], t);
- } break;
- default: {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::lerp((double)*p_args[0], (double)*p_args[1], t);
- } break;
- }
- } break;
- case MATH_LERP_ANGLE: {
- VALIDATE_ARG_COUNT(3);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- r_ret = Math::lerp_angle((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
- } break;
- case MATH_INVERSE_LERP: {
- VALIDATE_ARG_COUNT(3);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- r_ret = Math::inverse_lerp((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
- } break;
- case MATH_RANGE_LERP: {
- VALIDATE_ARG_COUNT(5);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- VALIDATE_ARG_NUM(3);
- VALIDATE_ARG_NUM(4);
- r_ret = Math::range_lerp((double)*p_args[0], (double)*p_args[1], (double)*p_args[2], (double)*p_args[3], (double)*p_args[4]);
- } break;
- case MATH_SMOOTHSTEP: {
- VALIDATE_ARG_COUNT(3);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- 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);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
- r_ret = Math::dectime((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
- } break;
- case MATH_RANDOMIZE: {
- VALIDATE_ARG_COUNT(0);
- Math::randomize();
- r_ret = Variant();
- } break;
- case MATH_RAND: {
- VALIDATE_ARG_COUNT(0);
- r_ret = Math::rand();
- } break;
- case MATH_RANDF: {
- VALIDATE_ARG_COUNT(0);
- r_ret = Math::randf();
- } break;
- case MATH_RANDOM: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- r_ret = Math::random((double)*p_args[0], (double)*p_args[1]);
- } break;
- case MATH_SEED: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- uint64_t seed = *p_args[0];
- Math::seed(seed);
- r_ret = Variant();
- } break;
- case MATH_RANDSEED: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- uint64_t seed = *p_args[0];
- int ret = Math::rand_from_seed(&seed);
- Array reta;
- reta.push_back(ret);
- reta.push_back(seed);
- r_ret = reta;
-
- } break;
- case MATH_DEG2RAD: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::deg2rad((double)*p_args[0]);
- } break;
- case MATH_RAD2DEG: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::rad2deg((double)*p_args[0]);
- } break;
- case MATH_LINEAR2DB: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::linear2db((double)*p_args[0]);
- } break;
- case MATH_DB2LINEAR: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- r_ret = Math::db2linear((double)*p_args[0]);
- } break;
- case MATH_POLAR2CARTESIAN: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- double r = *p_args[0];
- double th = *p_args[1];
- r_ret = Vector2(r * Math::cos(th), r * Math::sin(th));
- } break;
- case MATH_CARTESIAN2POLAR: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- double x = *p_args[0];
- double y = *p_args[1];
- r_ret = Vector2(Math::sqrt(x * x + y * y), Math::atan2(y, x));
- } break;
- case MATH_WRAP: {
- VALIDATE_ARG_COUNT(3);
- r_ret = Math::wrapi((int64_t)*p_args[0], (int64_t)*p_args[1], (int64_t)*p_args[2]);
- } break;
- case MATH_WRAPF: {
- VALIDATE_ARG_COUNT(3);
- r_ret = Math::wrapf((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
- } break;
- case LOGIC_MAX: {
- VALIDATE_ARG_COUNT(2);
- if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) {
-
- int64_t a = *p_args[0];
- int64_t b = *p_args[1];
- r_ret = MAX(a, b);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
-
- real_t a = *p_args[0];
- real_t b = *p_args[1];
-
- r_ret = MAX(a, b);
- }
-
- } break;
- case LOGIC_MIN: {
- VALIDATE_ARG_COUNT(2);
- if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) {
-
- int64_t a = *p_args[0];
- int64_t b = *p_args[1];
- r_ret = MIN(a, b);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
-
- real_t a = *p_args[0];
- real_t b = *p_args[1];
-
- r_ret = MIN(a, b);
- }
- } break;
- case LOGIC_CLAMP: {
- VALIDATE_ARG_COUNT(3);
- if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT && p_args[2]->get_type() == Variant::INT) {
-
- int64_t a = *p_args[0];
- int64_t b = *p_args[1];
- int64_t c = *p_args[2];
- r_ret = CLAMP(a, b, c);
- } else {
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
-
- real_t a = *p_args[0];
- real_t b = *p_args[1];
- real_t c = *p_args[2];
-
- r_ret = CLAMP(a, b, c);
- }
- } break;
- case LOGIC_NEAREST_PO2: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- int64_t num = *p_args[0];
- r_ret = next_power_of_2(num);
- } break;
- case OBJ_WEAKREF: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() == Variant::OBJECT) {
- if (p_args[0]->is_ref()) {
- Ref<WeakRef> wref = memnew(WeakRef);
- REF r = *p_args[0];
- if (r.is_valid()) {
- wref->set_ref(r);
- }
- r_ret = wref;
- } else {
- Ref<WeakRef> wref = memnew(WeakRef);
- Object *obj = *p_args[0];
- if (obj) {
- wref->set_obj(obj);
- }
- r_ret = wref;
- }
- } else if (p_args[0]->get_type() == Variant::NIL) {
- Ref<WeakRef> wref = memnew(WeakRef);
- r_ret = wref;
- } else {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = Variant();
- return;
- }
- } break;
- case FUNC_FUNCREF: {
- VALIDATE_ARG_COUNT(2);
- if (p_args[0]->get_type() != Variant::OBJECT) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = Variant();
- return;
- }
- if (p_args[1]->get_type() != Variant::STRING && p_args[1]->get_type() != Variant::NODE_PATH) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- return;
- }
-
- Ref<FuncRef> fr = memnew(FuncRef);
-
- fr->set_instance(*p_args[0]);
- fr->set_function(*p_args[1]);
-
- r_ret = fr;
-
- } break;
- case TYPE_CONVERT: {
- VALIDATE_ARG_COUNT(2);
- VALIDATE_ARG_NUM(1);
- int type = *p_args[1];
- if (type < 0 || type >= Variant::VARIANT_MAX) {
-
- r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants.");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::INT;
- return;
-
- } else {
-
- r_ret = Variant::construct(Variant::Type(type), p_args, 1, r_error);
- }
- } break;
- case TYPE_OF: {
-
- VALIDATE_ARG_COUNT(1);
- r_ret = p_args[0]->get_type();
-
- } break;
- case TYPE_EXISTS: {
-
- VALIDATE_ARG_COUNT(1);
- r_ret = ClassDB::class_exists(*p_args[0]);
-
- } break;
- case TEXT_CHAR: {
- VALIDATE_ARG_COUNT(1);
- VALIDATE_ARG_NUM(0);
- CharType result[2] = { *p_args[0], 0 };
- r_ret = String(result);
- } break;
- case TEXT_ORD: {
-
- VALIDATE_ARG_COUNT(1);
-
- if (p_args[0]->get_type() != Variant::STRING) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- return;
- }
-
- String str = p_args[0]->operator String();
-
- if (str.length() != 1) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = RTR("Expected a string of length 1 (a character).");
- return;
- }
-
- r_ret = str.get(0);
-
- } break;
- case TEXT_STR: {
- if (p_arg_count < 1) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- r_ret = Variant();
-
- return;
- }
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- String os = p_args[i]->operator String();
-
- if (i == 0)
- str = os;
- else
- str += os;
- }
-
- r_ret = str;
-
- } break;
- case TEXT_PRINT: {
-
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- str += p_args[i]->operator String();
- }
-
- print_line(str);
- r_ret = Variant();
-
- } break;
- case TEXT_PRINT_TABBED: {
-
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- if (i)
- str += "\t";
- str += p_args[i]->operator String();
- }
-
- print_line(str);
- r_ret = Variant();
-
- } break;
- case TEXT_PRINT_SPACED: {
-
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- if (i)
- str += " ";
- str += p_args[i]->operator String();
- }
-
- print_line(str);
- r_ret = Variant();
-
- } break;
-
- case TEXT_PRINTERR: {
-
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- str += p_args[i]->operator String();
- }
-
- print_error(str);
- r_ret = Variant();
-
- } break;
- case TEXT_PRINTRAW: {
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- str += p_args[i]->operator String();
- }
-
- OS::get_singleton()->print("%s", str.utf8().get_data());
- r_ret = Variant();
-
- } break;
- case TEXT_PRINT_DEBUG: {
- String str;
- for (int i = 0; i < p_arg_count; i++) {
-
- str += p_args[i]->operator String();
- }
-
- ScriptLanguage *script = GDScriptLanguage::get_singleton();
- if (script->debug_get_stack_level_count() > 0) {
- str += "\n At: " + script->debug_get_stack_level_source(0) + ":" + itos(script->debug_get_stack_level_line(0)) + ":" + script->debug_get_stack_level_function(0) + "()";
- }
-
- print_line(str);
- r_ret = Variant();
- } break;
- case PUSH_ERROR: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- break;
- }
-
- String message = *p_args[0];
- ERR_PRINT(message);
- r_ret = Variant();
- } break;
- case PUSH_WARNING: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- break;
- }
-
- String message = *p_args[0];
- WARN_PRINT(message);
- r_ret = Variant();
- } break;
- case VAR_TO_STR: {
- VALIDATE_ARG_COUNT(1);
- String vars;
- VariantWriter::write_to_string(*p_args[0], vars);
- r_ret = vars;
- } break;
- case STR_TO_VAR: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- return;
- }
- r_ret = *p_args[0];
-
- VariantParser::StreamString ss;
- ss.s = *p_args[0];
-
- String errs;
- int line;
- (void)VariantParser::parse(&ss, r_ret, errs, line);
- } break;
- case VAR_TO_BYTES: {
- bool full_objects = false;
- if (p_arg_count < 1) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- r_ret = Variant();
- return;
- } else if (p_arg_count > 2) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = 2;
- r_ret = Variant();
- } else if (p_arg_count == 2) {
- if (p_args[1]->get_type() != Variant::BOOL) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::BOOL;
- r_ret = Variant();
- return;
- }
- full_objects = *p_args[1];
- }
-
- PackedByteArray barr;
- int len;
- Error err = encode_variant(*p_args[0], nullptr, len, full_objects);
- if (err) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::NIL;
- r_ret = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).";
- return;
- }
-
- barr.resize(len);
- {
- uint8_t *w = barr.ptrw();
- encode_variant(*p_args[0], w, len, full_objects);
- }
- r_ret = barr;
- } break;
- case BYTES_TO_VAR: {
- bool allow_objects = false;
- if (p_arg_count < 1) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- r_ret = Variant();
- return;
- } else if (p_arg_count > 2) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = 2;
- r_ret = Variant();
- } else if (p_arg_count == 2) {
- if (p_args[1]->get_type() != Variant::BOOL) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::BOOL;
- r_ret = Variant();
- return;
- }
- allow_objects = *p_args[1];
- }
-
- if (p_args[0]->get_type() != Variant::PACKED_BYTE_ARRAY) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::PACKED_BYTE_ARRAY;
- r_ret = Variant();
- return;
- }
-
- PackedByteArray varr = *p_args[0];
- Variant ret;
- {
- const uint8_t *r = varr.ptr();
- Error err = decode_variant(ret, r, varr.size(), nullptr, allow_objects);
- if (err != OK) {
- r_ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::PACKED_BYTE_ARRAY;
- return;
- }
- }
-
- r_ret = ret;
-
- } break;
- case GEN_RANGE: {
-
- switch (p_arg_count) {
-
- case 0: {
-
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- r_ret = Variant();
-
- } break;
- case 1: {
-
- VALIDATE_ARG_NUM(0);
- int count = *p_args[0];
- Array arr;
- if (count <= 0) {
- r_ret = arr;
- return;
- }
- Error err = arr.resize(count);
- if (err != OK) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret = Variant();
- return;
- }
-
- for (int i = 0; i < count; i++) {
- arr[i] = i;
- }
-
- r_ret = arr;
- } break;
- case 2: {
-
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
-
- int from = *p_args[0];
- int to = *p_args[1];
-
- Array arr;
- if (from >= to) {
- r_ret = arr;
- return;
- }
- Error err = arr.resize(to - from);
- if (err != OK) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret = Variant();
- return;
- }
- for (int i = from; i < to; i++)
- arr[i - from] = i;
- r_ret = arr;
- } break;
- case 3: {
-
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
-
- int from = *p_args[0];
- int to = *p_args[1];
- int incr = *p_args[2];
- if (incr == 0) {
-
- r_ret = RTR("Step argument is zero!");
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- return;
- }
-
- Array arr;
- if (from >= to && incr > 0) {
- r_ret = arr;
- return;
- }
- if (from <= to && incr < 0) {
- r_ret = arr;
- return;
- }
-
- //calculate how many
- int count = 0;
- if (incr > 0) {
-
- count = ((to - from - 1) / incr) + 1;
- } else {
-
- count = ((from - to - 1) / -incr) + 1;
- }
-
- Error err = arr.resize(count);
-
- if (err != OK) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret = Variant();
- return;
- }
-
- if (incr > 0) {
- int idx = 0;
- for (int i = from; i < to; i += incr) {
- arr[idx++] = i;
- }
- } else {
-
- int idx = 0;
- for (int i = from; i > to; i += incr) {
- arr[idx++] = i;
- }
- }
-
- r_ret = arr;
- } break;
- default: {
-
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = 3;
- r_ret = Variant();
-
- } break;
- }
-
- } break;
- case RESOURCE_LOAD: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- } else {
- r_ret = ResourceLoader::load(*p_args[0]);
- }
-
- } break;
- case INST2DICT: {
-
- VALIDATE_ARG_COUNT(1);
-
- if (p_args[0]->get_type() == Variant::NIL) {
- r_ret = Variant();
- } else if (p_args[0]->get_type() != Variant::OBJECT) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_ret = Variant();
- } else {
-
- Object *obj = *p_args[0];
- if (!obj) {
- r_ret = Variant();
-
- } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::DICTIONARY;
- r_ret = RTR("Not a script with an instance");
- return;
- } else {
-
- GDScriptInstance *ins = static_cast<GDScriptInstance *>(obj->get_script_instance());
- Ref<GDScript> base = ins->get_script();
- if (base.is_null()) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::DICTIONARY;
- r_ret = RTR("Not based on a script");
- return;
- }
-
- GDScript *p = base.ptr();
- Vector<StringName> sname;
-
- while (p->_owner) {
-
- sname.push_back(p->name);
- p = p->_owner;
- }
- sname.invert();
-
- if (!p->path.is_resource_file()) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::DICTIONARY;
- r_ret = Variant();
-
- r_ret = RTR("Not based on a resource file");
-
- return;
- }
-
- NodePath cp(sname, Vector<StringName>(), false);
-
- Dictionary d;
- d["@subpath"] = cp;
- d["@path"] = p->get_path();
-
- for (Map<StringName, GDScript::MemberInfo>::Element *E = base->member_indices.front(); E; E = E->next()) {
- if (!d.has(E->key())) {
- d[E->key()] = ins->members[E->get().index];
- }
- }
- r_ret = d;
- }
- }
-
- } break;
- case DICT2INST: {
-
- VALIDATE_ARG_COUNT(1);
-
- if (p_args[0]->get_type() != Variant::DICTIONARY) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::DICTIONARY;
- r_ret = Variant();
-
- return;
- }
-
- Dictionary d = *p_args[0];
-
- if (!d.has("@path")) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = RTR("Invalid instance dictionary format (missing @path)");
-
- return;
- }
-
- Ref<Script> scr = ResourceLoader::load(d["@path"]);
- if (!scr.is_valid()) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = RTR("Invalid instance dictionary format (can't load script at @path)");
- return;
- }
-
- Ref<GDScript> gdscr = scr;
-
- if (!gdscr.is_valid()) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = Variant();
- r_ret = RTR("Invalid instance dictionary format (invalid script at @path)");
- return;
- }
-
- NodePath sub;
- if (d.has("@subpath")) {
- sub = d["@subpath"];
- }
-
- for (int i = 0; i < sub.get_name_count(); i++) {
-
- gdscr = gdscr->subclasses[sub.get_name(i)];
- if (!gdscr.is_valid()) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = Variant();
- r_ret = RTR("Invalid instance dictionary (invalid subclasses)");
- return;
- }
- }
- r_ret = gdscr->_new(nullptr, -1 /*skip initializer*/, r_error);
-
- GDScriptInstance *ins = static_cast<GDScriptInstance *>(static_cast<Object *>(r_ret)->get_script_instance());
- Ref<GDScript> gd_ref = ins->get_script();
-
- for (Map<StringName, GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) {
- if (d.has(E->key())) {
- ins->members.write[E->get().index] = d[E->key()];
- }
- }
-
- } break;
- case VALIDATE_JSON: {
-
- VALIDATE_ARG_COUNT(1);
-
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- return;
- }
-
- String errs;
- int errl;
-
- Error err = JSON::parse(*p_args[0], r_ret, errs, errl);
-
- if (err != OK) {
- r_ret = itos(errl) + ":" + errs;
- } else {
- r_ret = "";
- }
-
- } break;
- case PARSE_JSON: {
-
- VALIDATE_ARG_COUNT(1);
-
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::STRING;
- r_ret = Variant();
- return;
- }
-
- String errs;
- int errl;
-
- Error err = JSON::parse(*p_args[0], r_ret, errs, errl);
-
- if (err != OK) {
- r_ret = Variant();
- ERR_PRINT(vformat("Error parsing JSON at line %s: %s", errl, errs));
- }
-
- } break;
- case TO_JSON: {
- VALIDATE_ARG_COUNT(1);
-
- r_ret = JSON::print(*p_args[0]);
- } break;
- case HASH: {
-
- VALIDATE_ARG_COUNT(1);
- r_ret = p_args[0]->hash();
-
- } break;
- case COLOR8: {
-
- if (p_arg_count < 3) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 3;
- r_ret = Variant();
-
- return;
- }
- if (p_arg_count > 4) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = 4;
- r_ret = Variant();
-
- return;
- }
-
- VALIDATE_ARG_NUM(0);
- VALIDATE_ARG_NUM(1);
- VALIDATE_ARG_NUM(2);
-
- Color color((float)*p_args[0] / 255.0f, (float)*p_args[1] / 255.0f, (float)*p_args[2] / 255.0f);
-
- if (p_arg_count == 4) {
- VALIDATE_ARG_NUM(3);
- color.a = (float)*p_args[3] / 255.0f;
- }
-
- r_ret = color;
-
- } break;
- case COLORN: {
-
- if (p_arg_count < 1) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument = 1;
- r_ret = Variant();
- return;
- }
-
- if (p_arg_count > 2) {
- r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument = 2;
- r_ret = Variant();
- return;
- }
-
- if (p_args[0]->get_type() != Variant::STRING) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_ret = Variant();
- } else {
- Color color = Color::named(*p_args[0]);
- if (p_arg_count == 2) {
- VALIDATE_ARG_NUM(1);
- color.a = *p_args[1];
- }
- r_ret = color;
- }
-
- } break;
-
- case PRINT_STACK: {
- VALIDATE_ARG_COUNT(0);
-
- ScriptLanguage *script = GDScriptLanguage::get_singleton();
- for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
-
- print_line("Frame " + itos(i) + " - " + script->debug_get_stack_level_source(i) + ":" + itos(script->debug_get_stack_level_line(i)) + " in function '" + script->debug_get_stack_level_function(i) + "'");
- };
- } break;
-
- case GET_STACK: {
- VALIDATE_ARG_COUNT(0);
-
- ScriptLanguage *script = GDScriptLanguage::get_singleton();
- Array ret;
- for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
-
- Dictionary frame;
- frame["source"] = script->debug_get_stack_level_source(i);
- frame["function"] = script->debug_get_stack_level_function(i);
- frame["line"] = script->debug_get_stack_level_line(i);
- ret.push_back(frame);
- };
- r_ret = ret;
- } break;
-
- case INSTANCE_FROM_ID: {
-
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::INT && p_args[0]->get_type() != Variant::FLOAT) {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::INT;
- r_ret = Variant();
- break;
- }
-
- ObjectID id = *p_args[0];
- r_ret = ObjectDB::get_instance(id);
-
- } break;
- case LEN: {
-
- VALIDATE_ARG_COUNT(1);
- switch (p_args[0]->get_type()) {
- case Variant::STRING: {
-
- String d = *p_args[0];
- r_ret = d.length();
- } break;
- case Variant::DICTIONARY: {
-
- Dictionary d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::ARRAY: {
-
- Array d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_BYTE_ARRAY: {
-
- Vector<uint8_t> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_INT32_ARRAY: {
-
- Vector<int32_t> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_INT64_ARRAY: {
-
- Vector<int64_t> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_FLOAT32_ARRAY: {
-
- Vector<float> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_FLOAT64_ARRAY: {
-
- Vector<double> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_STRING_ARRAY: {
-
- Vector<String> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_VECTOR2_ARRAY: {
-
- Vector<Vector2> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_VECTOR3_ARRAY: {
-
- Vector<Vector3> d = *p_args[0];
- r_ret = d.size();
- } break;
- case Variant::PACKED_COLOR_ARRAY: {
-
- Vector<Color> d = *p_args[0];
- r_ret = d.size();
- } break;
- default: {
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
- r_ret = Variant();
- r_ret = RTR("Object can't provide a length.");
- }
- }
-
- } break;
- case IS_INSTANCE_VALID: {
-
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type() != Variant::OBJECT) {
- r_ret = false;
- } else {
- Object *obj = p_args[0]->get_validated_object();
- r_ret = obj != nullptr;
- }
-
- } break;
- case FUNC_MAX: {
-
- ERR_FAIL();
- } break;
- }
-}
-
-bool GDScriptFunctions::is_deterministic(Function p_func) {
-
- //man i couldn't have chosen a worse function name,
- //way too controversial..
-
- switch (p_func) {
-
- case MATH_SIN:
- case MATH_COS:
- case MATH_TAN:
- case MATH_SINH:
- case MATH_COSH:
- case MATH_TANH:
- case MATH_ASIN:
- case MATH_ACOS:
- case MATH_ATAN:
- case MATH_ATAN2:
- case MATH_SQRT:
- case MATH_FMOD:
- case MATH_FPOSMOD:
- case MATH_POSMOD:
- case MATH_FLOOR:
- case MATH_CEIL:
- case MATH_ROUND:
- case MATH_ABS:
- case MATH_SIGN:
- case MATH_POW:
- case MATH_LOG:
- case MATH_EXP:
- case MATH_ISNAN:
- case MATH_ISINF:
- case MATH_EASE:
- case MATH_STEP_DECIMALS:
- case MATH_STEPIFY:
- case MATH_LERP:
- case MATH_INVERSE_LERP:
- case MATH_RANGE_LERP:
- case MATH_SMOOTHSTEP:
- case MATH_MOVE_TOWARD:
- case MATH_DECTIME:
- case MATH_DEG2RAD:
- case MATH_RAD2DEG:
- case MATH_LINEAR2DB:
- case MATH_DB2LINEAR:
- case MATH_POLAR2CARTESIAN:
- case MATH_CARTESIAN2POLAR:
- case MATH_WRAP:
- case MATH_WRAPF:
- case LOGIC_MAX:
- case LOGIC_MIN:
- case LOGIC_CLAMP:
- case LOGIC_NEAREST_PO2:
- case TYPE_CONVERT:
- case TYPE_OF:
- case TYPE_EXISTS:
- case TEXT_CHAR:
- case TEXT_ORD:
- case TEXT_STR:
- case COLOR8:
- case LEN:
- // enable for debug only, otherwise not desirable - case GEN_RANGE:
- return true;
- default:
- return false;
- }
-
- return false;
-}
-
-MethodInfo GDScriptFunctions::get_info(Function p_func) {
-
-#ifdef DEBUG_ENABLED
- //using a switch, so the compiler generates a jumptable
-
- switch (p_func) {
-
- case MATH_SIN: {
- MethodInfo mi("sin", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
-
- } break;
- case MATH_COS: {
- MethodInfo mi("cos", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_TAN: {
- MethodInfo mi("tan", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_SINH: {
- MethodInfo mi("sinh", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_COSH: {
- MethodInfo mi("cosh", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_TANH: {
- MethodInfo mi("tanh", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ASIN: {
- MethodInfo mi("asin", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ACOS: {
- MethodInfo mi("acos", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ATAN: {
- MethodInfo mi("atan", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ATAN2: {
- MethodInfo mi("atan2", PropertyInfo(Variant::FLOAT, "y"), PropertyInfo(Variant::FLOAT, "x"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_SQRT: {
- MethodInfo mi("sqrt", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_FMOD: {
- MethodInfo mi("fmod", PropertyInfo(Variant::FLOAT, "a"), PropertyInfo(Variant::FLOAT, "b"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_FPOSMOD: {
- MethodInfo mi("fposmod", PropertyInfo(Variant::FLOAT, "a"), PropertyInfo(Variant::FLOAT, "b"));
- mi.return_val.type = Variant::FLOAT;
- 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::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_CEIL: {
- MethodInfo mi("ceil", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ROUND: {
- MethodInfo mi("round", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ABS: {
- MethodInfo mi("abs", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_SIGN: {
- MethodInfo mi("sign", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_POW: {
- MethodInfo mi("pow", PropertyInfo(Variant::FLOAT, "base"), PropertyInfo(Variant::FLOAT, "exp"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_LOG: {
- MethodInfo mi("log", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_EXP: {
- MethodInfo mi("exp", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_ISNAN: {
- MethodInfo mi("is_nan", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::BOOL;
- return mi;
- } break;
- case MATH_ISINF: {
- MethodInfo mi("is_inf", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::BOOL;
- return mi;
- } break;
- case MATH_ISEQUALAPPROX: {
- MethodInfo mi("is_equal_approx", PropertyInfo(Variant::FLOAT, "a"), PropertyInfo(Variant::FLOAT, "b"));
- mi.return_val.type = Variant::BOOL;
- return mi;
- } break;
- case MATH_ISZEROAPPROX: {
- MethodInfo mi("is_zero_approx", PropertyInfo(Variant::FLOAT, "s"));
- mi.return_val.type = Variant::BOOL;
- return mi;
- } break;
- case MATH_EASE: {
- MethodInfo mi("ease", PropertyInfo(Variant::FLOAT, "s"), PropertyInfo(Variant::FLOAT, "curve"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_STEP_DECIMALS: {
- MethodInfo mi("step_decimals", PropertyInfo(Variant::FLOAT, "step"));
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case MATH_STEPIFY: {
- MethodInfo mi("stepify", PropertyInfo(Variant::FLOAT, "s"), PropertyInfo(Variant::FLOAT, "step"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_LERP: {
- MethodInfo mi("lerp", PropertyInfo(Variant::NIL, "from"), PropertyInfo(Variant::NIL, "to"), PropertyInfo(Variant::FLOAT, "weight"));
- mi.return_val.type = Variant::NIL;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
- } break;
- case MATH_LERP_ANGLE: {
- MethodInfo mi("lerp_angle", PropertyInfo(Variant::FLOAT, "from"), PropertyInfo(Variant::FLOAT, "to"), PropertyInfo(Variant::FLOAT, "weight"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_INVERSE_LERP: {
- MethodInfo mi("inverse_lerp", PropertyInfo(Variant::FLOAT, "from"), PropertyInfo(Variant::FLOAT, "to"), PropertyInfo(Variant::FLOAT, "weight"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_RANGE_LERP: {
- MethodInfo mi("range_lerp", PropertyInfo(Variant::FLOAT, "value"), PropertyInfo(Variant::FLOAT, "istart"), PropertyInfo(Variant::FLOAT, "istop"), PropertyInfo(Variant::FLOAT, "ostart"), PropertyInfo(Variant::FLOAT, "ostop"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_SMOOTHSTEP: {
- MethodInfo mi("smoothstep", PropertyInfo(Variant::FLOAT, "from"), PropertyInfo(Variant::FLOAT, "to"), PropertyInfo(Variant::FLOAT, "weight"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_MOVE_TOWARD: {
- MethodInfo mi("move_toward", PropertyInfo(Variant::FLOAT, "from"), PropertyInfo(Variant::FLOAT, "to"), PropertyInfo(Variant::FLOAT, "delta"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_DECTIME: {
- MethodInfo mi("dectime", PropertyInfo(Variant::FLOAT, "value"), PropertyInfo(Variant::FLOAT, "amount"), PropertyInfo(Variant::FLOAT, "step"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_RANDOMIZE: {
- MethodInfo mi("randomize");
- mi.return_val.type = Variant::NIL;
- return mi;
- } break;
- case MATH_RAND: {
- MethodInfo mi("randi");
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case MATH_RANDF: {
- MethodInfo mi("randf");
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_RANDOM: {
- MethodInfo mi("rand_range", PropertyInfo(Variant::FLOAT, "from"), PropertyInfo(Variant::FLOAT, "to"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_SEED: {
- MethodInfo mi("seed", PropertyInfo(Variant::INT, "seed"));
- mi.return_val.type = Variant::NIL;
- return mi;
- } break;
- case MATH_RANDSEED: {
- MethodInfo mi("rand_seed", PropertyInfo(Variant::INT, "seed"));
- mi.return_val.type = Variant::ARRAY;
- return mi;
- } break;
- case MATH_DEG2RAD: {
- MethodInfo mi("deg2rad", PropertyInfo(Variant::FLOAT, "deg"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_RAD2DEG: {
- MethodInfo mi("rad2deg", PropertyInfo(Variant::FLOAT, "rad"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_LINEAR2DB: {
- MethodInfo mi("linear2db", PropertyInfo(Variant::FLOAT, "nrg"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_DB2LINEAR: {
- MethodInfo mi("db2linear", PropertyInfo(Variant::FLOAT, "db"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case MATH_POLAR2CARTESIAN: {
- MethodInfo mi("polar2cartesian", PropertyInfo(Variant::FLOAT, "r"), PropertyInfo(Variant::FLOAT, "th"));
- mi.return_val.type = Variant::VECTOR2;
- return mi;
- } break;
- case MATH_CARTESIAN2POLAR: {
- MethodInfo mi("cartesian2polar", PropertyInfo(Variant::FLOAT, "x"), PropertyInfo(Variant::FLOAT, "y"));
- mi.return_val.type = Variant::VECTOR2;
- return mi;
- } break;
- case MATH_WRAP: {
- MethodInfo mi("wrapi", PropertyInfo(Variant::INT, "value"), PropertyInfo(Variant::INT, "min"), PropertyInfo(Variant::INT, "max"));
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case MATH_WRAPF: {
- MethodInfo mi("wrapf", PropertyInfo(Variant::FLOAT, "value"), PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case LOGIC_MAX: {
- MethodInfo mi("max", PropertyInfo(Variant::FLOAT, "a"), PropertyInfo(Variant::FLOAT, "b"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
-
- } break;
- case LOGIC_MIN: {
- MethodInfo mi("min", PropertyInfo(Variant::FLOAT, "a"), PropertyInfo(Variant::FLOAT, "b"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case LOGIC_CLAMP: {
- MethodInfo mi("clamp", PropertyInfo(Variant::FLOAT, "value"), PropertyInfo(Variant::FLOAT, "min"), PropertyInfo(Variant::FLOAT, "max"));
- mi.return_val.type = Variant::FLOAT;
- return mi;
- } break;
- case LOGIC_NEAREST_PO2: {
- MethodInfo mi("nearest_po2", PropertyInfo(Variant::INT, "value"));
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case OBJ_WEAKREF: {
-
- MethodInfo mi("weakref", PropertyInfo(Variant::OBJECT, "obj"));
- mi.return_val.type = Variant::OBJECT;
- mi.return_val.class_name = "WeakRef";
-
- return mi;
-
- } break;
- case FUNC_FUNCREF: {
-
- MethodInfo mi("funcref", PropertyInfo(Variant::OBJECT, "instance"), PropertyInfo(Variant::STRING, "funcname"));
- mi.return_val.type = Variant::OBJECT;
- mi.return_val.class_name = "FuncRef";
- return mi;
-
- } break;
- case TYPE_CONVERT: {
-
- MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT), PropertyInfo(Variant::INT, "type"));
- mi.return_val.type = Variant::NIL;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
- } break;
- case TYPE_OF: {
-
- MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
- mi.return_val.type = Variant::INT;
- return mi;
-
- } break;
- case TYPE_EXISTS: {
-
- MethodInfo mi("type_exists", PropertyInfo(Variant::STRING, "type"));
- mi.return_val.type = Variant::BOOL;
- return mi;
-
- } break;
- case TEXT_CHAR: {
-
- MethodInfo mi("char", PropertyInfo(Variant::INT, "code"));
- mi.return_val.type = Variant::STRING;
- return mi;
-
- } break;
- case TEXT_ORD: {
-
- MethodInfo mi("ord", PropertyInfo(Variant::STRING, "char"));
- mi.return_val.type = Variant::INT;
- return mi;
-
- } break;
- case TEXT_STR: {
-
- MethodInfo mi("str");
- mi.return_val.type = Variant::STRING;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINT: {
-
- MethodInfo mi("print");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINT_TABBED: {
-
- MethodInfo mi("printt");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINT_SPACED: {
-
- MethodInfo mi("prints");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINTERR: {
-
- MethodInfo mi("printerr");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINTRAW: {
-
- MethodInfo mi("printraw");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case TEXT_PRINT_DEBUG: {
-
- MethodInfo mi("print_debug");
- mi.return_val.type = Variant::NIL;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
-
- } break;
- case PUSH_ERROR: {
-
- MethodInfo mi(Variant::NIL, "push_error", PropertyInfo(Variant::STRING, "message"));
- mi.return_val.type = Variant::NIL;
- return mi;
-
- } break;
- case PUSH_WARNING: {
-
- MethodInfo mi(Variant::NIL, "push_warning", PropertyInfo(Variant::STRING, "message"));
- mi.return_val.type = Variant::NIL;
- return mi;
-
- } break;
- case VAR_TO_STR: {
-
- MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
- mi.return_val.type = Variant::STRING;
- return mi;
- } break;
- case STR_TO_VAR: {
-
- MethodInfo mi(Variant::NIL, "str2var", PropertyInfo(Variant::STRING, "string"));
- mi.return_val.type = Variant::NIL;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
- } break;
- case VAR_TO_BYTES: {
-
- MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT), PropertyInfo(Variant::BOOL, "full_objects"));
- mi.default_arguments.push_back(false);
- mi.return_val.type = Variant::PACKED_BYTE_ARRAY;
- return mi;
- } break;
- case BYTES_TO_VAR: {
-
- MethodInfo mi(Variant::NIL, "bytes2var", PropertyInfo(Variant::PACKED_BYTE_ARRAY, "bytes"), PropertyInfo(Variant::BOOL, "allow_objects"));
- mi.default_arguments.push_back(false);
- mi.return_val.type = Variant::NIL;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
- } break;
- case GEN_RANGE: {
-
- MethodInfo mi("range");
- mi.return_val.type = Variant::ARRAY;
- mi.flags |= METHOD_FLAG_VARARG;
- return mi;
- } break;
- case RESOURCE_LOAD: {
-
- MethodInfo mi("load", PropertyInfo(Variant::STRING, "path"));
- mi.return_val.type = Variant::OBJECT;
- mi.return_val.class_name = "Resource";
- return mi;
- } break;
- case INST2DICT: {
-
- MethodInfo mi("inst2dict", PropertyInfo(Variant::OBJECT, "inst"));
- mi.return_val.type = Variant::DICTIONARY;
- return mi;
- } break;
- case DICT2INST: {
-
- MethodInfo mi("dict2inst", PropertyInfo(Variant::DICTIONARY, "dict"));
- mi.return_val.type = Variant::OBJECT;
- return mi;
- } break;
- case VALIDATE_JSON: {
-
- MethodInfo mi("validate_json", PropertyInfo(Variant::STRING, "json"));
- mi.return_val.type = Variant::STRING;
- return mi;
- } break;
- case PARSE_JSON: {
-
- MethodInfo mi(Variant::NIL, "parse_json", PropertyInfo(Variant::STRING, "json"));
- mi.return_val.type = Variant::NIL;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
- } break;
- case TO_JSON: {
-
- MethodInfo mi("to_json", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
- mi.return_val.type = Variant::STRING;
- return mi;
- } break;
- case HASH: {
-
- MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case COLOR8: {
-
- MethodInfo mi("Color8", PropertyInfo(Variant::INT, "r8"), PropertyInfo(Variant::INT, "g8"), PropertyInfo(Variant::INT, "b8"), PropertyInfo(Variant::INT, "a8"));
- mi.default_arguments.push_back(255);
- mi.return_val.type = Variant::COLOR;
- return mi;
- } break;
- case COLORN: {
-
- MethodInfo mi("ColorN", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::FLOAT, "alpha"));
- mi.default_arguments.push_back(1.0f);
- mi.return_val.type = Variant::COLOR;
- return mi;
- } break;
-
- case PRINT_STACK: {
- MethodInfo mi("print_stack");
- mi.return_val.type = Variant::NIL;
- return mi;
- } break;
- case GET_STACK: {
- MethodInfo mi("get_stack");
- mi.return_val.type = Variant::ARRAY;
- return mi;
- } break;
-
- case INSTANCE_FROM_ID: {
- MethodInfo mi("instance_from_id", PropertyInfo(Variant::INT, "instance_id"));
- mi.return_val.type = Variant::OBJECT;
- return mi;
- } break;
- case LEN: {
- MethodInfo mi("len", PropertyInfo(Variant::NIL, "var", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
- mi.return_val.type = Variant::INT;
- return mi;
- } break;
- case IS_INSTANCE_VALID: {
- MethodInfo mi("is_instance_valid", PropertyInfo(Variant::OBJECT, "instance"));
- mi.return_val.type = Variant::BOOL;
- return mi;
- } break;
- default: {
-
- ERR_FAIL_V(MethodInfo());
- } break;
- }
-#endif
- MethodInfo mi;
- mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
- return mi;
-}
diff --git a/modules/gdscript/gdscript_functions.h b/modules/gdscript/gdscript_functions.h
deleted file mode 100644
index 2c6dc02913..0000000000
--- a/modules/gdscript/gdscript_functions.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*************************************************************************/
-/* gdscript_functions.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 GDSCRIPT_FUNCTIONS_H
-#define GDSCRIPT_FUNCTIONS_H
-
-#include "core/variant.h"
-
-class GDScriptFunctions {
-public:
- enum Function {
- MATH_SIN,
- MATH_COS,
- MATH_TAN,
- MATH_SINH,
- MATH_COSH,
- MATH_TANH,
- MATH_ASIN,
- MATH_ACOS,
- MATH_ATAN,
- MATH_ATAN2,
- MATH_SQRT,
- MATH_FMOD,
- MATH_FPOSMOD,
- MATH_POSMOD,
- MATH_FLOOR,
- MATH_CEIL,
- MATH_ROUND,
- MATH_ABS,
- MATH_SIGN,
- MATH_POW,
- MATH_LOG,
- MATH_EXP,
- MATH_ISNAN,
- MATH_ISINF,
- MATH_ISEQUALAPPROX,
- MATH_ISZEROAPPROX,
- MATH_EASE,
- MATH_STEP_DECIMALS,
- MATH_STEPIFY,
- MATH_LERP,
- MATH_LERP_ANGLE,
- MATH_INVERSE_LERP,
- MATH_RANGE_LERP,
- MATH_SMOOTHSTEP,
- MATH_MOVE_TOWARD,
- MATH_DECTIME,
- MATH_RANDOMIZE,
- MATH_RAND,
- MATH_RANDF,
- MATH_RANDOM,
- MATH_SEED,
- MATH_RANDSEED,
- MATH_DEG2RAD,
- MATH_RAD2DEG,
- MATH_LINEAR2DB,
- MATH_DB2LINEAR,
- MATH_POLAR2CARTESIAN,
- MATH_CARTESIAN2POLAR,
- MATH_WRAP,
- MATH_WRAPF,
- LOGIC_MAX,
- LOGIC_MIN,
- LOGIC_CLAMP,
- LOGIC_NEAREST_PO2,
- OBJ_WEAKREF,
- FUNC_FUNCREF,
- TYPE_CONVERT,
- TYPE_OF,
- TYPE_EXISTS,
- TEXT_CHAR,
- TEXT_ORD,
- TEXT_STR,
- TEXT_PRINT,
- TEXT_PRINT_TABBED,
- TEXT_PRINT_SPACED,
- TEXT_PRINTERR,
- TEXT_PRINTRAW,
- TEXT_PRINT_DEBUG,
- PUSH_ERROR,
- PUSH_WARNING,
- VAR_TO_STR,
- STR_TO_VAR,
- VAR_TO_BYTES,
- BYTES_TO_VAR,
- GEN_RANGE,
- RESOURCE_LOAD,
- INST2DICT,
- DICT2INST,
- VALIDATE_JSON,
- PARSE_JSON,
- TO_JSON,
- HASH,
- COLOR8,
- COLORN,
- PRINT_STACK,
- GET_STACK,
- INSTANCE_FROM_ID,
- LEN,
- IS_INSTANCE_VALID,
- FUNC_MAX
- };
-
- static const char *get_func_name(Function p_func);
- static void call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Callable::CallError &r_error);
- static bool is_deterministic(Function p_func);
- static MethodInfo get_info(Function p_func);
-};
-
-#endif // GDSCRIPT_FUNCTIONS_H
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 17077567c7..a77fb14064 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,8775 +30,4103 @@
#include "gdscript_parser.h"
-#include "core/core_string_names.h"
-#include "core/engine.h"
+#include "core/config/project_settings.h"
#include "core/io/resource_loader.h"
+#include "core/math/math_defs.h"
#include "core/os/file_access.h"
-#include "core/print_string.h"
-#include "core/project_settings.h"
-#include "core/reference.h"
-#include "core/script_language.h"
#include "gdscript.h"
-template <class T>
-T *GDScriptParser::alloc_node() {
+#ifdef DEBUG_ENABLED
+#include "core/os/os.h"
+#include "core/string/string_builder.h"
+#endif // DEBUG_ENABLED
- T *t = memnew(T);
+#ifdef TOOLS_ENABLED
+#include "editor/editor_settings.h"
+#endif // TOOLS_ENABLED
+
+static HashMap<StringName, Variant::Type> builtin_types;
+Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
+ if (builtin_types.is_empty()) {
+ builtin_types["bool"] = Variant::BOOL;
+ builtin_types["int"] = Variant::INT;
+ builtin_types["float"] = Variant::FLOAT;
+ builtin_types["String"] = Variant::STRING;
+ builtin_types["Vector2"] = Variant::VECTOR2;
+ builtin_types["Vector2i"] = Variant::VECTOR2I;
+ builtin_types["Rect2"] = Variant::RECT2;
+ builtin_types["Rect2i"] = Variant::RECT2I;
+ builtin_types["Transform2D"] = Variant::TRANSFORM2D;
+ builtin_types["Vector3"] = Variant::VECTOR3;
+ builtin_types["Vector3i"] = Variant::VECTOR3I;
+ builtin_types["AABB"] = Variant::AABB;
+ builtin_types["Plane"] = Variant::PLANE;
+ builtin_types["Quat"] = Variant::QUAT;
+ builtin_types["Basis"] = Variant::BASIS;
+ builtin_types["Transform"] = Variant::TRANSFORM;
+ builtin_types["Color"] = Variant::COLOR;
+ builtin_types["RID"] = Variant::RID;
+ builtin_types["Object"] = Variant::OBJECT;
+ builtin_types["StringName"] = Variant::STRING_NAME;
+ builtin_types["NodePath"] = Variant::NODE_PATH;
+ builtin_types["Dictionary"] = Variant::DICTIONARY;
+ builtin_types["Callable"] = Variant::CALLABLE;
+ builtin_types["Signal"] = Variant::SIGNAL;
+ builtin_types["Array"] = Variant::ARRAY;
+ builtin_types["PackedByteArray"] = Variant::PACKED_BYTE_ARRAY;
+ builtin_types["PackedInt32Array"] = Variant::PACKED_INT32_ARRAY;
+ builtin_types["PackedInt64Array"] = Variant::PACKED_INT64_ARRAY;
+ builtin_types["PackedFloat32Array"] = Variant::PACKED_FLOAT32_ARRAY;
+ builtin_types["PackedFloat64Array"] = Variant::PACKED_FLOAT64_ARRAY;
+ builtin_types["PackedStringArray"] = Variant::PACKED_STRING_ARRAY;
+ builtin_types["PackedVector2Array"] = Variant::PACKED_VECTOR2_ARRAY;
+ builtin_types["PackedVector3Array"] = Variant::PACKED_VECTOR3_ARRAY;
+ builtin_types["PackedColorArray"] = Variant::PACKED_COLOR_ARRAY;
+ // NIL is not here, hence the -1.
+ if (builtin_types.size() != Variant::VARIANT_MAX - 1) {
+ ERR_PRINT("Outdated parser: amount of built-in types don't match the amount of types in Variant.");
+ }
+ }
- t->next = list;
- list = t;
+ if (builtin_types.has(p_type)) {
+ return builtin_types[p_type];
+ }
+ return Variant::VARIANT_MAX;
+}
- if (!head)
- head = t;
+void GDScriptParser::cleanup() {
+ builtin_types.clear();
+}
- t->line = tokenizer->get_token_line();
- t->column = tokenizer->get_token_column();
- return t;
+void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
+ List<StringName> keys;
+ valid_annotations.get_key_list(&keys);
+ for (const List<StringName>::Element *E = keys.front(); E != nullptr; E = E->next()) {
+ r_annotations->push_back(valid_annotations[E->get()].info);
+ }
}
-#ifdef DEBUG_ENABLED
-static String _find_function_name(const GDScriptParser::OperatorNode *p_call);
-#endif // DEBUG_ENABLED
+GDScriptParser::GDScriptParser() {
+ // Register valid annotations.
+ // TODO: Should this be static?
+ // TODO: Validate applicable types (e.g. a VARIABLE annotation that only applies to string variables).
+ register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
+ register_annotation(MethodInfo("@icon", { Variant::STRING, "icon_path" }), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
+ register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
+ // Export annotations.
+ register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_TYPE_STRING, Variant::NIL>);
+ register_annotation(MethodInfo("@export_enum", { Variant::STRING, "names" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::INT>, 0, true);
+ register_annotation(MethodInfo("@export_file", { Variant::STRING, "filter" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, 1, true);
+ register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
+ register_annotation(MethodInfo("@export_global_file", { Variant::STRING, "filter" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, 1, true);
+ register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
+ register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
+ register_annotation(MethodInfo("@export_placeholder"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
+ register_annotation(MethodInfo("@export_range", { Variant::FLOAT, "min" }, { Variant::FLOAT, "max" }, { Variant::FLOAT, "step" }, { Variant::STRING, "slider1" }, { Variant::STRING, "slider2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, 3);
+ register_annotation(MethodInfo("@export_exp_range", { Variant::FLOAT, "min" }, { Variant::FLOAT, "max" }, { Variant::FLOAT, "step" }, { Variant::STRING, "slider1" }, { Variant::STRING, "slider2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_RANGE, Variant::FLOAT>, 3);
+ register_annotation(MethodInfo("@export_exp_easing", { Variant::STRING, "hint1" }, { Variant::STRING, "hint2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, 2);
+ register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
+ register_annotation(MethodInfo("@export_node_path", { Variant::STRING, "type" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, 1, true);
+ register_annotation(MethodInfo("@export_flags", { Variant::STRING, "names" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, 0, true);
+ register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
+ register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
+ register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
+ register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
+ // Networking.
+ register_annotation(MethodInfo("@remote"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_REMOTE>);
+ register_annotation(MethodInfo("@master"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_MASTER>);
+ register_annotation(MethodInfo("@puppet"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_PUPPET>);
+ register_annotation(MethodInfo("@remotesync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_REMOTESYNC>);
+ register_annotation(MethodInfo("@mastersync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_MASTERSYNC>);
+ register_annotation(MethodInfo("@puppetsync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_PUPPETSYNC>);
+ // TODO: Warning annotations.
+}
-bool GDScriptParser::_end_statement() {
+GDScriptParser::~GDScriptParser() {
+ clear();
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) {
- tokenizer->advance();
- return true; //handle next
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE || tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
- return true; //will be handled properly
+void GDScriptParser::clear() {
+ while (list != nullptr) {
+ Node *element = list;
+ list = list->next;
+ memdelete(element);
}
- return false;
+ head = nullptr;
+ list = nullptr;
+ _is_tool = false;
+ for_completion = false;
+ errors.clear();
+ multiline_stack.clear();
}
-bool GDScriptParser::_enter_indent_block(BlockNode *p_block) {
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COLON) {
- // report location at the previous token (on the previous line)
- int error_line = tokenizer->get_token_line(-1);
- int error_column = tokenizer->get_token_column(-1);
- _set_error("':' expected at end of line.", error_line, error_column);
- return false;
+void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
+ // TODO: Improve error reporting by pointing at source code.
+ // TODO: Errors might point at more than one place at once (e.g. show previous declaration).
+ panic_mode = true;
+ // TODO: Improve positional information.
+ if (p_origin == nullptr) {
+ errors.push_back({ p_message, current.start_line, current.start_column });
+ } else {
+ errors.push_back({ p_message, p_origin->start_line, p_origin->leftmost_column });
}
- tokenizer->advance();
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
- return false;
+#ifdef DEBUG_ENABLED
+void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const String &p_symbol1, const String &p_symbol2, const String &p_symbol3, const String &p_symbol4) {
+ ERR_FAIL_COND(p_source == nullptr);
+ Vector<String> symbols;
+ if (!p_symbol1.is_empty()) {
+ symbols.push_back(p_symbol1);
}
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE) {
- // be more python-like
- IndentLevel current_level = indent_level.back()->get();
- indent_level.push_back(current_level);
- return true;
- //_set_error("newline expected after ':'.");
- //return false;
+ if (!p_symbol2.is_empty()) {
+ symbols.push_back(p_symbol2);
}
+ if (!p_symbol3.is_empty()) {
+ symbols.push_back(p_symbol3);
+ }
+ if (!p_symbol4.is_empty()) {
+ symbols.push_back(p_symbol4);
+ }
+ push_warning(p_source, p_code, symbols);
+}
- while (true) {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE) {
-
- return false; //wtf
- } else if (tokenizer->get_token(1) == GDScriptTokenizer::TK_EOF) {
- return false;
- } else if (tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) {
-
- int indent = tokenizer->get_token_line_indent();
- int tabs = tokenizer->get_token_line_tab_indent();
- IndentLevel current_level = indent_level.back()->get();
- IndentLevel new_indent(indent, tabs);
- if (new_indent.is_mixed(current_level)) {
- _set_error("Mixed tabs and spaces in indentation.");
- return false;
- }
-
- if (indent <= current_level.indent) {
- return false;
- }
+void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
+ ERR_FAIL_COND(p_source == nullptr);
+ if (is_ignoring_warnings) {
+ return;
+ }
+ if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && script_path.begins_with("res://addons/")) {
+ return;
+ }
- indent_level.push_back(new_indent);
- tokenizer->advance();
- return true;
+ String warn_name = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)p_code).to_lower();
+ if (ignored_warnings.has(warn_name)) {
+ return;
+ }
+ if (!GLOBAL_GET("debug/gdscript/warnings/" + warn_name)) {
+ return;
+ }
- } else if (p_block) {
+ GDScriptWarning warning;
+ warning.code = p_code;
+ warning.symbols = p_symbols;
+ warning.start_line = p_source->start_line;
+ warning.end_line = p_source->end_line;
+ warning.leftmost_column = p_source->leftmost_column;
+ warning.rightmost_column = p_source->rightmost_column;
- NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line = tokenizer->get_token_line();
- p_block->statements.push_back(nl);
+ List<GDScriptWarning>::Element *before = nullptr;
+ for (List<GDScriptWarning>::Element *E = warnings.front(); E != nullptr; E = E->next()) {
+ if (E->get().start_line > warning.start_line) {
+ break;
}
+ before = E;
+ }
+ if (before) {
+ warnings.insert_after(before, warning);
+ } else {
+ warnings.push_front(warning);
+ }
+}
+#endif
- tokenizer->advance(); // go to next newline
+void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument, bool p_force) {
+ if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
+ return;
+ }
+ if (previous.cursor_place != GDScriptTokenizer::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizer::CURSOR_END && current.cursor_place == GDScriptTokenizer::CURSOR_NONE) {
+ return;
}
+ CompletionContext context;
+ context.type = p_type;
+ context.current_class = current_class;
+ context.current_function = current_function;
+ context.current_suite = current_suite;
+ context.current_line = tokenizer.get_cursor_line();
+ context.current_argument = p_argument;
+ context.node = p_node;
+ completion_context = context;
}
-bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete, bool p_parsing_constant) {
+void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force) {
+ if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
+ return;
+ }
+ if (previous.cursor_place != GDScriptTokenizer::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizer::CURSOR_END && current.cursor_place == GDScriptTokenizer::CURSOR_NONE) {
+ return;
+ }
+ CompletionContext context;
+ context.type = p_type;
+ context.current_class = current_class;
+ context.current_function = current_function;
+ context.current_suite = current_suite;
+ context.current_line = tokenizer.get_cursor_line();
+ context.builtin_type = p_builtin_type;
+ completion_context = context;
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- tokenizer->advance();
- } else {
+void GDScriptParser::push_completion_call(Node *p_call) {
+ if (!for_completion) {
+ return;
+ }
+ CompletionCall call;
+ call.call = p_call;
+ call.argument = 0;
+ completion_call_stack.push_back(call);
+ if (previous.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE || previous.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_BEGINNING) {
+ completion_call = call;
+ }
+}
- parenthesis++;
- int argidx = 0;
+void GDScriptParser::pop_completion_call() {
+ if (!for_completion) {
+ return;
+ }
+ ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
+ completion_call_stack.pop_back();
+}
- while (true) {
+void GDScriptParser::set_last_completion_call_arg(int p_argument) {
+ if (!for_completion || passed_cursor) {
+ return;
+ }
+ ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
+ completion_call_stack.back()->get().argument = p_argument;
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- _make_completable_call(argidx);
- completion_node = p_parent;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING && tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR) {
- //completing a string argument..
- completion_cursor = tokenizer->get_token_constant();
+Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion) {
+ clear();
- _make_completable_call(argidx);
- completion_node = p_parent;
- tokenizer->advance(1);
- return false;
- }
+ String source = p_source_code;
+ int cursor_line = -1;
+ int cursor_column = -1;
+ for_completion = p_for_completion;
- Node *arg = _parse_expression(p_parent, p_static, false, p_parsing_constant);
- if (!arg) {
- return false;
+ int tab_size = 4;
+#ifdef TOOLS_ENABLED
+ if (EditorSettings::get_singleton()) {
+ tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
+ }
+#endif // TOOLS_ENABLED
+
+ if (p_for_completion) {
+ // Remove cursor sentinel char.
+ const Vector<String> lines = p_source_code.split("\n");
+ cursor_line = 1;
+ cursor_column = 1;
+ for (int i = 0; i < lines.size(); i++) {
+ bool found = false;
+ const String &line = lines[i];
+ for (int j = 0; j < line.size(); j++) {
+ if (line[j] == char32_t(0xFFFF)) {
+ found = true;
+ break;
+ } else if (line[j] == '\t') {
+ cursor_column += tab_size - 1;
+ }
+ cursor_column++;
}
-
- p_args.push_back(arg);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- tokenizer->advance();
+ if (found) {
break;
+ }
+ cursor_line++;
+ cursor_column = 1;
+ }
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
+ source = source.replace_first(String::chr(0xFFFF), String());
+ }
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
+ tokenizer.set_source_code(source);
+ tokenizer.set_cursor_position(cursor_line, cursor_column);
+ script_path = p_script_path;
+ current = tokenizer.scan();
+ // Avoid error as the first token.
+ while (current.type == GDScriptTokenizer::Token::ERROR) {
+ push_error(current.literal);
+ current = tokenizer.scan();
+ }
- _set_error("Expression expected");
- return false;
- }
+ push_multiline(false); // Keep one for the whole parsing.
+ parse_program();
+ pop_multiline();
- tokenizer->advance();
- argidx++;
- } else {
- // something is broken
- _set_error("Expected ',' or ')'");
- return false;
- }
- }
- parenthesis--;
+#ifdef DEBUG_ENABLED
+ if (multiline_stack.size() > 0) {
+ ERR_PRINT("Parser bug: Imbalanced multiline stack.");
}
+#endif
- return true;
+ if (errors.is_empty()) {
+ return OK;
+ } else {
+ return ERR_PARSE_ERROR;
+ }
}
-void GDScriptParser::_make_completable_call(int p_arg) {
-
- completion_cursor = StringName();
- completion_type = COMPLETION_CALL_ARGUMENTS;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_argument = p_arg;
- completion_block = current_block;
- completion_found = true;
- tokenizer->advance();
+GDScriptTokenizer::Token GDScriptParser::advance() {
+ if (current.type == GDScriptTokenizer::Token::TK_EOF) {
+ ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
+ }
+ if (for_completion && !completion_call_stack.is_empty()) {
+ if (completion_call.call == nullptr && tokenizer.is_past_cursor()) {
+ completion_call = completion_call_stack.back()->get();
+ passed_cursor = true;
+ }
+ }
+ previous = current;
+ current = tokenizer.scan();
+ while (current.type == GDScriptTokenizer::Token::ERROR) {
+ push_error(current.literal);
+ current = tokenizer.scan();
+ }
+ return previous;
}
-bool GDScriptParser::_get_completable_identifier(CompletionType p_type, StringName &identifier) {
-
- identifier = StringName();
- if (tokenizer->is_token_literal()) {
- identifier = tokenizer->get_token_literal();
- tokenizer->advance();
+bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
+ if (!check(p_token_type)) {
+ return false;
}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
-
- completion_cursor = identifier;
- completion_type = p_type;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_block = current_block;
- completion_found = true;
- completion_ident_is_call = false;
- tokenizer->advance();
+ advance();
+ return true;
+}
- if (tokenizer->is_token_literal()) {
- identifier = identifier.operator String() + tokenizer->get_token_literal().operator String();
- tokenizer->advance();
- }
+bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) {
+ if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
+ return current.is_identifier();
+ }
+ return current.type == p_token_type;
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- completion_ident_is_call = true;
- }
+bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
+ if (match(p_token_type)) {
return true;
}
-
+ push_error(p_error_message);
return false;
}
-GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign, bool p_parsing_constant) {
-
- //Vector<Node*> expressions;
- //Vector<OperatorNode::Operator> operators;
-
- Vector<Expression> expression;
-
- Node *expr = nullptr;
-
- int op_line = tokenizer->get_token_line(); // when operators are created at the bottom, the line might have been changed (\n found)
-
- while (true) {
-
- /*****************/
- /* Parse Operand */
- /*****************/
+bool GDScriptParser::is_at_end() {
+ return check(GDScriptTokenizer::Token::TK_EOF);
+}
- if (parenthesis > 0) {
- //remove empty space (only allowed if inside parenthesis
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- }
+void GDScriptParser::synchronize() {
+ panic_mode = false;
+ while (!is_at_end()) {
+ if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
+ return;
}
- // Check that the next token is not TK_CURSOR and if it is, the offset should be incremented.
- int next_valid_offset = 1;
- if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_CURSOR) {
- next_valid_offset++;
- // There is a chunk of the identifier that also needs to be ignored (not always there!)
- if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_IDENTIFIER) {
- next_valid_offset++;
- }
+ switch (current.type) {
+ case GDScriptTokenizer::Token::CLASS:
+ case GDScriptTokenizer::Token::FUNC:
+ case GDScriptTokenizer::Token::STATIC:
+ case GDScriptTokenizer::Token::VAR:
+ case GDScriptTokenizer::Token::CONST:
+ case GDScriptTokenizer::Token::SIGNAL:
+ //case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
+ case GDScriptTokenizer::Token::FOR:
+ case GDScriptTokenizer::Token::WHILE:
+ case GDScriptTokenizer::Token::MATCH:
+ case GDScriptTokenizer::Token::RETURN:
+ case GDScriptTokenizer::Token::ANNOTATION:
+ return;
+ default:
+ // Do nothing.
+ break;
}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- //subexpression ()
- tokenizer->advance();
- parenthesis++;
- Node *subexpr = _parse_expression(p_parent, p_static, p_allow_assign, p_parsing_constant);
- parenthesis--;
- if (!subexpr)
- return nullptr;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
-
- _set_error("Expected ')' in expression");
- return nullptr;
- }
-
- tokenizer->advance();
- expr = subexpr;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_DOLLAR) {
- tokenizer->advance();
-
- String path;
-
- bool need_identifier = true;
- bool done = false;
- int line = tokenizer->get_token_line();
-
- while (!done) {
-
- switch (tokenizer->get_token()) {
- case GDScriptTokenizer::TK_CURSOR: {
- completion_type = COMPLETION_GET_NODE;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_cursor = path;
- completion_argument = 0;
- completion_block = current_block;
- completion_found = true;
- tokenizer->advance();
- } break;
- case GDScriptTokenizer::TK_CONSTANT: {
-
- if (!need_identifier) {
- done = true;
- break;
- }
-
- if (tokenizer->get_token_constant().get_type() != Variant::STRING) {
- _set_error("Expected string constant or identifier after '$' or '/'.");
- return nullptr;
- }
-
- path += String(tokenizer->get_token_constant());
- tokenizer->advance();
- need_identifier = false;
-
- } break;
- case GDScriptTokenizer::TK_OP_DIV: {
-
- if (need_identifier) {
- done = true;
- break;
- }
-
- path += "/";
- tokenizer->advance();
- need_identifier = true;
-
- } break;
- default: {
- // Instead of checking for TK_IDENTIFIER, we check with is_token_literal, as this allows us to use match/sync/etc. as a name
- if (need_identifier && tokenizer->is_token_literal()) {
- path += String(tokenizer->get_token_literal());
- tokenizer->advance();
- need_identifier = false;
- } else {
- done = true;
- }
-
- break;
- }
- }
- }
+ advance();
+ }
+}
- if (path == "") {
- _set_error("Path expected after $.");
- return nullptr;
- }
+void GDScriptParser::push_multiline(bool p_state) {
+ multiline_stack.push_back(p_state);
+ tokenizer.set_multiline_mode(p_state);
+ if (p_state) {
+ // Consume potential whitespace tokens already waiting in line.
+ while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
+ current = tokenizer.scan(); // Don't call advance() here, as we don't want to change the previous token.
+ }
+ }
+}
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_CALL;
- op->line = line;
- op->arguments.push_back(alloc_node<SelfNode>());
- op->arguments[0]->line = line;
-
- IdentifierNode *funcname = alloc_node<IdentifierNode>();
- funcname->name = "get_node";
- funcname->line = line;
- op->arguments.push_back(funcname);
-
- ConstantNode *nodepath = alloc_node<ConstantNode>();
- nodepath->value = NodePath(StringName(path));
- nodepath->datatype = _type_from_variant(nodepath->value);
- nodepath->line = line;
- op->arguments.push_back(nodepath);
-
- expr = op;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- tokenizer->advance();
- continue; //no point in cursor in the middle of expression
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) {
-
- //constant defined by tokenizer
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = tokenizer->get_token_constant();
- constant->datatype = _type_from_variant(constant->value);
- tokenizer->advance();
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_PI) {
-
- //constant defined by tokenizer
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = Math_PI;
- constant->datatype = _type_from_variant(constant->value);
- tokenizer->advance();
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_TAU) {
+void GDScriptParser::pop_multiline() {
+ ERR_FAIL_COND_MSG(multiline_stack.size() == 0, "Parser bug: trying to pop from multiline stack without available value.");
+ multiline_stack.pop_back();
+ tokenizer.set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
+}
- //constant defined by tokenizer
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = Math_TAU;
- constant->datatype = _type_from_variant(constant->value);
- tokenizer->advance();
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_INF) {
+bool GDScriptParser::is_statement_end() {
+ return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
+}
- //constant defined by tokenizer
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = Math_INF;
- constant->datatype = _type_from_variant(constant->value);
- tokenizer->advance();
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONST_NAN) {
+void GDScriptParser::end_statement(const String &p_context) {
+ bool found = false;
+ while (is_statement_end() && !is_at_end()) {
+ // Remove sequential newlines/semicolons.
+ found = true;
+ advance();
+ }
+ if (!found && !is_at_end()) {
+ push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
+ }
+}
- //constant defined by tokenizer
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = Math_NAN;
- constant->datatype = _type_from_variant(constant->value);
- tokenizer->advance();
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_PRELOAD) {
-
- //constant defined by tokenizer
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected '(' after 'preload'");
- return nullptr;
- }
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- completion_cursor = StringName();
- completion_node = p_parent;
- completion_type = COMPLETION_RESOURCE_PATH;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_block = current_block;
- completion_argument = 0;
- completion_found = true;
- tokenizer->advance();
+void GDScriptParser::parse_program() {
+ head = alloc_node<ClassNode>();
+ current_class = head;
+
+ if (match(GDScriptTokenizer::Token::ANNOTATION)) {
+ // Check for @tool annotation.
+ AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL);
+ if (annotation != nullptr) {
+ if (annotation->name == "@tool") {
+ // TODO: don't allow @tool anywhere else. (Should all script annotations be the first thing?).
+ _is_tool = true;
+ if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
+ push_error(R"(Expected newline after "@tool" annotation.)");
+ }
+ // @tool annotation has no specific target.
+ annotation->apply(this, nullptr);
+ } else {
+ annotation_stack.push_back(annotation);
}
+ }
+ }
- String path;
- bool found_constant = false;
- bool valid = false;
- ConstantNode *cn;
-
- Node *subexpr = _parse_and_reduce_expression(p_parent, p_static);
- if (subexpr) {
- if (subexpr->type == Node::TYPE_CONSTANT) {
- cn = static_cast<ConstantNode *>(subexpr);
- found_constant = true;
- }
- if (subexpr->type == Node::TYPE_IDENTIFIER) {
- IdentifierNode *in = static_cast<IdentifierNode *>(subexpr);
-
- // Try to find the constant expression by the identifier
- if (current_class->constant_expressions.has(in->name)) {
- Node *cn_exp = current_class->constant_expressions[in->name].expression;
- if (cn_exp->type == Node::TYPE_CONSTANT) {
- cn = static_cast<ConstantNode *>(cn_exp);
- found_constant = true;
- }
- }
- }
-
- if (found_constant && cn->value.get_type() == Variant::STRING) {
- valid = true;
- path = (String)cn->value;
+ for (bool should_break = false; !should_break;) {
+ // Order here doesn't matter, but there should be only one of each at most.
+ switch (current.type) {
+ case GDScriptTokenizer::Token::CLASS_NAME:
+ if (!annotation_stack.is_empty()) {
+ push_error(R"("class_name" should be used before annotations.)");
}
- }
-
- if (!valid) {
- _set_error("expected string constant as 'preload' argument.");
- return nullptr;
- }
-
- if (!path.is_abs_path() && base_path != "")
- path = base_path.plus_file(path);
- path = path.replace("///", "//").simplify_path();
- if (path == self_path) {
-
- _set_error("Can't preload itself (use 'get_script()').");
- return nullptr;
- }
-
- Ref<Resource> res;
- dependencies.push_back(path);
- if (!dependencies_only) {
- if (!validating) {
-
- //this can be too slow for just validating code
- if (for_completion && ScriptCodeCompletionCache::get_singleton() && FileAccess::exists(path)) {
- res = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(path);
- } else if (!for_completion || FileAccess::exists(path)) {
- res = ResourceLoader::load(path);
- }
+ advance();
+ if (head->identifier != nullptr) {
+ push_error(R"("class_name" can only be used once.)");
} else {
-
- if (!FileAccess::exists(path)) {
- _set_error("Can't preload resource at path: " + path);
- return nullptr;
- } else if (ScriptCodeCompletionCache::get_singleton()) {
- res = ScriptCodeCompletionCache::get_singleton()->get_cached_resource(path);
- }
- }
- if (!res.is_valid()) {
- _set_error("Can't preload resource at path: " + path);
- return nullptr;
+ parse_class_name();
}
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected ')' after 'preload' path");
- return nullptr;
- }
-
- Ref<GDScript> gds = res;
- if (gds.is_valid() && !gds->is_valid()) {
- _set_error("Couldn't fully preload the script, possible cyclic reference or compilation error. Use \"load()\" instead if a cyclic reference is intended.");
- return nullptr;
- }
-
- tokenizer->advance();
-
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = res;
- constant->datatype = _type_from_variant(constant->value);
-
- expr = constant;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_YIELD) {
-
- if (!current_function) {
- _set_error("\"yield()\" can only be used inside function blocks.");
- return nullptr;
- }
-
- current_function->has_yield = true;
-
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected \"(\" after \"yield\".");
- return nullptr;
- }
-
- tokenizer->advance();
-
- OperatorNode *yield = alloc_node<OperatorNode>();
- yield->op = OperatorNode::OP_YIELD;
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- expr = yield;
- tokenizer->advance();
- } else {
-
- parenthesis++;
-
- Node *object = _parse_and_reduce_expression(p_parent, p_static);
- if (!object)
- return nullptr;
- yield->arguments.push_back(object);
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected \",\" after the first argument of \"yield\".");
- return nullptr;
+ break;
+ case GDScriptTokenizer::Token::EXTENDS:
+ if (!annotation_stack.is_empty()) {
+ push_error(R"("extends" should be used before annotations.)");
}
-
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
-
- completion_cursor = StringName();
- completion_node = object;
- completion_type = COMPLETION_YIELD;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_argument = 0;
- completion_block = current_block;
- completion_found = true;
- tokenizer->advance();
+ advance();
+ if (head->extends_used) {
+ push_error(R"("extends" can only be used once.)");
+ } else {
+ parse_extends();
+ end_statement("superclass");
}
+ break;
+ default:
+ should_break = true;
+ break;
+ }
- Node *signal = _parse_and_reduce_expression(p_parent, p_static);
- if (!signal)
- return nullptr;
- yield->arguments.push_back(signal);
+ if (panic_mode) {
+ synchronize();
+ }
+ }
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" after the second argument of \"yield\".");
- return nullptr;
+ if (match(GDScriptTokenizer::Token::ANNOTATION)) {
+ // Check for @icon annotation.
+ AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL);
+ if (annotation != nullptr) {
+ if (annotation->name == "@icon") {
+ if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
+ push_error(R"(Expected newline after "@icon" annotation.)");
}
-
- parenthesis--;
-
- tokenizer->advance();
-
- expr = yield;
- }
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_SELF) {
-
- if (p_static) {
- _set_error("\"self\" isn't allowed in a static function or constant expression.");
- return nullptr;
- }
- //constant defined by tokenizer
- SelfNode *self = alloc_node<SelfNode>();
- tokenizer->advance();
- expr = self;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) {
-
- Variant::Type bi_type = tokenizer->get_token_type();
- tokenizer->advance(2);
-
- StringName identifier;
-
- if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT, identifier)) {
-
- completion_built_in_constant = bi_type;
+ annotation->apply(this, head);
+ } else {
+ annotation_stack.push_back(annotation);
}
+ }
+ }
- if (identifier == StringName()) {
-
- _set_error("Built-in type constant or static function expected after \".\".");
- return nullptr;
- }
- if (!Variant::has_constant(bi_type, identifier)) {
+ parse_class_body();
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN &&
- Variant::is_method_const(bi_type, identifier) &&
- Variant::get_method_return_type(bi_type, identifier) == bi_type) {
+#ifdef TOOLS_ENABLED
+ for (Map<int, GDScriptTokenizer::CommentData>::Element *E = tokenizer.get_comments().front(); E; E = E->next()) {
+ if (E->get().new_line && E->get().comment.begins_with("##")) {
+ class_doc_line = MIN(class_doc_line, E->key());
+ }
+ }
+ if (has_comment(class_doc_line)) {
+ get_class_doc_comment(class_doc_line, head->doc_brief_description, head->doc_description, head->doc_tutorials, false);
+ }
+#endif // TOOLS_ENABLED
- tokenizer->advance();
+ if (!check(GDScriptTokenizer::Token::TK_EOF)) {
+ push_error("Expected end of file.");
+ }
- OperatorNode *construct = alloc_node<OperatorNode>();
- construct->op = OperatorNode::OP_CALL;
+ clear_unused_annotations();
+}
- TypeNode *tn = alloc_node<TypeNode>();
- tn->vtype = bi_type;
- construct->arguments.push_back(tn);
+GDScriptParser::ClassNode *GDScriptParser::parse_class() {
+ ClassNode *n_class = alloc_node<ClassNode>();
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_CALL;
- op->arguments.push_back(construct);
+ ClassNode *previous_class = current_class;
+ current_class = n_class;
+ n_class->outer = previous_class;
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
- op->arguments.push_back(id);
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
+ n_class->identifier = parse_identifier();
+ }
- if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
- return nullptr;
+ if (match(GDScriptTokenizer::Token::EXTENDS)) {
+ parse_extends();
+ }
- expr = op;
- } else {
- // Object is a special case
- bool valid = false;
- if (bi_type == Variant::OBJECT) {
- int object_constant = ClassDB::get_integer_constant("Object", identifier, &valid);
- if (valid) {
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = object_constant;
- cn->datatype = _type_from_variant(cn->value);
- expr = cn;
- }
- }
- if (!valid) {
- _set_error("Static constant '" + identifier.operator String() + "' not present in built-in type " + Variant::get_type_name(bi_type) + ".");
- return nullptr;
- }
- }
- } else {
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
+ consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected newline after class declaration.)");
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = Variant::get_constant_value(bi_type, identifier);
- cn->datatype = _type_from_variant(cn->value);
- expr = cn;
- }
+ if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
+ current_class = previous_class;
+ return n_class;
+ }
- } else if (tokenizer->get_token(next_valid_offset) == GDScriptTokenizer::TK_PARENTHESIS_OPEN && tokenizer->is_token_literal()) {
- // We check with is_token_literal, as this allows us to use match/sync/etc. as a name
- //function or constructor
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_CALL;
-
- //Do a quick Array and Dictionary Check. Replace if either require no arguments.
- bool replaced = false;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE) {
- Variant::Type ct = tokenizer->get_token_type();
- if (!p_parsing_constant) {
- if (ct == Variant::ARRAY) {
- if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- ArrayNode *arr = alloc_node<ArrayNode>();
- expr = arr;
- replaced = true;
- tokenizer->advance(3);
- }
- }
- if (ct == Variant::DICTIONARY) {
- if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- DictionaryNode *dict = alloc_node<DictionaryNode>();
- expr = dict;
- replaced = true;
- tokenizer->advance(3);
- }
- }
- }
+ if (match(GDScriptTokenizer::Token::EXTENDS)) {
+ if (n_class->extends_used) {
+ push_error(R"(Cannot use "extends" more than once in the same class.)");
+ }
+ parse_extends();
+ end_statement("superclass");
+ }
- if (!replaced) {
- TypeNode *tn = alloc_node<TypeNode>();
- tn->vtype = tokenizer->get_token_type();
- op->arguments.push_back(tn);
- tokenizer->advance(2);
- }
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC) {
+ parse_class_body();
- BuiltInFunctionNode *bn = alloc_node<BuiltInFunctionNode>();
- bn->function = tokenizer->get_token_built_in_func();
- op->arguments.push_back(bn);
- tokenizer->advance(2);
- } else {
+ consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
- SelfNode *self = alloc_node<SelfNode>();
- op->arguments.push_back(self);
+ current_class = previous_class;
+ return n_class;
+}
- StringName identifier;
- if (_get_completable_identifier(COMPLETION_FUNCTION, identifier)) {
- }
+void GDScriptParser::parse_class_name() {
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
+ current_class->identifier = parse_identifier();
+ }
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
- op->arguments.push_back(id);
- tokenizer->advance(1);
+ // TODO: Move this to annotation
+ if (match(GDScriptTokenizer::Token::COMMA)) {
+ // Icon path.
+ if (consume(GDScriptTokenizer::Token::LITERAL, R"(Expected class icon path string after ",".)")) {
+ if (previous.literal.get_type() != Variant::STRING) {
+ push_error(vformat(R"(Only strings can be used for the class icon path, found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
}
+ current_class->icon_path = previous.literal;
+ }
+ }
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- _make_completable_call(0);
- completion_node = op;
+ if (match(GDScriptTokenizer::Token::EXTENDS)) {
+ // Allow extends on the same line.
+ parse_extends();
+ end_statement("superclass");
+ } else {
+ end_statement("class_name statement");
+ }
+}
- if (op->arguments[0]->type == GDScriptParser::Node::Type::TYPE_BUILT_IN_FUNCTION) {
- BuiltInFunctionNode *bn = static_cast<BuiltInFunctionNode *>(op->arguments[0]);
- if (bn->function == GDScriptFunctions::Function::RESOURCE_LOAD) {
- completion_type = COMPLETION_RESOURCE_PATH;
- }
- }
- }
- if (!replaced) {
- if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
- return nullptr;
- expr = op;
- }
- } else if (tokenizer->is_token_literal(0, true)) {
- // We check with is_token_literal, as this allows us to use match/sync/etc. as a name
- //identifier (reference)
-
- const ClassNode *cln = current_class;
- bool bfn = false;
- StringName identifier;
- int id_line = tokenizer->get_token_line();
- if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) {
- }
+void GDScriptParser::parse_extends() {
+ current_class->extends_used = true;
- BlockNode *b = current_block;
- while (!bfn && b) {
- if (b->variables.has(identifier)) {
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
- id->declared_block = b;
- id->line = id_line;
- expr = id;
- bfn = true;
+ int chain_index = 0;
-#ifdef DEBUG_ENABLED
- LocalVarNode *lv = b->variables[identifier];
- 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: {
- if (lv->assignments == 0) {
- if (!lv->datatype.has_type) {
- _set_error("Using assignment with operation on a variable that was never assigned.");
- return nullptr;
- }
- _add_warning(GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, -1, identifier.operator String());
- }
- [[fallthrough]];
- }
- case GDScriptTokenizer::TK_OP_ASSIGN: {
- lv->assignments += 1;
- lv->usages--; // Assignment is not really usage
- } break;
- default: {
- lv->usages++;
- }
- }
-#endif // DEBUG_ENABLED
- break;
- }
- b = b->parent_block;
- }
+ if (match(GDScriptTokenizer::Token::LITERAL)) {
+ if (previous.literal.get_type() != Variant::STRING) {
+ push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
+ }
+ current_class->extends_path = previous.literal;
- if (!bfn && p_parsing_constant) {
- if (cln->constant_expressions.has(identifier)) {
- expr = cln->constant_expressions[identifier].expression;
- bfn = true;
- } else if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
- //check from constants
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]];
- constant->datatype = _type_from_variant(constant->value);
- constant->line = id_line;
- expr = constant;
- bfn = true;
- }
+ if (!match(GDScriptTokenizer::Token::PERIOD)) {
+ return;
+ }
+ }
- if (!bfn && GDScriptLanguage::get_singleton()->get_named_globals_map().has(identifier)) {
- //check from singletons
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = GDScriptLanguage::get_singleton()->get_named_globals_map()[identifier];
- constant->datatype = _type_from_variant(constant->value);
- expr = constant;
- bfn = true;
- }
+ make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
- if (!dependencies_only) {
- if (!bfn && ScriptServer::is_global_class(identifier)) {
- Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(identifier));
- if (scr.is_valid() && scr->is_valid()) {
- ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value = scr;
- constant->datatype = _type_from_variant(constant->value);
- expr = constant;
- bfn = true;
- }
- }
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
+ return;
+ }
+ current_class->extends.push_back(previous.literal);
- // Check parents for the constant
- 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;
- 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];
- constant->datatype = _type_from_variant(constant->value);
- expr = constant;
- bfn = true;
- }
- }
- }
- }
- }
+ while (match(GDScriptTokenizer::Token::PERIOD)) {
+ make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
+ return;
+ }
+ current_class->extends.push_back(previous.literal);
+ }
+}
- if (!bfn) {
-#ifdef DEBUG_ENABLED
- 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
- } break;
- default: {
- current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] + 1;
- }
- }
- }
- }
-#endif // DEBUG_ENABLED
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
- id->line = id_line;
- expr = id;
- }
+template <class T>
+void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(), AnnotationInfo::TargetKind p_target, const String &p_member_kind) {
+ advance();
+ T *member = (this->*p_parse_function)();
+ if (member == nullptr) {
+ return;
+ }
+#ifdef TOOLS_ENABLED
+ int doc_comment_line = member->start_line - 1;
+#endif // TOOLS_ENABLED
+
+ // Consume annotations.
+ while (!annotation_stack.is_empty()) {
+ AnnotationNode *last_annotation = annotation_stack.back()->get();
+ if (last_annotation->applies_to(p_target)) {
+ last_annotation->apply(this, member);
+ member->annotations.push_front(last_annotation);
+ annotation_stack.pop_back();
+ } else {
+ push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
+ clear_unused_annotations();
+ return;
+ }
+#ifdef TOOLS_ENABLED
+ if (last_annotation->start_line == doc_comment_line) {
+ doc_comment_line--;
+ }
+#endif // TOOLS_ENABLED
+ }
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ADD || tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB || tokenizer->get_token() == GDScriptTokenizer::TK_OP_NOT || tokenizer->get_token() == GDScriptTokenizer::TK_OP_BIT_INVERT) {
+#ifdef TOOLS_ENABLED
+ // Consume doc comments.
+ class_doc_line = MIN(class_doc_line, doc_comment_line - 1);
+ if (has_comment(doc_comment_line)) {
+ if constexpr (std::is_same_v<T, ClassNode>) {
+ get_class_doc_comment(doc_comment_line, member->doc_brief_description, member->doc_description, member->doc_tutorials, true);
+ } else {
+ member->doc_description = get_doc_comment(doc_comment_line);
+ }
+ }
+#endif // TOOLS_ENABLED
- //single prefix operators like !expr +expr -expr ++expr --expr
- alloc_node<OperatorNode>();
- Expression e;
- e.is_op = true;
+ if (member->identifier != nullptr) {
+ // Enums may be unnamed.
+ // TODO: Consider names in outer scope too, for constants and classes (and static functions?)
+ if (current_class->members_indices.has(member->identifier->name)) {
+ push_error(vformat(R"(%s "%s" has the same name as a previously declared %s.)", p_member_kind.capitalize(), member->identifier->name, current_class->get_member(member->identifier->name).get_type_name()), member->identifier);
+ } else {
+ current_class->add_member(member);
+ }
+ }
+}
- switch (tokenizer->get_token()) {
- case GDScriptTokenizer::TK_OP_ADD: e.op = OperatorNode::OP_POS; break;
- case GDScriptTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break;
- case GDScriptTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break;
- case GDScriptTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break;
- default: {
+void GDScriptParser::parse_class_body() {
+ bool class_end = false;
+ while (!class_end && !is_at_end()) {
+ switch (current.type) {
+ case GDScriptTokenizer::Token::VAR:
+ parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable");
+ break;
+ case GDScriptTokenizer::Token::CONST:
+ parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
+ break;
+ case GDScriptTokenizer::Token::SIGNAL:
+ parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
+ break;
+ case GDScriptTokenizer::Token::STATIC:
+ case GDScriptTokenizer::Token::FUNC:
+ parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function");
+ break;
+ case GDScriptTokenizer::Token::CLASS:
+ parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class");
+ break;
+ case GDScriptTokenizer::Token::ENUM:
+ parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
+ break;
+ case GDScriptTokenizer::Token::ANNOTATION: {
+ advance();
+ AnnotationNode *annotation = parse_annotation(AnnotationInfo::CLASS_LEVEL);
+ if (annotation != nullptr) {
+ annotation_stack.push_back(annotation);
}
+ break;
}
+ case GDScriptTokenizer::Token::PASS:
+ advance();
+ end_statement(R"("pass")");
+ break;
+ case GDScriptTokenizer::Token::DEDENT:
+ class_end = true;
+ break;
+ default:
+ push_error(vformat(R"(Unexpected "%s" in class body.)", current.get_name()));
+ advance();
+ break;
+ }
+ if (panic_mode) {
+ synchronize();
+ }
+ }
+}
- tokenizer->advance();
+GDScriptParser::VariableNode *GDScriptParser::parse_variable() {
+ return parse_variable(true);
+}
- if (e.op != OperatorNode::OP_NOT && tokenizer->get_token() == GDScriptTokenizer::TK_OP_NOT) {
- _set_error("Misplaced 'not'.");
- return nullptr;
- }
+GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_allow_property) {
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
+ return nullptr;
+ }
- expression.push_back(e);
- continue; //only exception, must continue...
+ VariableNode *variable = alloc_node<VariableNode>();
+ variable->identifier = parse_identifier();
- /*
- Node *subexpr=_parse_expression(op,p_static);
- if (!subexpr)
- return nullptr;
- op->arguments.push_back(subexpr);
- expr=op;*/
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ if (check(GDScriptTokenizer::Token::NEWLINE)) {
+ if (p_allow_property) {
+ advance();
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_IS && tokenizer->get_token(1) == GDScriptTokenizer::TK_BUILT_IN_TYPE) {
- // 'is' operator with built-in type
- if (!expr) {
- _set_error("Expected identifier before 'is' operator");
+ return parse_property(variable, true);
+ } else {
+ push_error(R"(Expected type after ":")");
return nullptr;
}
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_IS_BUILTIN;
- op->arguments.push_back(expr);
-
- tokenizer->advance();
-
- TypeNode *tn = alloc_node<TypeNode>();
- tn->vtype = tokenizer->get_token_type();
- op->arguments.push_back(tn);
- tokenizer->advance();
-
- expr = op;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_OPEN) {
- // array
- tokenizer->advance();
-
- ArrayNode *arr = alloc_node<ArrayNode>();
- bool expecting_comma = false;
-
- while (true) {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
-
- _set_error("Unterminated array");
- return nullptr;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) {
- tokenizer->advance();
- break;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
-
- tokenizer->advance(); //ignore newline
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- if (!expecting_comma) {
- _set_error("expression or ']' expected");
- return nullptr;
- }
-
- expecting_comma = false;
- tokenizer->advance(); //ignore newline
- } else {
- //parse expression
- if (expecting_comma) {
- _set_error("',' or ']' expected");
- return nullptr;
+ } else if (check((GDScriptTokenizer::Token::EQUAL))) {
+ // Infer type.
+ variable->infer_datatype = true;
+ } else {
+ if (p_allow_property) {
+ make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
+ if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
+ // Check if get or set.
+ if (current.get_identifier() == "get" || current.get_identifier() == "set") {
+ return parse_property(variable, false);
}
- Node *n = _parse_expression(arr, p_static, p_allow_assign, p_parsing_constant);
- if (!n)
- return nullptr;
- arr->elements.push_back(n);
- expecting_comma = true;
}
}
- expr = arr;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) {
- // array
- tokenizer->advance();
-
- DictionaryNode *dict = alloc_node<DictionaryNode>();
-
- enum DictExpect {
-
- DICT_EXPECT_KEY,
- DICT_EXPECT_COLON,
- DICT_EXPECT_VALUE,
- DICT_EXPECT_COMMA
-
- };
-
- Node *key = nullptr;
- Set<Variant> keys;
-
- DictExpect expecting = DICT_EXPECT_KEY;
-
- while (true) {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
-
- _set_error("Unterminated dictionary");
- return nullptr;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
+ // Parse type.
+ variable->datatype_specifier = parse_type();
+ }
+ }
- if (expecting == DICT_EXPECT_COLON) {
- _set_error("':' expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_VALUE) {
- _set_error("value expected");
- return nullptr;
- }
- tokenizer->advance();
- break;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
+ if (match(GDScriptTokenizer::Token::EQUAL)) {
+ // Initializer.
+ variable->initializer = parse_expression(false);
+ variable->assignments++;
+ }
- tokenizer->advance(); //ignore newline
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
+ if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
+ if (match(GDScriptTokenizer::Token::NEWLINE)) {
+ return parse_property(variable, true);
+ } else {
+ return parse_property(variable, false);
+ }
+ }
- if (expecting == DICT_EXPECT_KEY) {
- _set_error("key or '}' expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_VALUE) {
- _set_error("value expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_COLON) {
- _set_error("':' expected");
- return nullptr;
- }
+ end_statement("variable declaration");
- expecting = DICT_EXPECT_KEY;
- tokenizer->advance(); //ignore newline
+ variable->export_info.name = variable->identifier->name;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
+ return variable;
+}
- if (expecting == DICT_EXPECT_KEY) {
- _set_error("key or '}' expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_VALUE) {
- _set_error("value expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_COMMA) {
- _set_error("',' or '}' expected");
- return nullptr;
- }
+GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
+ if (p_need_indent) {
+ if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
+ return nullptr;
+ }
+ }
- expecting = DICT_EXPECT_VALUE;
- tokenizer->advance(); //ignore newline
- } else {
+ VariableNode *property = p_variable;
- if (expecting == DICT_EXPECT_COMMA) {
- _set_error("',' or '}' expected");
- return nullptr;
- }
- if (expecting == DICT_EXPECT_COLON) {
- _set_error("':' expected");
- return nullptr;
- }
+ make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
- if (expecting == DICT_EXPECT_KEY) {
-
- if (tokenizer->is_token_literal() && tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- // We check with is_token_literal, as this allows us to use match/sync/etc. as a name
- //lua style identifier, easier to write
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = tokenizer->get_token_literal();
- cn->datatype = _type_from_variant(cn->value);
- key = cn;
- tokenizer->advance(2);
- expecting = DICT_EXPECT_VALUE;
- } else {
- //python/js style more flexible
- key = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant);
- if (!key)
- return nullptr;
- expecting = DICT_EXPECT_COLON;
- }
- }
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
+ return nullptr;
+ }
- if (expecting == DICT_EXPECT_VALUE) {
- Node *value = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant);
- if (!value)
- return nullptr;
- expecting = DICT_EXPECT_COMMA;
+ IdentifierNode *function = parse_identifier();
- if (key->type == GDScriptParser::Node::TYPE_CONSTANT) {
- Variant const &keyName = static_cast<const GDScriptParser::ConstantNode *>(key)->value;
+ if (check(GDScriptTokenizer::Token::EQUAL)) {
+ p_variable->property = VariableNode::PROP_SETGET;
+ } else {
+ p_variable->property = VariableNode::PROP_INLINE;
+ if (!p_need_indent) {
+ push_error("Property with inline code must go to an indented block.");
+ }
+ }
- if (keys.has(keyName)) {
- _set_error("Duplicate key found in Dictionary literal");
- return nullptr;
- }
- keys.insert(keyName);
- }
+ bool getter_used = false;
+ bool setter_used = false;
- DictionaryNode::Pair pair;
- pair.key = key;
- pair.value = value;
- dict->elements.push_back(pair);
- key = nullptr;
- }
- }
+ // Run with a loop because order doesn't matter.
+ for (int i = 0; i < 2; i++) {
+ if (function->name == "set") {
+ if (setter_used) {
+ push_error(R"(Properties can only have one setter.)");
+ } else {
+ parse_property_setter(property);
+ setter_used = true;
}
-
- expr = dict;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && (tokenizer->is_token_literal(1) || tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR)) {
- // We check with is_token_literal, as this allows us to use match/sync/etc. as a name
- // parent call
-
- tokenizer->advance(); //goto identifier
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_PARENT_CALL;
-
- /*SelfNode *self = alloc_node<SelfNode>();
- op->arguments.push_back(self);
- forbidden for now */
- StringName identifier;
- bool is_completion = _get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier) && for_completion;
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
- op->arguments.push_back(id);
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- if (!is_completion) {
- _set_error("Expected '(' for parent function call.");
- return nullptr;
- }
+ } else if (function->name == "get") {
+ if (getter_used) {
+ push_error(R"(Properties can only have one getter.)");
} else {
- tokenizer->advance();
- if (!_parse_arguments(op, op->arguments, p_static, false, p_parsing_constant)) {
- return nullptr;
- }
+ parse_property_getter(property);
+ getter_used = true;
}
-
- expr = op;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && expression.size() > 0 && expression[expression.size() - 1].is_op && expression[expression.size() - 1].op == OperatorNode::OP_IS) {
- Expression e = expression[expression.size() - 1];
- e.op = OperatorNode::OP_IS_BUILTIN;
- expression.write[expression.size() - 1] = e;
-
- TypeNode *tn = alloc_node<TypeNode>();
- tn->vtype = tokenizer->get_token_type();
- expr = tn;
- tokenizer->advance();
} else {
-
- //find list [ or find dictionary {
- _set_error("Error parsing expression, misplaced: " + String(tokenizer->get_token_name(tokenizer->get_token())));
- return nullptr; //nothing
+ // TODO: Update message to only have the missing one if it's the case.
+ push_error(R"(Expected "get" or "set" for property declaration.)");
}
- ERR_FAIL_COND_V_MSG(!expr, nullptr, "GDScriptParser bug, couldn't figure out what expression is.");
-
- /******************/
- /* Parse Indexing */
- /******************/
-
- while (true) {
-
- //expressions can be indexed any number of times
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) {
-
- //indexing using "."
-
- if (tokenizer->get_token(1) != GDScriptTokenizer::TK_CURSOR && !tokenizer->is_token_literal(1)) {
- // We check with is_token_literal, as this allows us to use match/sync/etc. as a name
- _set_error("Expected identifier as member");
- return nullptr;
- } else if (tokenizer->get_token(2) == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- //call!!
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_CALL;
-
- tokenizer->advance();
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- 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
- tokenizer->advance(1);
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- _make_completable_call(0);
- completion_node = op;
+ if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
+ if (match(GDScriptTokenizer::Token::COMMA)) {
+ // Consume potential newline.
+ if (match(GDScriptTokenizer::Token::NEWLINE)) {
+ if (!p_need_indent) {
+ push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
}
- if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
- return nullptr;
- expr = op;
-
- } else {
- //simple indexing!
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_INDEX_NAMED;
- tokenizer->advance();
-
- StringName identifier;
- if (_get_completable_identifier(COMPLETION_INDEX, identifier)) {
-
- if (identifier == StringName()) {
- identifier = "@temp"; //so it parses alright
- }
- completion_node = op;
-
- //indexing stuff
- }
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = identifier;
-
- op->arguments.push_back(expr);
- op->arguments.push_back(id);
-
- expr = op;
}
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_OPEN) {
- //indexing using "[]"
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_INDEX;
-
- tokenizer->advance(1);
-
- Node *subexpr = _parse_expression(op, p_static, p_allow_assign, p_parsing_constant);
- if (!subexpr) {
- return nullptr;
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_BRACKET_CLOSE) {
- _set_error("Expected ']'");
- return nullptr;
- }
-
- op->arguments.push_back(expr);
- op->arguments.push_back(subexpr);
- tokenizer->advance(1);
- expr = op;
-
- } else
+ } else {
break;
- }
-
- /*****************/
- /* Parse Casting */
- /*****************/
-
- bool has_casting = expr->type == Node::TYPE_CAST;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_AS) {
- if (has_casting) {
- _set_error("Unexpected 'as'.");
- return nullptr;
- }
- CastNode *cn = alloc_node<CastNode>();
- if (!_parse_type(cn->cast_type)) {
- _set_error("Expected type after 'as'.");
- return nullptr;
}
- has_casting = true;
- cn->source_node = expr;
- expr = cn;
- }
-
- /******************/
- /* Parse Operator */
- /******************/
-
- if (parenthesis > 0) {
- //remove empty space (only allowed if inside parenthesis
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- }
- }
-
- Expression e;
- e.is_op = false;
- e.node = expr;
- expression.push_back(e);
-
- // determine which operator is next
-
- OperatorNode::Operator op;
- bool valid = true;
-
-//assign, if allowed is only allowed on the first operator
-#define _VALIDATE_ASSIGN \
- if (!p_allow_assign || has_casting) { \
- _set_error("Unexpected assign."); \
- return nullptr; \
- } \
- p_allow_assign = false;
-
- switch (tokenizer->get_token()) { //see operator
-
- case GDScriptTokenizer::TK_OP_IN: op = OperatorNode::OP_IN; break;
- case GDScriptTokenizer::TK_OP_EQUAL: op = OperatorNode::OP_EQUAL; break;
- case GDScriptTokenizer::TK_OP_NOT_EQUAL: op = OperatorNode::OP_NOT_EQUAL; break;
- case GDScriptTokenizer::TK_OP_LESS: op = OperatorNode::OP_LESS; break;
- case GDScriptTokenizer::TK_OP_LESS_EQUAL: op = OperatorNode::OP_LESS_EQUAL; break;
- case GDScriptTokenizer::TK_OP_GREATER: op = OperatorNode::OP_GREATER; break;
- case GDScriptTokenizer::TK_OP_GREATER_EQUAL: op = OperatorNode::OP_GREATER_EQUAL; break;
- case GDScriptTokenizer::TK_OP_AND: op = OperatorNode::OP_AND; break;
- case GDScriptTokenizer::TK_OP_OR: op = OperatorNode::OP_OR; break;
- case GDScriptTokenizer::TK_OP_ADD: op = OperatorNode::OP_ADD; break;
- case GDScriptTokenizer::TK_OP_SUB: op = OperatorNode::OP_SUB; break;
- case GDScriptTokenizer::TK_OP_MUL: op = OperatorNode::OP_MUL; break;
- case GDScriptTokenizer::TK_OP_DIV: op = OperatorNode::OP_DIV; break;
- case GDScriptTokenizer::TK_OP_MOD:
- op = OperatorNode::OP_MOD;
- break;
- //case GDScriptTokenizer::TK_OP_NEG: op=OperatorNode::OP_NEG ; break;
- case GDScriptTokenizer::TK_OP_SHIFT_LEFT: op = OperatorNode::OP_SHIFT_LEFT; break;
- case GDScriptTokenizer::TK_OP_SHIFT_RIGHT: op = OperatorNode::OP_SHIFT_RIGHT; break;
- case GDScriptTokenizer::TK_OP_ASSIGN: {
- _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN;
-
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_CURSOR) {
- //code complete assignment
- completion_type = COMPLETION_ASSIGN;
- completion_node = expr;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_block = current_block;
- completion_found = true;
- tokenizer->advance();
- }
-
- } break;
- case GDScriptTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_ADD; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SUB; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MUL; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_DIV; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MOD; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_LEFT; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_AND; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_OR; break;
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_XOR; break;
- case GDScriptTokenizer::TK_OP_BIT_AND: op = OperatorNode::OP_BIT_AND; break;
- case GDScriptTokenizer::TK_OP_BIT_OR: op = OperatorNode::OP_BIT_OR; break;
- case GDScriptTokenizer::TK_OP_BIT_XOR: op = OperatorNode::OP_BIT_XOR; break;
- case GDScriptTokenizer::TK_PR_IS: op = OperatorNode::OP_IS; break;
- case GDScriptTokenizer::TK_CF_IF: op = OperatorNode::OP_TERNARY_IF; break;
- case GDScriptTokenizer::TK_CF_ELSE: op = OperatorNode::OP_TERNARY_ELSE; break;
- default: valid = false; break;
}
- if (valid) {
- e.is_op = true;
- e.op = op;
- expression.push_back(e);
- tokenizer->advance();
- } else {
+ if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
break;
}
+ function = parse_identifier();
}
- /* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
-
- while (expression.size() > 1) {
-
- int next_op = -1;
- int min_priority = 0xFFFFF;
- bool is_unary = false;
- bool is_ternary = false;
-
- for (int i = 0; i < expression.size(); i++) {
+ if (p_variable->property == VariableNode::PROP_SETGET) {
+ end_statement("property declaration");
+ }
- if (!expression[i].is_op) {
+ if (p_need_indent) {
+ consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
+ }
+ return property;
+}
- continue;
+void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
+ switch (p_variable->property) {
+ case VariableNode::PROP_INLINE:
+ consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
+ p_variable->setter_parameter = parse_identifier();
}
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
+ consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
- int priority;
-
- bool unary = false;
- bool ternary = false;
- bool error = false;
- bool right_to_left = false;
-
- switch (expression[i].op) {
-
- case OperatorNode::OP_IS:
- case OperatorNode::OP_IS_BUILTIN:
- priority = -1;
- break; //before anything
-
- case OperatorNode::OP_BIT_INVERT:
- priority = 0;
- unary = true;
- break;
- case OperatorNode::OP_NEG:
- case OperatorNode::OP_POS:
- priority = 1;
- unary = true;
- break;
-
- case OperatorNode::OP_MUL: priority = 2; break;
- case OperatorNode::OP_DIV: priority = 2; break;
- case OperatorNode::OP_MOD: priority = 2; break;
-
- case OperatorNode::OP_ADD: priority = 3; break;
- case OperatorNode::OP_SUB: priority = 3; break;
-
- case OperatorNode::OP_SHIFT_LEFT: priority = 4; break;
- case OperatorNode::OP_SHIFT_RIGHT: priority = 4; break;
-
- case OperatorNode::OP_BIT_AND: priority = 5; break;
- case OperatorNode::OP_BIT_XOR: priority = 6; break;
- case OperatorNode::OP_BIT_OR: priority = 7; break;
-
- case OperatorNode::OP_LESS: priority = 8; break;
- case OperatorNode::OP_LESS_EQUAL: priority = 8; break;
- case OperatorNode::OP_GREATER: priority = 8; break;
- case OperatorNode::OP_GREATER_EQUAL: priority = 8; break;
-
- case OperatorNode::OP_EQUAL: priority = 8; break;
- case OperatorNode::OP_NOT_EQUAL: priority = 8; break;
-
- case OperatorNode::OP_IN: priority = 10; break;
+ p_variable->setter = parse_suite("setter definition");
+ break;
- case OperatorNode::OP_NOT:
- priority = 11;
- unary = true;
- break;
- case OperatorNode::OP_AND: priority = 12; break;
- case OperatorNode::OP_OR: priority = 13; break;
+ case VariableNode::PROP_SETGET:
+ consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
+ make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
+ p_variable->setter_pointer = parse_identifier();
+ }
+ break;
+ case VariableNode::PROP_NONE:
+ break; // Unreachable.
+ }
+}
- case OperatorNode::OP_TERNARY_IF:
- priority = 14;
- ternary = true;
- right_to_left = true;
- break;
- case OperatorNode::OP_TERNARY_ELSE:
- priority = 14;
- error = true;
- // Rigth-to-left should be false in this case, otherwise it would always error.
- break;
+void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
+ switch (p_variable->property) {
+ case VariableNode::PROP_INLINE:
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "get".)");
- case OperatorNode::OP_ASSIGN: priority = 15; break;
- case OperatorNode::OP_ASSIGN_ADD: priority = 15; break;
- case OperatorNode::OP_ASSIGN_SUB: priority = 15; break;
- case OperatorNode::OP_ASSIGN_MUL: priority = 15; break;
- case OperatorNode::OP_ASSIGN_DIV: priority = 15; break;
- case OperatorNode::OP_ASSIGN_MOD: priority = 15; break;
- case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority = 15; break;
- case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority = 15; break;
- case OperatorNode::OP_ASSIGN_BIT_AND: priority = 15; break;
- case OperatorNode::OP_ASSIGN_BIT_OR: priority = 15; break;
- case OperatorNode::OP_ASSIGN_BIT_XOR: priority = 15; break;
-
- default: {
- _set_error("GDScriptParser bug, invalid operator in expression: " + itos(expression[i].op));
- return nullptr;
- }
+ p_variable->getter = parse_suite("getter definition");
+ break;
+ case VariableNode::PROP_SETGET:
+ consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
+ make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
+ p_variable->getter_pointer = parse_identifier();
}
+ break;
+ case VariableNode::PROP_NONE:
+ break; // Unreachable.
+ }
+}
- if (priority < min_priority || (right_to_left && priority == min_priority)) {
- // < is used for left to right (default)
- // <= is used for right to left
- if (error) {
- _set_error("Unexpected operator");
- return nullptr;
- }
- next_op = i;
- min_priority = priority;
- is_unary = unary;
- is_ternary = ternary;
- }
- }
+GDScriptParser::ConstantNode *GDScriptParser::parse_constant() {
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
+ return nullptr;
+ }
- if (next_op == -1) {
+ ConstantNode *constant = alloc_node<ConstantNode>();
+ constant->identifier = parse_identifier();
- _set_error("Yet another parser bug....");
- ERR_FAIL_V(nullptr);
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ if (check((GDScriptTokenizer::Token::EQUAL))) {
+ // Infer type.
+ constant->infer_datatype = true;
+ } else {
+ // Parse type.
+ constant->datatype_specifier = parse_type();
}
+ }
- // OK! create operator..
- if (is_unary) {
-
- int expr_pos = next_op;
- while (expression[expr_pos].is_op) {
-
- expr_pos++;
- if (expr_pos == expression.size()) {
- //can happen..
- _set_error("Unexpected end of expression...");
- return nullptr;
- }
- }
+ if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
+ // Initializer.
+ constant->initializer = parse_expression(false);
- //consecutively do unary operators
- for (int i = expr_pos - 1; i >= next_op; i--) {
+ if (constant->initializer == nullptr) {
+ push_error(R"(Expected initializer expression for constant.)");
+ return nullptr;
+ }
+ } else {
+ return nullptr;
+ }
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = expression[i].op;
- op->arguments.push_back(expression[i + 1].node);
- op->line = op_line; //line might have been changed from a \n
- expression.write[i].is_op = false;
- expression.write[i].node = op;
- expression.remove(i + 1);
- }
+ end_statement("constant declaration");
- } else if (is_ternary) {
- if (next_op < 1 || next_op >= (expression.size() - 1)) {
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
- }
+ return constant;
+}
- if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) {
- _set_error("Expected else after ternary if.");
- return nullptr;
- }
- if (next_op >= (expression.size() - 3)) {
- _set_error("Expected value after ternary else.");
- return nullptr;
- }
+GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
+ return nullptr;
+ }
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = expression[next_op].op;
- op->line = op_line; //line might have been changed from a \n
+ ParameterNode *parameter = alloc_node<ParameterNode>();
+ parameter->identifier = parse_identifier();
- if (expression[next_op - 1].is_op) {
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ if (check((GDScriptTokenizer::Token::EQUAL))) {
+ // Infer type.
+ parameter->infer_datatype = true;
+ } else {
+ // Parse type.
+ make_completion_context(COMPLETION_TYPE_NAME, parameter);
+ parameter->datatype_specifier = parse_type();
+ }
+ }
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
- }
+ if (match(GDScriptTokenizer::Token::EQUAL)) {
+ // Default value.
+ parameter->default_value = parse_expression(false);
+ }
- if (expression[next_op + 1].is_op) {
- // this is not invalid and can really appear
- // but it becomes invalid anyway because no binary op
- // can be followed by a unary op in a valid combination,
- // due to how precedence works, unaries will always disappear first
+ return parameter;
+}
- _set_error("Unexpected two consecutive operators after ternary if.");
- return nullptr;
- }
+GDScriptParser::SignalNode *GDScriptParser::parse_signal() {
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
+ return nullptr;
+ }
- if (expression[next_op + 3].is_op) {
- // this is not invalid and can really appear
- // but it becomes invalid anyway because no binary op
- // can be followed by a unary op in a valid combination,
- // due to how precedence works, unaries will always disappear first
+ SignalNode *signal = alloc_node<SignalNode>();
+ signal->identifier = parse_identifier();
- _set_error("Unexpected two consecutive operators after ternary else.");
- return nullptr;
+ if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
+ do {
+ if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
+ // Allow for trailing comma.
+ break;
}
- op->arguments.push_back(expression[next_op + 1].node); //next expression goes as first
- op->arguments.push_back(expression[next_op - 1].node); //left expression goes as when-true
- op->arguments.push_back(expression[next_op + 3].node); //expression after next goes as when-false
-
- //replace all 3 nodes by this operator and make it an expression
- expression.write[next_op - 1].node = op;
- expression.remove(next_op);
- expression.remove(next_op);
- expression.remove(next_op);
- expression.remove(next_op);
- } else {
-
- if (next_op < 1 || next_op >= (expression.size() - 1)) {
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
+ ParameterNode *parameter = parse_parameter();
+ if (parameter == nullptr) {
+ push_error("Expected signal parameter name.");
+ break;
}
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = expression[next_op].op;
- op->line = op_line; //line might have been changed from a \n
-
- if (expression[next_op - 1].is_op) {
-
- _set_error("Parser bug...");
- ERR_FAIL_V(nullptr);
+ if (parameter->default_value != nullptr) {
+ push_error(R"(Signal parameters cannot have a default value.)");
}
-
- if (expression[next_op + 1].is_op) {
- // this is not invalid and can really appear
- // but it becomes invalid anyway because no binary op
- // can be followed by a unary op in a valid combination,
- // due to how precedence works, unaries will always disappear first
-
- _set_error("Unexpected two consecutive operators.");
- return nullptr;
+ if (signal->parameters_indices.has(parameter->identifier->name)) {
+ push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
+ } else {
+ signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
+ signal->parameters.push_back(parameter);
}
+ } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
- op->arguments.push_back(expression[next_op - 1].node); //expression goes as left
- op->arguments.push_back(expression[next_op + 1].node); //next expression goes as right
-
- //replace all 3 nodes by this operator and make it an expression
- expression.write[next_op - 1].node = op;
- expression.remove(next_op);
- expression.remove(next_op);
- }
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
}
- return expression[0].node;
-}
+ end_statement("signal declaration");
-GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to_const) {
+ return signal;
+}
- switch (p_node->type) {
+GDScriptParser::EnumNode *GDScriptParser::parse_enum() {
+ EnumNode *enum_node = alloc_node<EnumNode>();
+ bool named = false;
- case Node::TYPE_BUILT_IN_FUNCTION: {
- //many may probably be optimizable
- return p_node;
- } break;
- case Node::TYPE_ARRAY: {
+ if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
+ advance();
+ enum_node->identifier = parse_identifier();
+ named = true;
+ }
- ArrayNode *an = static_cast<ArrayNode *>(p_node);
- bool all_constants = true;
+ push_multiline(true);
+ consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
- for (int i = 0; i < an->elements.size(); i++) {
+ HashMap<StringName, int> elements;
- an->elements.write[i] = _reduce_expression(an->elements[i], p_to_const);
- if (an->elements[i]->type != Node::TYPE_CONSTANT)
- all_constants = false;
+ do {
+ if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
+ break; // Allow trailing comma.
+ }
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
+ EnumNode::Value item;
+ item.identifier = parse_identifier();
+ item.parent_enum = enum_node;
+ item.line = previous.start_line;
+ item.leftmost_column = previous.leftmost_column;
+ item.rightmost_column = previous.rightmost_column;
+
+ if (elements.has(item.identifier->name)) {
+ push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
+ } else if (!named) {
+ // TODO: Abstract this recursive member check.
+ ClassNode *parent = current_class;
+ while (parent != nullptr) {
+ if (parent->members_indices.has(item.identifier->name)) {
+ push_error(vformat(R"(Name "%s" is already used as a class %s.)", item.identifier->name, parent->get_member(item.identifier->name).get_type_name()));
+ break;
+ }
+ parent = parent->outer;
+ }
}
- if (all_constants && p_to_const) {
- //reduce constant array expression
+ elements[item.identifier->name] = item.line;
- ConstantNode *cn = alloc_node<ConstantNode>();
- Array arr;
- arr.resize(an->elements.size());
- for (int i = 0; i < an->elements.size(); i++) {
- ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]);
- arr[i] = acn->value;
+ if (match(GDScriptTokenizer::Token::EQUAL)) {
+ ExpressionNode *value = parse_expression(false);
+ if (value == nullptr) {
+ push_error(R"(Expected expression value after "=".)");
}
- cn->value = arr;
- cn->datatype = _type_from_variant(cn->value);
- return cn;
+ item.custom_value = value;
}
+ item.rightmost_column = previous.rightmost_column;
- return an;
-
- } break;
- case Node::TYPE_DICTIONARY: {
-
- DictionaryNode *dn = static_cast<DictionaryNode *>(p_node);
- bool all_constants = true;
-
- for (int i = 0; i < dn->elements.size(); i++) {
-
- dn->elements.write[i].key = _reduce_expression(dn->elements[i].key, p_to_const);
- if (dn->elements[i].key->type != Node::TYPE_CONSTANT)
- all_constants = false;
- dn->elements.write[i].value = _reduce_expression(dn->elements[i].value, p_to_const);
- if (dn->elements[i].value->type != Node::TYPE_CONSTANT)
- all_constants = false;
+ item.index = enum_node->values.size();
+ enum_node->values.push_back(item);
+ if (!named) {
+ // Add as member of current class.
+ current_class->add_member(item);
}
+ }
+ } while (match(GDScriptTokenizer::Token::COMMA));
- if (all_constants && p_to_const) {
- //reduce constant array expression
-
- ConstantNode *cn = alloc_node<ConstantNode>();
- Dictionary dict;
- for (int i = 0; i < dn->elements.size(); i++) {
- ConstantNode *key_c = static_cast<ConstantNode *>(dn->elements[i].key);
- ConstantNode *value_c = static_cast<ConstantNode *>(dn->elements[i].value);
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
- dict[key_c->value] = value_c->value;
+#ifdef TOOLS_ENABLED
+ // Enum values documentaion.
+ for (int i = 0; i < enum_node->values.size(); i++) {
+ if (i == enum_node->values.size() - 1) {
+ // If close bracket is same line as last value.
+ if (enum_node->values[i].line != previous.start_line && has_comment(enum_node->values[i].line)) {
+ if (named) {
+ enum_node->values.write[i].doc_description = get_doc_comment(enum_node->values[i].line, true);
+ } else {
+ current_class->set_enum_value_doc(enum_node->values[i].identifier->name, get_doc_comment(enum_node->values[i].line, true));
}
- cn->value = dict;
- cn->datatype = _type_from_variant(cn->value);
- return cn;
}
-
- return dn;
-
- } break;
- case Node::TYPE_OPERATOR: {
-
- OperatorNode *op = static_cast<OperatorNode *>(p_node);
-
- bool all_constants = true;
- int last_not_constant = -1;
-
- for (int i = 0; i < op->arguments.size(); i++) {
-
- op->arguments.write[i] = _reduce_expression(op->arguments[i], p_to_const);
- if (op->arguments[i]->type != Node::TYPE_CONSTANT) {
- all_constants = false;
- last_not_constant = i;
+ } else {
+ // If two values are same line.
+ if (enum_node->values[i].line != enum_node->values[i + 1].line && has_comment(enum_node->values[i].line)) {
+ if (named) {
+ enum_node->values.write[i].doc_description = get_doc_comment(enum_node->values[i].line, true);
+ } else {
+ current_class->set_enum_value_doc(enum_node->values[i].identifier->name, get_doc_comment(enum_node->values[i].line, true));
}
}
+ }
+ }
+#endif // TOOLS_ENABLED
- if (op->op == OperatorNode::OP_IS) {
- //nothing much
- return op;
- }
- if (op->op == OperatorNode::OP_PARENT_CALL) {
- //nothing much
- return op;
-
- } else if (op->op == OperatorNode::OP_CALL) {
- //can reduce base type constructors
- if ((op->arguments[0]->type == Node::TYPE_TYPE || (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && GDScriptFunctions::is_deterministic(static_cast<BuiltInFunctionNode *>(op->arguments[0])->function))) && last_not_constant == 0) {
-
- //native type constructor or intrinsic function
- const Variant **vptr = nullptr;
- Vector<Variant *> ptrs;
- if (op->arguments.size() > 1) {
-
- ptrs.resize(op->arguments.size() - 1);
- for (int i = 0; i < ptrs.size(); i++) {
-
- ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i + 1]);
- ptrs.write[i] = &cn->value;
- }
-
- vptr = (const Variant **)&ptrs[0];
- }
-
- Callable::CallError ce;
- Variant v;
-
- if (op->arguments[0]->type == Node::TYPE_TYPE) {
- TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]);
- v = Variant::construct(tn->vtype, vptr, ptrs.size(), ce);
-
- } else {
- GDScriptFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function;
- GDScriptFunctions::call(func, vptr, ptrs.size(), v, ce);
- }
-
- if (ce.error != Callable::CallError::CALL_OK) {
-
- String errwhere;
- if (op->arguments[0]->type == Node::TYPE_TYPE) {
- TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]);
- errwhere = "'" + Variant::get_type_name(tn->vtype) + "' constructor";
-
- } else {
- GDScriptFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function;
- errwhere = String("'") + GDScriptFunctions::get_func_name(func) + "' intrinsic function";
- }
-
- switch (ce.error) {
+ end_statement("enum");
- case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
+ return enum_node;
+}
- _set_error("Invalid argument (#" + itos(ce.argument + 1) + ") for " + errwhere + ".");
+GDScriptParser::FunctionNode *GDScriptParser::parse_function() {
+ bool _static = false;
+ if (previous.type == GDScriptTokenizer::Token::STATIC) {
+ // TODO: Improve message if user uses "static" with "var" or "const"
+ if (!consume(GDScriptTokenizer::Token::FUNC, R"(Expected "func" after "static".)")) {
+ return nullptr;
+ }
+ _static = true;
+ }
- } break;
- case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
+ FunctionNode *function = alloc_node<FunctionNode>();
+ make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
- _set_error("Too many arguments for " + errwhere + ".");
- } break;
- case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
+ return nullptr;
+ }
- _set_error("Too few arguments for " + errwhere + ".");
- } break;
- default: {
- _set_error("Invalid arguments for " + errwhere + ".");
+ FunctionNode *previous_function = current_function;
+ current_function = function;
- } break;
- }
+ function->identifier = parse_identifier();
+ function->is_static = _static;
- error_line = op->line;
+ push_multiline(true);
+ consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
- return p_node;
- }
+ SuiteNode *body = alloc_node<SuiteNode>();
+ SuiteNode *previous_suite = current_suite;
+ current_suite = body;
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = v;
- cn->datatype = _type_from_variant(v);
- return cn;
+ if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
+ bool default_used = false;
+ do {
+ if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
+ // Allow for trailing comma.
+ break;
+ }
+ ParameterNode *parameter = parse_parameter();
+ if (parameter == nullptr) {
+ break;
+ }
+ if (parameter->default_value != nullptr) {
+ default_used = true;
+ } else {
+ if (default_used) {
+ push_error("Cannot have a mandatory parameters after optional parameters.");
+ continue;
}
+ }
+ if (function->parameters_indices.has(parameter->identifier->name)) {
+ push_error(vformat(R"(Parameter with name "%s" was already declared for this function.)", parameter->identifier->name));
+ } else {
+ function->parameters_indices[parameter->identifier->name] = function->parameters.size();
+ function->parameters.push_back(parameter);
+ body->add_local(parameter);
+ }
+ } while (match(GDScriptTokenizer::Token::COMMA));
+ }
- return op; //don't reduce yet
-
- } else if (op->op == OperatorNode::OP_YIELD) {
- return op;
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after function parameters.)*");
- } else if (op->op == OperatorNode::OP_INDEX) {
- //can reduce indices into constant arrays or dictionaries
+ if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
+ make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, function);
+ function->return_type = parse_type(true);
+ if (function->return_type == nullptr) {
+ push_error(R"(Expected return type or "void" after "->".)");
+ }
+ }
- if (all_constants) {
+ // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after function declaration.)");
- ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]);
- ConstantNode *cb = static_cast<ConstantNode *>(op->arguments[1]);
+ current_suite = previous_suite;
+ function->body = parse_suite("function declaration", body);
- bool valid;
+ current_function = previous_function;
+ return function;
+}
- Variant v = ca->value.get(cb->value, &valid);
- if (!valid) {
- _set_error("invalid index in constant expression");
- error_line = op->line;
- return op;
- }
+GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
+ AnnotationNode *annotation = alloc_node<AnnotationNode>();
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = v;
- cn->datatype = _type_from_variant(v);
- return cn;
- }
+ annotation->name = previous.literal;
- return op;
+ make_completion_context(COMPLETION_ANNOTATION, annotation);
- } else if (op->op == OperatorNode::OP_INDEX_NAMED) {
+ bool valid = true;
- if (op->arguments[0]->type == Node::TYPE_CONSTANT && op->arguments[1]->type == Node::TYPE_IDENTIFIER) {
+ if (!valid_annotations.has(annotation->name)) {
+ push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
+ valid = false;
+ }
- ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]);
- IdentifierNode *ib = static_cast<IdentifierNode *>(op->arguments[1]);
+ annotation->info = &valid_annotations[annotation->name];
- bool valid;
- Variant v = ca->value.get_named(ib->name, &valid);
- if (!valid) {
- _set_error("invalid index '" + String(ib->name) + "' in constant expression");
- error_line = op->line;
- return op;
- }
+ if (!annotation->applies_to(p_valid_targets)) {
+ push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
+ valid = false;
+ }
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = v;
- cn->datatype = _type_from_variant(v);
- return cn;
+ if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
+ // Arguments.
+ push_completion_call(annotation);
+ make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, 0, true);
+ if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
+ int argument_index = 0;
+ do {
+ make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index, true);
+ set_last_completion_call_arg(argument_index++);
+ ExpressionNode *argument = parse_expression(false);
+ if (argument == nullptr) {
+ valid = false;
+ continue;
}
+ annotation->arguments.push_back(argument);
+ } while (match(GDScriptTokenizer::Token::COMMA));
- return op;
- }
-
- //validate assignment (don't assign to constant expression
- switch (op->op) {
-
- case OperatorNode::OP_ASSIGN:
- case OperatorNode::OP_ASSIGN_ADD:
- case OperatorNode::OP_ASSIGN_SUB:
- case OperatorNode::OP_ASSIGN_MUL:
- case OperatorNode::OP_ASSIGN_DIV:
- case OperatorNode::OP_ASSIGN_MOD:
- case OperatorNode::OP_ASSIGN_SHIFT_LEFT:
- case OperatorNode::OP_ASSIGN_SHIFT_RIGHT:
- case OperatorNode::OP_ASSIGN_BIT_AND:
- case OperatorNode::OP_ASSIGN_BIT_OR:
- case OperatorNode::OP_ASSIGN_BIT_XOR: {
-
- if (op->arguments[0]->type == Node::TYPE_CONSTANT) {
- _set_error("Can't assign to constant", tokenizer->get_token_line() - 1);
- error_line = op->line;
- return op;
- } else if (op->arguments[0]->type == Node::TYPE_SELF) {
- _set_error("Can't assign to self.", op->line);
- error_line = op->line;
- return op;
- }
-
- if (op->arguments[0]->type == Node::TYPE_OPERATOR) {
- OperatorNode *on = static_cast<OperatorNode *>(op->arguments[0]);
- if (on->op != OperatorNode::OP_INDEX && on->op != OperatorNode::OP_INDEX_NAMED) {
- _set_error("Can't assign to an expression", tokenizer->get_token_line() - 1);
- error_line = op->line;
- return op;
- }
- }
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
+ }
+ pop_completion_call();
+ }
- } break;
- default: {
- break;
- }
- }
- //now se if all are constants
- if (!all_constants)
- return op; //nothing to reduce from here on
-#define _REDUCE_UNARY(m_vop) \
- bool valid = false; \
- Variant res; \
- Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, Variant(), res, valid); \
- if (!valid) { \
- _set_error("Invalid operand for unary operator"); \
- error_line = op->line; \
- return p_node; \
- } \
- ConstantNode *cn = alloc_node<ConstantNode>(); \
- cn->value = res; \
- cn->datatype = _type_from_variant(res); \
- return cn;
-
-#define _REDUCE_BINARY(m_vop) \
- bool valid = false; \
- Variant res; \
- Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, static_cast<ConstantNode *>(op->arguments[1])->value, res, valid); \
- if (!valid) { \
- _set_error("Invalid operands for operator"); \
- error_line = op->line; \
- return p_node; \
- } \
- ConstantNode *cn = alloc_node<ConstantNode>(); \
- cn->value = res; \
- cn->datatype = _type_from_variant(res); \
- return cn;
-
- switch (op->op) {
-
- //unary operators
- case OperatorNode::OP_NEG: {
- _REDUCE_UNARY(Variant::OP_NEGATE);
- } break;
- case OperatorNode::OP_POS: {
- _REDUCE_UNARY(Variant::OP_POSITIVE);
- } break;
- case OperatorNode::OP_NOT: {
- _REDUCE_UNARY(Variant::OP_NOT);
- } break;
- case OperatorNode::OP_BIT_INVERT: {
- _REDUCE_UNARY(Variant::OP_BIT_NEGATE);
- } break;
- //binary operators (in precedence order)
- case OperatorNode::OP_IN: {
- _REDUCE_BINARY(Variant::OP_IN);
- } break;
- case OperatorNode::OP_EQUAL: {
- _REDUCE_BINARY(Variant::OP_EQUAL);
- } break;
- case OperatorNode::OP_NOT_EQUAL: {
- _REDUCE_BINARY(Variant::OP_NOT_EQUAL);
- } break;
- case OperatorNode::OP_LESS: {
- _REDUCE_BINARY(Variant::OP_LESS);
- } break;
- case OperatorNode::OP_LESS_EQUAL: {
- _REDUCE_BINARY(Variant::OP_LESS_EQUAL);
- } break;
- case OperatorNode::OP_GREATER: {
- _REDUCE_BINARY(Variant::OP_GREATER);
- } break;
- case OperatorNode::OP_GREATER_EQUAL: {
- _REDUCE_BINARY(Variant::OP_GREATER_EQUAL);
- } break;
- case OperatorNode::OP_AND: {
- _REDUCE_BINARY(Variant::OP_AND);
- } break;
- case OperatorNode::OP_OR: {
- _REDUCE_BINARY(Variant::OP_OR);
- } break;
- case OperatorNode::OP_ADD: {
- _REDUCE_BINARY(Variant::OP_ADD);
- } break;
- case OperatorNode::OP_SUB: {
- _REDUCE_BINARY(Variant::OP_SUBTRACT);
- } break;
- case OperatorNode::OP_MUL: {
- _REDUCE_BINARY(Variant::OP_MULTIPLY);
- } break;
- case OperatorNode::OP_DIV: {
- _REDUCE_BINARY(Variant::OP_DIVIDE);
- } break;
- case OperatorNode::OP_MOD: {
- _REDUCE_BINARY(Variant::OP_MODULE);
- } break;
- case OperatorNode::OP_SHIFT_LEFT: {
- _REDUCE_BINARY(Variant::OP_SHIFT_LEFT);
- } break;
- case OperatorNode::OP_SHIFT_RIGHT: {
- _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT);
- } break;
- case OperatorNode::OP_BIT_AND: {
- _REDUCE_BINARY(Variant::OP_BIT_AND);
- } break;
- case OperatorNode::OP_BIT_OR: {
- _REDUCE_BINARY(Variant::OP_BIT_OR);
- } break;
- case OperatorNode::OP_BIT_XOR: {
- _REDUCE_BINARY(Variant::OP_BIT_XOR);
- } break;
- case OperatorNode::OP_TERNARY_IF: {
- if (static_cast<ConstantNode *>(op->arguments[0])->value.booleanize()) {
- return op->arguments[1];
- } else {
- return op->arguments[2];
- }
- } break;
- default: {
- ERR_FAIL_V(op);
- }
- }
+ match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
- } break;
- default: {
- return p_node;
- } break;
+ if (valid) {
+ valid = validate_annotation_arguments(annotation);
}
-}
-
-GDScriptParser::Node *GDScriptParser::_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const, bool p_allow_assign) {
- Node *expr = _parse_expression(p_parent, p_static, p_allow_assign, p_reduce_const);
- if (!expr || error_set)
- return nullptr;
- expr = _reduce_expression(expr, p_reduce_const);
- if (!expr || error_set)
- return nullptr;
- return expr;
+ return valid ? annotation : nullptr;
}
-bool GDScriptParser::_reduce_export_var_type(Variant &p_value, int p_line) {
-
- if (p_value.get_type() == Variant::ARRAY) {
- Array arr = p_value;
- for (int i = 0; i < arr.size(); i++) {
- if (!_reduce_export_var_type(arr[i], p_line)) return false;
- }
- return true;
- }
-
- if (p_value.get_type() == Variant::DICTIONARY) {
- Dictionary dict = p_value;
- for (int i = 0; i < dict.size(); i++) {
- Variant value = dict.get_value_at_index(i);
- if (!_reduce_export_var_type(value, p_line)) return false;
- }
- return true;
+void GDScriptParser::clear_unused_annotations() {
+ for (const List<AnnotationNode *>::Element *E = annotation_stack.front(); E != nullptr; E = E->next()) {
+ AnnotationNode *annotation = E->get();
+ push_error(vformat(R"(Annotation "%s" does not precedes a valid target, so it will have no effect.)", annotation->name), annotation);
}
- // validate type
- DataType type = _type_from_variant(p_value);
- if (type.kind == DataType::BUILTIN) {
- return true;
- } else if (type.kind == DataType::NATIVE) {
- if (ClassDB::is_parent_class(type.native_type, "Resource")) {
- return true;
- }
- }
- _set_error("Invalid export type. Only built-in and native resource types can be exported.", p_line);
- return false;
+ annotation_stack.clear();
}
-bool GDScriptParser::_recover_from_completion() {
+bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, int p_optional_arguments, bool p_is_vararg) {
+ ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
- if (!completion_found) {
- return false; //can't recover if no completion
- }
- //skip stuff until newline
- while (tokenizer->get_token() != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token() != GDScriptTokenizer::TK_EOF && tokenizer->get_token() != GDScriptTokenizer::TK_ERROR) {
- tokenizer->advance();
- }
- completion_found = false;
- error_set = false;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) {
- error_set = true;
+ AnnotationInfo new_annotation;
+ new_annotation.info = p_info;
+ new_annotation.info.default_arguments.resize(p_optional_arguments);
+ if (p_is_vararg) {
+ new_annotation.info.flags |= METHOD_FLAG_VARARG;
}
+ new_annotation.apply = p_apply;
+ new_annotation.target_kind = p_target_kinds;
+ valid_annotations[p_info.name] = new_annotation;
return true;
}
-GDScriptParser::PatternNode *GDScriptParser::_parse_pattern(bool p_static) {
+GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite) {
+ SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
+ suite->parent_block = current_suite;
+ current_suite = suite;
- PatternNode *pattern = alloc_node<PatternNode>();
+ bool multiline = false;
- GDScriptTokenizer::Token token = tokenizer->get_token();
- if (error_set)
- return nullptr;
-
- if (token == GDScriptTokenizer::TK_EOF) {
- return nullptr;
+ if (check(GDScriptTokenizer::Token::NEWLINE)) {
+ multiline = true;
}
- switch (token) {
- // array
- case GDScriptTokenizer::TK_BRACKET_OPEN: {
- tokenizer->advance();
- pattern->pt_type = GDScriptParser::PatternNode::PT_ARRAY;
- while (true) {
+ if (multiline) {
+ consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after %s.)", p_context));
- if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) {
- tokenizer->advance();
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) {
- // match everything
- tokenizer->advance(2);
- PatternNode *sub_pattern = alloc_node<PatternNode>();
- sub_pattern->pt_type = GDScriptParser::PatternNode::PT_IGNORE_REST;
- pattern->array.push_back(sub_pattern);
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA && tokenizer->get_token(1) == GDScriptTokenizer::TK_BRACKET_CLOSE) {
- tokenizer->advance(2);
- break;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) {
- tokenizer->advance(1);
- break;
- } else {
- _set_error("'..' pattern only allowed at the end of an array pattern");
- return nullptr;
- }
- }
-
- PatternNode *sub_pattern = _parse_pattern(p_static);
- if (!sub_pattern) {
- return nullptr;
- }
+ if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
+ current_suite = suite->parent_block;
+ return suite;
+ }
+ }
- pattern->array.push_back(sub_pattern);
+ do {
+ Node *statement = parse_statement();
+ if (statement == nullptr) {
+ continue;
+ }
+ suite->statements.push_back(statement);
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- continue;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_BRACKET_CLOSE) {
- tokenizer->advance();
- break;
- } else {
- _set_error("Not a valid pattern");
- return nullptr;
- }
- }
- } break;
- // bind
- case GDScriptTokenizer::TK_PR_VAR: {
- tokenizer->advance();
- if (!tokenizer->is_token_literal()) {
- _set_error("Expected identifier for binding variable name.");
- return nullptr;
- }
- pattern->pt_type = GDScriptParser::PatternNode::PT_BIND;
- pattern->bind = tokenizer->get_token_literal();
- // Check if variable name is already used
- BlockNode *bl = current_block;
- while (bl) {
- if (bl->variables.has(pattern->bind)) {
- _set_error("Binding name of '" + pattern->bind.operator String() + "' is already declared in this scope.");
- return nullptr;
+ // Register locals.
+ switch (statement->type) {
+ case Node::VARIABLE: {
+ VariableNode *variable = static_cast<VariableNode *>(statement);
+ const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
+ if (local.type != SuiteNode::Local::UNDEFINED) {
+ push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name));
}
- bl = bl->parent_block;
+ current_suite->add_local(variable);
+ break;
}
- // Create local variable for proper identifier detection later
- LocalVarNode *lv = alloc_node<LocalVarNode>();
- lv->name = pattern->bind;
- current_block->variables.insert(lv->name, lv);
- tokenizer->advance();
- } break;
- // dictionary
- case GDScriptTokenizer::TK_CURLY_BRACKET_OPEN: {
- tokenizer->advance();
- pattern->pt_type = GDScriptParser::PatternNode::PT_DICTIONARY;
- while (true) {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
- tokenizer->advance();
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDScriptTokenizer::TK_PERIOD) {
- // match everything
- tokenizer->advance(2);
- PatternNode *sub_pattern = alloc_node<PatternNode>();
- sub_pattern->pt_type = PatternNode::PT_IGNORE_REST;
- pattern->array.push_back(sub_pattern);
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA && tokenizer->get_token(1) == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
- tokenizer->advance(2);
- break;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
- tokenizer->advance(1);
- break;
+ case Node::CONSTANT: {
+ ConstantNode *constant = static_cast<ConstantNode *>(statement);
+ const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
+ if (local.type != SuiteNode::Local::UNDEFINED) {
+ String name;
+ if (local.type == SuiteNode::Local::CONSTANT) {
+ name = "constant";
} else {
- _set_error("'..' pattern only allowed at the end of a dictionary pattern");
- return nullptr;
+ name = "variable";
}
+ push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name));
}
+ current_suite->add_local(constant);
+ break;
+ }
+ default:
+ break;
+ }
- Node *key = _parse_and_reduce_expression(pattern, p_static);
- if (!key) {
- _set_error("Not a valid key in pattern");
- return nullptr;
- }
+ } while (multiline && !check(GDScriptTokenizer::Token::DEDENT) && !is_at_end());
- if (key->type != GDScriptParser::Node::TYPE_CONSTANT) {
- _set_error("Not a constant expression as key");
- return nullptr;
- }
+ if (multiline) {
+ consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
+ }
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
- tokenizer->advance();
+ current_suite = suite->parent_block;
+ return suite;
+}
- PatternNode *value = _parse_pattern(p_static);
- if (!value) {
- _set_error("Expected pattern in dictionary value");
- return nullptr;
- }
+GDScriptParser::Node *GDScriptParser::parse_statement() {
+ Node *result = nullptr;
+#ifdef DEBUG_ENABLED
+ bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
+#endif
- pattern->dictionary.insert(static_cast<ConstantNode *>(key), value);
- } else {
- pattern->dictionary.insert(static_cast<ConstantNode *>(key), nullptr);
+ switch (current.type) {
+ case GDScriptTokenizer::Token::PASS:
+ advance();
+ result = alloc_node<PassNode>();
+ end_statement(R"("pass")");
+ break;
+ case GDScriptTokenizer::Token::VAR:
+ advance();
+ result = parse_variable();
+ break;
+ case GDScriptTokenizer::Token::CONST:
+ advance();
+ result = parse_constant();
+ break;
+ case GDScriptTokenizer::Token::IF:
+ advance();
+ result = parse_if();
+ break;
+ case GDScriptTokenizer::Token::FOR:
+ advance();
+ result = parse_for();
+ break;
+ case GDScriptTokenizer::Token::WHILE:
+ advance();
+ result = parse_while();
+ break;
+ case GDScriptTokenizer::Token::MATCH:
+ advance();
+ result = parse_match();
+ break;
+ case GDScriptTokenizer::Token::BREAK:
+ advance();
+ result = parse_break();
+ break;
+ case GDScriptTokenizer::Token::CONTINUE:
+ advance();
+ result = parse_continue();
+ break;
+ case GDScriptTokenizer::Token::RETURN: {
+ advance();
+ ReturnNode *n_return = alloc_node<ReturnNode>();
+ if (!is_statement_end()) {
+ if (current_function && current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init) {
+ push_error(R"(Constructor cannot return a value.)");
}
+ n_return->return_value = parse_expression(false);
+ }
+ result = n_return;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- continue;
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
- tokenizer->advance();
- break;
- } else {
- _set_error("Not a valid pattern");
- return nullptr;
- }
+ current_suite->has_return = true;
+
+ end_statement("return statement");
+ break;
+ }
+ case GDScriptTokenizer::Token::BREAKPOINT:
+ advance();
+ result = alloc_node<BreakpointNode>();
+ end_statement(R"("breakpoint")");
+ break;
+ case GDScriptTokenizer::Token::ASSERT:
+ advance();
+ result = parse_assert();
+ break;
+ case GDScriptTokenizer::Token::ANNOTATION: {
+ advance();
+ AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
+ if (annotation != nullptr) {
+ annotation_stack.push_back(annotation);
}
- } break;
- case GDScriptTokenizer::TK_WILDCARD: {
- tokenizer->advance();
- pattern->pt_type = PatternNode::PT_WILDCARD;
- } break;
- // all the constants like strings and numbers
+ break;
+ }
default: {
- Node *value = _parse_and_reduce_expression(pattern, p_static);
- if (!value) {
- _set_error("Expect constant expression or variables in a pattern");
- return nullptr;
+ // Expression statement.
+ ExpressionNode *expression = parse_expression(true); // Allow assignment here.
+ if (expression == nullptr) {
+ push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
}
+ end_statement("expression");
+ result = expression;
- if (value->type == Node::TYPE_OPERATOR) {
- // Maybe it's SomeEnum.VALUE
- Node *current_value = value;
-
- while (current_value->type == Node::TYPE_OPERATOR) {
- OperatorNode *op_node = static_cast<OperatorNode *>(current_value);
-
- if (op_node->op != OperatorNode::OP_INDEX_NAMED) {
- _set_error("Invalid operator in pattern. Only index (`A.B`) is allowed");
- return nullptr;
- }
- current_value = op_node->arguments[0];
- }
-
- if (current_value->type != Node::TYPE_IDENTIFIER) {
- _set_error("Only constant expression or variables allowed in a pattern");
- return nullptr;
+#ifdef DEBUG_ENABLED
+ if (expression != nullptr) {
+ switch (expression->type) {
+ case Node::CALL:
+ case Node::ASSIGNMENT:
+ case Node::AWAIT:
+ // Fine.
+ break;
+ default:
+ push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
}
-
- } else if (value->type != Node::TYPE_IDENTIFIER && value->type != Node::TYPE_CONSTANT) {
- _set_error("Only constant expressions or variables allowed in a pattern");
- return nullptr;
}
-
- pattern->pt_type = PatternNode::PT_CONSTANT;
- pattern->constant = value;
- } break;
- }
-
- return pattern;
-}
-
-void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static) {
- IndentLevel current_level = indent_level.back()->get();
-
- p_block->has_return = true;
-
- bool catch_all_appeared = false;
-
- while (true) {
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline())
- ;
-
- // GDScriptTokenizer::Token token = tokenizer->get_token();
- if (error_set)
- return;
-
- if (current_level.indent > indent_level.back()->get().indent) {
- break; // go back a level
- }
-
- pending_newline = -1;
-
- PatternBranchNode *branch = alloc_node<PatternBranchNode>();
- branch->body = alloc_node<BlockNode>();
- branch->body->parent_block = p_block;
- p_block->sub_blocks.push_back(branch->body);
- current_block = branch->body;
-
- branch->patterns.push_back(_parse_pattern(p_static));
- if (!branch->patterns[0]) {
+#endif
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;
+ if (unreachable && result != nullptr) {
+ current_suite->has_unreachable_code = true;
+ if (current_function) {
+ push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier->name);
+ } else {
+ // TODO: Properties setters and getters with unreachable code are not being warned
}
+ }
#endif
- while (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- branch->patterns.push_back(_parse_pattern(p_static));
- if (!branch->patterns[branch->patterns.size() - 1]) {
- return;
- }
-
- PatternNode::PatternType pt = branch->patterns[branch->patterns.size() - 1]->pt_type;
+ if (panic_mode) {
+ synchronize();
+ }
- if (pt == PatternNode::PT_BIND) {
- _set_error("Cannot use bindings with multipattern.");
- return;
- }
+ return result;
+}
- catch_all = catch_all || pt == PatternNode::PT_WILDCARD;
- }
+GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
+ // TODO: Add assert message.
+ AssertNode *assert = alloc_node<AssertNode>();
- catch_all_appeared = catch_all_appeared || catch_all;
+ consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
+ assert->condition = parse_expression(false);
+ if (assert->condition == nullptr) {
+ push_error("Expected expression to assert.");
+ return nullptr;
+ }
- if (!_enter_indent_block()) {
- _set_error("Expected block in pattern branch");
- return;
+ if (match(GDScriptTokenizer::Token::COMMA)) {
+ // Error message.
+ assert->message = parse_expression(false);
+ if (assert->message == nullptr) {
+ push_error(R"(Expected error message for assert after ",".)");
+ return nullptr;
}
+ }
- _parse_block(branch->body, p_static);
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
- current_block = p_block;
+ end_statement(R"("assert")");
- if (!branch->body->has_return) {
- p_block->has_return = false;
- }
+ return assert;
+}
- p_branches.push_back(branch);
+GDScriptParser::BreakNode *GDScriptParser::parse_break() {
+ if (!can_break) {
+ push_error(R"(Cannot use "break" outside of a loop.)");
}
+ end_statement(R"("break")");
+ return alloc_node<BreakNode>();
+}
- // Even if all branches return, there is possibility of default fallthrough
- if (!catch_all_appeared) {
- p_block->has_return = false;
+GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
+ if (!can_continue) {
+ push_error(R"(Cannot use "continue" outside of a loop or pattern matching block.)");
}
+ current_suite->has_continue = true;
+ end_statement(R"("continue")");
+ ContinueNode *cont = alloc_node<ContinueNode>();
+ cont->is_for_match = is_continue_match;
+ return cont;
}
-void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) {
-
- const DataType &to_match_type = p_node_to_match->get_datatype();
-
- switch (p_pattern->pt_type) {
- case PatternNode::PT_CONSTANT: {
-
- DataType pattern_type = _reduce_node_type(p_pattern->constant);
- if (error_set) {
- return;
- }
-
- OperatorNode *type_comp = nullptr;
-
- // static type check if possible
- if (pattern_type.has_type && to_match_type.has_type) {
- if (!_is_type_compatible(to_match_type, pattern_type) && !_is_type_compatible(pattern_type, to_match_type)) {
- _set_error("The pattern type (" + pattern_type.to_string() + ") isn't compatible with the type of the value to match (" + to_match_type.to_string() + ").",
- p_pattern->line);
- return;
- }
- } else {
- // runtime typecheck
- BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
- typeof_node->function = GDScriptFunctions::TYPE_OF;
-
- OperatorNode *typeof_match_value = alloc_node<OperatorNode>();
- typeof_match_value->op = OperatorNode::OP_CALL;
- typeof_match_value->arguments.push_back(typeof_node);
- typeof_match_value->arguments.push_back(p_node_to_match);
-
- OperatorNode *typeof_pattern_value = alloc_node<OperatorNode>();
- typeof_pattern_value->op = OperatorNode::OP_CALL;
- typeof_pattern_value->arguments.push_back(typeof_node);
- typeof_pattern_value->arguments.push_back(p_pattern->constant);
-
- type_comp = alloc_node<OperatorNode>();
- type_comp->op = OperatorNode::OP_EQUAL;
- type_comp->arguments.push_back(typeof_match_value);
- type_comp->arguments.push_back(typeof_pattern_value);
- }
-
- // compare the actual values
- OperatorNode *value_comp = alloc_node<OperatorNode>();
- value_comp->op = OperatorNode::OP_EQUAL;
- value_comp->arguments.push_back(p_pattern->constant);
- value_comp->arguments.push_back(p_node_to_match);
-
- if (type_comp) {
- OperatorNode *full_comparison = alloc_node<OperatorNode>();
- full_comparison->op = OperatorNode::OP_AND;
- full_comparison->arguments.push_back(type_comp);
- full_comparison->arguments.push_back(value_comp);
-
- p_resulting_node = full_comparison;
- } else {
- p_resulting_node = value_comp;
- }
-
- } break;
- case PatternNode::PT_BIND: {
- p_bindings[p_pattern->bind] = p_node_to_match;
-
- // a bind always matches
- ConstantNode *true_value = alloc_node<ConstantNode>();
- true_value->value = Variant(true);
- true_value->datatype = _type_from_variant(true_value->value);
- p_resulting_node = true_value;
- } break;
- case PatternNode::PT_ARRAY: {
-
- bool open_ended = false;
-
- if (p_pattern->array.size() > 0) {
- if (p_pattern->array[p_pattern->array.size() - 1]->pt_type == PatternNode::PT_IGNORE_REST) {
- open_ended = true;
- }
- }
-
- // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() >= length
- // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() == length
-
- {
- OperatorNode *type_comp = nullptr;
- // static type check if possible
- if (to_match_type.has_type) {
- // must be an array
- if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::ARRAY) {
- _set_error("Cannot match an array pattern with a non-array expression.", p_pattern->line);
- return;
- }
- } else {
- // runtime typecheck
- BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
- typeof_node->function = GDScriptFunctions::TYPE_OF;
-
- OperatorNode *typeof_match_value = alloc_node<OperatorNode>();
- typeof_match_value->op = OperatorNode::OP_CALL;
- typeof_match_value->arguments.push_back(typeof_node);
- typeof_match_value->arguments.push_back(p_node_to_match);
-
- IdentifierNode *typeof_array = alloc_node<IdentifierNode>();
- typeof_array->name = "TYPE_ARRAY";
-
- type_comp = alloc_node<OperatorNode>();
- type_comp->op = OperatorNode::OP_EQUAL;
- type_comp->arguments.push_back(typeof_match_value);
- type_comp->arguments.push_back(typeof_array);
- }
-
- // size
- ConstantNode *length = alloc_node<ConstantNode>();
- length->value = Variant(open_ended ? p_pattern->array.size() - 1 : p_pattern->array.size());
- length->datatype = _type_from_variant(length->value);
-
- OperatorNode *call = alloc_node<OperatorNode>();
- call->op = OperatorNode::OP_CALL;
- call->arguments.push_back(p_node_to_match);
-
- IdentifierNode *size = alloc_node<IdentifierNode>();
- size->name = "size";
- call->arguments.push_back(size);
-
- OperatorNode *length_comparison = alloc_node<OperatorNode>();
- length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL;
- length_comparison->arguments.push_back(call);
- length_comparison->arguments.push_back(length);
-
- if (type_comp) {
- OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>();
- type_and_length_comparison->op = OperatorNode::OP_AND;
- type_and_length_comparison->arguments.push_back(type_comp);
- type_and_length_comparison->arguments.push_back(length_comparison);
-
- p_resulting_node = type_and_length_comparison;
- } else {
- p_resulting_node = length_comparison;
- }
- }
-
- for (int i = 0; i < p_pattern->array.size(); i++) {
- PatternNode *pattern = p_pattern->array[i];
-
- Node *condition = nullptr;
-
- ConstantNode *index = alloc_node<ConstantNode>();
- index->value = Variant(i);
- index->datatype = _type_from_variant(index->value);
-
- OperatorNode *indexed_value = alloc_node<OperatorNode>();
- indexed_value->op = OperatorNode::OP_INDEX;
- indexed_value->arguments.push_back(p_node_to_match);
- indexed_value->arguments.push_back(index);
-
- _generate_pattern(pattern, indexed_value, condition, p_bindings);
-
- // concatenate all the patterns with &&
- OperatorNode *and_node = alloc_node<OperatorNode>();
- and_node->op = OperatorNode::OP_AND;
- and_node->arguments.push_back(p_resulting_node);
- and_node->arguments.push_back(condition);
-
- p_resulting_node = and_node;
- }
-
- } break;
- case PatternNode::PT_DICTIONARY: {
-
- bool open_ended = false;
+GDScriptParser::ForNode *GDScriptParser::parse_for() {
+ ForNode *n_for = alloc_node<ForNode>();
- if (p_pattern->array.size() > 0) {
- open_ended = true;
- }
-
- // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() >= length
- // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() == length
-
- {
- OperatorNode *type_comp = nullptr;
- // static type check if possible
- if (to_match_type.has_type) {
- // must be an dictionary
- if (to_match_type.kind != DataType::BUILTIN || to_match_type.builtin_type != Variant::DICTIONARY) {
- _set_error("Cannot match an dictionary pattern with a non-dictionary expression.", p_pattern->line);
- return;
- }
- } else {
- // runtime typecheck
- BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
- typeof_node->function = GDScriptFunctions::TYPE_OF;
-
- OperatorNode *typeof_match_value = alloc_node<OperatorNode>();
- typeof_match_value->op = OperatorNode::OP_CALL;
- typeof_match_value->arguments.push_back(typeof_node);
- typeof_match_value->arguments.push_back(p_node_to_match);
-
- IdentifierNode *typeof_dictionary = alloc_node<IdentifierNode>();
- typeof_dictionary->name = "TYPE_DICTIONARY";
-
- type_comp = alloc_node<OperatorNode>();
- type_comp->op = OperatorNode::OP_EQUAL;
- type_comp->arguments.push_back(typeof_match_value);
- type_comp->arguments.push_back(typeof_dictionary);
- }
-
- // size
- ConstantNode *length = alloc_node<ConstantNode>();
- length->value = Variant(open_ended ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size());
- length->datatype = _type_from_variant(length->value);
-
- OperatorNode *call = alloc_node<OperatorNode>();
- call->op = OperatorNode::OP_CALL;
- call->arguments.push_back(p_node_to_match);
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
+ n_for->variable = parse_identifier();
+ }
- IdentifierNode *size = alloc_node<IdentifierNode>();
- size->name = "size";
- call->arguments.push_back(size);
+ consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable name.)");
- OperatorNode *length_comparison = alloc_node<OperatorNode>();
- length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL;
- length_comparison->arguments.push_back(call);
- length_comparison->arguments.push_back(length);
+ n_for->list = parse_expression(false);
- if (type_comp) {
- OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>();
- type_and_length_comparison->op = OperatorNode::OP_AND;
- type_and_length_comparison->arguments.push_back(type_comp);
- type_and_length_comparison->arguments.push_back(length_comparison);
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
- p_resulting_node = type_and_length_comparison;
- } else {
- p_resulting_node = length_comparison;
- }
- }
+ // Save break/continue state.
+ bool could_break = can_break;
+ bool could_continue = can_continue;
+ bool was_continue_match = is_continue_match;
- for (Map<ConstantNode *, PatternNode *>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) {
+ // Allow break/continue.
+ can_break = true;
+ can_continue = true;
+ is_continue_match = false;
- Node *condition = nullptr;
-
- // check for has, then for pattern
+ SuiteNode *suite = alloc_node<SuiteNode>();
+ if (n_for->variable) {
+ suite->add_local(SuiteNode::Local(n_for->variable));
+ }
+ suite->parent_for = n_for;
- IdentifierNode *has = alloc_node<IdentifierNode>();
- has->name = "has";
+ n_for->loop = parse_suite(R"("for" block)", suite);
- OperatorNode *has_call = alloc_node<OperatorNode>();
- has_call->op = OperatorNode::OP_CALL;
- has_call->arguments.push_back(p_node_to_match);
- has_call->arguments.push_back(has);
- has_call->arguments.push_back(e->key());
+ // Reset break/continue state.
+ can_break = could_break;
+ can_continue = could_continue;
+ is_continue_match = was_continue_match;
- if (e->value()) {
+ return n_for;
+}
- OperatorNode *indexed_value = alloc_node<OperatorNode>();
- indexed_value->op = OperatorNode::OP_INDEX;
- indexed_value->arguments.push_back(p_node_to_match);
- indexed_value->arguments.push_back(e->key());
+GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
+ IfNode *n_if = alloc_node<IfNode>();
- _generate_pattern(e->value(), indexed_value, condition, p_bindings);
+ n_if->condition = parse_expression(false);
+ if (n_if->condition == nullptr) {
+ push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
+ }
- OperatorNode *has_and_pattern = alloc_node<OperatorNode>();
- has_and_pattern->op = OperatorNode::OP_AND;
- has_and_pattern->arguments.push_back(has_call);
- has_and_pattern->arguments.push_back(condition);
+ consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
- condition = has_and_pattern;
+ n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
+ n_if->true_block->parent_if = n_if;
- } else {
- condition = has_call;
- }
-
- // concatenate all the patterns with &&
- OperatorNode *and_node = alloc_node<OperatorNode>();
- and_node->op = OperatorNode::OP_AND;
- and_node->arguments.push_back(p_resulting_node);
- and_node->arguments.push_back(condition);
-
- p_resulting_node = and_node;
- }
+ if (n_if->true_block->has_continue) {
+ current_suite->has_continue = true;
+ }
- } break;
- case PatternNode::PT_IGNORE_REST:
- case PatternNode::PT_WILDCARD: {
- // simply generate a `true`
- ConstantNode *true_value = alloc_node<ConstantNode>();
- true_value->value = Variant(true);
- true_value->datatype = _type_from_variant(true_value->value);
- p_resulting_node = true_value;
- } break;
- default: {
+ if (match(GDScriptTokenizer::Token::ELIF)) {
+ IfNode *elif = parse_if("elif");
- } break;
+ SuiteNode *else_block = alloc_node<SuiteNode>();
+ else_block->statements.push_back(elif);
+ n_if->false_block = else_block;
+ } else if (match(GDScriptTokenizer::Token::ELSE)) {
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
+ n_if->false_block = parse_suite(R"("else" block)");
}
-}
-void GDScriptParser::_transform_match_statment(MatchNode *p_match_statement) {
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = "#match_value";
- id->line = p_match_statement->line;
- id->datatype = _reduce_node_type(p_match_statement->val_to_match);
- if (id->datatype.has_type) {
- _mark_line_as_safe(id->line);
- } else {
- _mark_line_as_unsafe(id->line);
+ if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
+ current_suite->has_return = true;
}
-
- if (error_set) {
- return;
+ if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
+ current_suite->has_continue = true;
}
- for (int i = 0; i < p_match_statement->branches.size(); i++) {
-
- PatternBranchNode *branch = p_match_statement->branches[i];
+ return n_if;
+}
- MatchNode::CompiledPatternBranch compiled_branch;
- compiled_branch.compiled_pattern = nullptr;
+GDScriptParser::MatchNode *GDScriptParser::parse_match() {
+ MatchNode *match = alloc_node<MatchNode>();
- Map<StringName, Node *> binding;
+ match->test = parse_expression(false);
+ if (match->test == nullptr) {
+ push_error(R"(Expected expression to test after "match".)");
+ }
- for (int j = 0; j < branch->patterns.size(); j++) {
- PatternNode *pattern = branch->patterns[j];
- _mark_line_as_safe(pattern->line);
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
+ consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
- Map<StringName, Node *> bindings;
- Node *resulting_node = nullptr;
- _generate_pattern(pattern, id, resulting_node, bindings);
+ if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
+ return match;
+ }
- if (!resulting_node) {
- return;
- }
+#ifdef DEBUG_ENABLED
+ bool all_have_return = true;
+ bool have_wildcard = false;
+ bool wildcard_has_return = false;
+ bool have_wildcard_without_continue = false;
+#endif
- if (!binding.empty() && !bindings.empty()) {
- _set_error("Multipatterns can't contain bindings");
- return;
- } else {
- binding = bindings;
- }
+ while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
+ MatchBranchNode *branch = parse_match_branch();
+ if (branch == nullptr) {
+ continue;
+ }
- // Result is always a boolean
- DataType resulting_node_type;
- resulting_node_type.has_type = true;
- resulting_node_type.is_constant = true;
- resulting_node_type.kind = DataType::BUILTIN;
- resulting_node_type.builtin_type = Variant::BOOL;
- resulting_node->set_datatype(resulting_node_type);
-
- if (compiled_branch.compiled_pattern) {
- OperatorNode *or_node = alloc_node<OperatorNode>();
- or_node->op = OperatorNode::OP_OR;
- or_node->arguments.push_back(compiled_branch.compiled_pattern);
- or_node->arguments.push_back(resulting_node);
-
- compiled_branch.compiled_pattern = or_node;
- } else {
- // single pattern | first one
- compiled_branch.compiled_pattern = resulting_node;
- }
+#ifdef DEBUG_ENABLED
+ if (have_wildcard_without_continue) {
+ push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
}
- // prepare the body ...hehe
- for (Map<StringName, Node *>::Element *e = binding.front(); e; e = e->next()) {
- if (!branch->body->variables.has(e->key())) {
- _set_error("Parser bug: missing pattern bind variable.", branch->line);
- ERR_FAIL();
+ if (branch->has_wildcard) {
+ have_wildcard = true;
+ if (branch->block->has_return) {
+ wildcard_has_return = true;
+ }
+ if (!branch->block->has_continue) {
+ have_wildcard_without_continue = true;
}
-
- LocalVarNode *local_var = branch->body->variables[e->key()];
- local_var->assign = e->value();
- local_var->set_datatype(local_var->assign->get_datatype());
- local_var->assignments++;
-
- IdentifierNode *id2 = alloc_node<IdentifierNode>();
- id2->name = local_var->name;
- id2->declared_block = branch->body;
- id2->set_datatype(local_var->assign->get_datatype());
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_ASSIGN;
- op->arguments.push_back(id2);
- op->arguments.push_back(local_var->assign);
- local_var->assign_op = op;
-
- branch->body->statements.push_front(op);
- branch->body->statements.push_front(local_var);
}
-
- compiled_branch.body = branch->body;
-
- p_match_statement->compiled_pattern_branches.push_back(compiled_branch);
+ if (!branch->block->has_return) {
+ all_have_return = false;
+ }
+#endif
+ match->branches.push_back(branch);
}
-}
-
-void GDScriptParser::_parse_block(BlockNode *p_block, bool p_static) {
- IndentLevel current_level = indent_level.back()->get();
+ consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
#ifdef DEBUG_ENABLED
-
- NewLineNode *nl = alloc_node<NewLineNode>();
-
- nl->line = tokenizer->get_token_line();
- p_block->statements.push_back(nl);
+ if (wildcard_has_return || (all_have_return && have_wildcard)) {
+ current_suite->has_return = true;
+ }
#endif
- bool is_first_line = true;
+ return match;
+}
- while (true) {
- if (!is_first_line && indent_level.back()->prev() && indent_level.back()->prev()->get().indent == current_level.indent) {
- if (indent_level.back()->prev()->get().is_mixed(current_level)) {
- _set_error("Mixed tabs and spaces in indentation.");
- return;
- }
- // pythonic single-line expression, don't parse future lines
- indent_level.pop_back();
- p_block->end_line = tokenizer->get_token_line();
- return;
- }
- is_first_line = false;
+GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
+ MatchBranchNode *branch = alloc_node<MatchBranchNode>();
- GDScriptTokenizer::Token token = tokenizer->get_token();
- if (error_set)
- return;
+ bool has_bind = false;
- if (current_level.indent > indent_level.back()->get().indent) {
- p_block->end_line = tokenizer->get_token_line();
- return; //go back a level
+ do {
+ PatternNode *pattern = parse_match_pattern();
+ if (pattern == nullptr) {
+ continue;
}
-
- if (pending_newline != -1) {
-
- NewLineNode *nl2 = alloc_node<NewLineNode>();
- nl2->line = pending_newline;
- p_block->statements.push_back(nl2);
- pending_newline = -1;
+ if (pattern->pattern_type == PatternNode::PT_BIND) {
+ has_bind = true;
}
-
-#ifdef DEBUG_ENABLED
- switch (token) {
- case GDScriptTokenizer::TK_EOF:
- case GDScriptTokenizer::TK_ERROR:
- case GDScriptTokenizer::TK_NEWLINE:
- case GDScriptTokenizer::TK_CF_PASS: {
- // will check later
- } break;
- default: {
- if (p_block->has_return && !current_function->has_unreachable_code) {
- _add_warning(GDScriptWarning::UNREACHABLE_CODE, -1, current_function->name.operator String());
- current_function->has_unreachable_code = true;
- }
- } break;
+ if (branch->patterns.size() > 0 && has_bind) {
+ push_error(R"(Cannot use a variable bind with multiple patterns.)");
}
-#endif // DEBUG_ENABLED
- switch (token) {
- case GDScriptTokenizer::TK_EOF: {
- p_block->end_line = tokenizer->get_token_line();
- return; // End of file!
- } break;
- case GDScriptTokenizer::TK_ERROR: {
- return;
- } break;
- case GDScriptTokenizer::TK_NEWLINE: {
-
- int line = tokenizer->get_token_line();
-
- if (!_parse_newline()) {
- if (!error_set) {
- p_block->end_line = tokenizer->get_token_line();
- pending_newline = p_block->end_line;
- }
- return;
- }
+ if (pattern->pattern_type == PatternNode::PT_REST) {
+ push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
+ } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
+ branch->has_wildcard = true;
+ }
+ branch->patterns.push_back(pattern);
+ } while (match(GDScriptTokenizer::Token::COMMA));
- _mark_line_as_safe(line);
- NewLineNode *nl2 = alloc_node<NewLineNode>();
- nl2->line = line;
- p_block->statements.push_back(nl2);
+ if (branch->patterns.is_empty()) {
+ push_error(R"(No pattern found for "match" branch.)");
+ }
- } break;
- case GDScriptTokenizer::TK_CF_PASS: {
- if (tokenizer->get_token(1) != GDScriptTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF) {
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)");
- _set_error("Expected \";\" or a line break.");
- return;
- }
- _mark_line_as_safe(tokenizer->get_token_line());
- tokenizer->advance();
- if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON) {
- // Ignore semicolon after 'pass'.
- tokenizer->advance();
- }
- } break;
- case GDScriptTokenizer::TK_PR_VAR: {
- // Variable declaration and (eventual) initialization.
+ // Save continue state.
+ bool could_continue = can_continue;
+ bool was_continue_match = is_continue_match;
+ // Allow continue for match.
+ can_continue = true;
+ is_continue_match = true;
- tokenizer->advance();
- int var_line = tokenizer->get_token_line();
- if (!tokenizer->is_token_literal(0, true)) {
+ SuiteNode *suite = alloc_node<SuiteNode>();
+ if (branch->patterns.size() > 0) {
+ List<StringName> binds;
+ branch->patterns[0]->binds.get_key_list(&binds);
- _set_error("Expected an identifier for the local variable name.");
- return;
- }
- StringName n = tokenizer->get_token_literal();
- tokenizer->advance();
- if (current_function) {
- for (int i = 0; i < current_function->arguments.size(); i++) {
- if (n == current_function->arguments[i]) {
- _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(current_function->line) + ").");
- return;
- }
- }
- }
- BlockNode *check_block = p_block;
- while (check_block) {
- if (check_block->variables.has(n)) {
- _set_error("Variable \"" + String(n) + "\" already defined in the scope (at line " + itos(check_block->variables[n]->line) + ").");
- return;
- }
- check_block = check_block->parent_block;
- }
+ for (List<StringName>::Element *E = binds.front(); E != nullptr; E = E->next()) {
+ SuiteNode::Local local(branch->patterns[0]->binds[E->get()]);
+ suite->add_local(local);
+ }
+ }
- //must know when the local variable is declared
- LocalVarNode *lv = alloc_node<LocalVarNode>();
- lv->name = n;
- lv->line = var_line;
- p_block->statements.push_back(lv);
+ branch->block = parse_suite("match pattern block", suite);
- Node *assigned = nullptr;
+ // Restore continue state.
+ can_continue = could_continue;
+ is_continue_match = was_continue_match;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- lv->datatype = DataType();
-#ifdef DEBUG_ENABLED
- lv->datatype.infer_type = true;
-#endif
- tokenizer->advance();
- } else if (!_parse_type(lv->datatype)) {
- _set_error("Expected a type for the variable.");
- return;
- }
- }
+ return branch;
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) {
+GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
+ PatternNode *pattern = alloc_node<PatternNode>();
- tokenizer->advance();
- Node *subexpr = _parse_and_reduce_expression(p_block, p_static);
- if (!subexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
+ switch (current.type) {
+ case GDScriptTokenizer::Token::LITERAL:
+ advance();
+ pattern->pattern_type = PatternNode::PT_LITERAL;
+ pattern->literal = parse_literal();
+ if (pattern->literal == nullptr) {
+ // Error happened.
+ return nullptr;
+ }
+ break;
+ case GDScriptTokenizer::Token::VAR: {
+ // Bind.
+ advance();
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
+ return nullptr;
+ }
+ pattern->pattern_type = PatternNode::PT_BIND;
+ pattern->bind = parse_identifier();
- lv->assignments++;
- assigned = subexpr;
- } else {
+ PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
- assigned = _get_default_value_for_type(lv->datatype, var_line);
- }
- //must be added later, to avoid self-referencing.
- p_block->variables.insert(n, lv);
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = n;
- id->declared_block = p_block;
- id->line = var_line;
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_ASSIGN;
- op->arguments.push_back(id);
- op->arguments.push_back(assigned);
- op->line = var_line;
- p_block->statements.push_back(op);
- lv->assign_op = op;
- lv->assign = assigned;
-
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"var\").");
- return;
+ if (p_root_pattern != nullptr) {
+ if (p_root_pattern->has_bind(pattern->bind->name)) {
+ push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
+ return nullptr;
}
+ }
- } break;
- case GDScriptTokenizer::TK_CF_IF: {
+ if (current_suite->has_local(pattern->bind->name)) {
+ push_error(vformat(R"(There's already a %s named "%s" in this scope.)", current_suite->get_local(pattern->bind->name).get_name(), pattern->bind->name));
+ return nullptr;
+ }
- tokenizer->advance();
+ root_pattern->binds[pattern->bind->name] = pattern->bind;
- Node *condition = _parse_and_reduce_expression(p_block, p_static);
- if (!condition) {
- if (_recover_from_completion()) {
- break;
+ } break;
+ case GDScriptTokenizer::Token::UNDERSCORE:
+ // Wildcard.
+ advance();
+ pattern->pattern_type = PatternNode::PT_WILDCARD;
+ break;
+ case GDScriptTokenizer::Token::PERIOD_PERIOD:
+ // Rest.
+ advance();
+ pattern->pattern_type = PatternNode::PT_REST;
+ break;
+ case GDScriptTokenizer::Token::BRACKET_OPEN: {
+ // Array.
+ advance();
+ pattern->pattern_type = PatternNode::PT_ARRAY;
+
+ if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
+ do {
+ PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
+ if (sub_pattern == nullptr) {
+ continue;
}
- return;
- }
-
- ControlFlowNode *cf_if = alloc_node<ControlFlowNode>();
-
- cf_if->cf_type = ControlFlowNode::CF_IF;
- cf_if->arguments.push_back(condition);
-
- cf_if->body = alloc_node<BlockNode>();
- cf_if->body->parent_block = p_block;
- cf_if->body->if_condition = condition; //helps code completion
-
- p_block->sub_blocks.push_back(cf_if->body);
-
- if (!_enter_indent_block(cf_if->body)) {
- _set_error("Expected an indented block after \"if\".");
- p_block->end_line = tokenizer->get_token_line();
- return;
- }
-
- current_block = cf_if->body;
- _parse_block(cf_if->body, p_static);
- current_block = p_block;
-
- if (error_set)
- return;
- p_block->statements.push_back(cf_if);
-
- bool all_have_return = cf_if->body->has_return;
- bool have_else = false;
-
- while (true) {
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline())
- ;
-
- if (indent_level.back()->get().indent < current_level.indent) { //not at current indent level
- p_block->end_line = tokenizer->get_token_line();
- return;
+ if (pattern->rest_used) {
+ push_error(R"(The ".." pattern must be the last element in the pattern array.)");
+ } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
+ pattern->rest_used = true;
}
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELIF) {
-
- if (indent_level.back()->get().indent > current_level.indent) {
-
- _set_error("Invalid indentation.");
- return;
- }
-
- tokenizer->advance();
-
- cf_if->body_else = alloc_node<BlockNode>();
- cf_if->body_else->parent_block = p_block;
- p_block->sub_blocks.push_back(cf_if->body_else);
-
- ControlFlowNode *cf_else = alloc_node<ControlFlowNode>();
- cf_else->cf_type = ControlFlowNode::CF_IF;
-
- //condition
- Node *condition2 = _parse_and_reduce_expression(p_block, p_static);
- if (!condition2) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
- cf_else->arguments.push_back(condition2);
- cf_else->cf_type = ControlFlowNode::CF_IF;
-
- cf_if->body_else->statements.push_back(cf_else);
- cf_if = cf_else;
- cf_if->body = alloc_node<BlockNode>();
- cf_if->body->parent_block = p_block;
- p_block->sub_blocks.push_back(cf_if->body);
-
- if (!_enter_indent_block(cf_if->body)) {
- _set_error("Expected an indented block after \"elif\".");
- p_block->end_line = tokenizer->get_token_line();
- return;
- }
-
- current_block = cf_else->body;
- _parse_block(cf_else->body, p_static);
- current_block = p_block;
- if (error_set)
- return;
-
- all_have_return = all_have_return && cf_else->body->has_return;
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CF_ELSE) {
-
- if (indent_level.back()->get().indent > current_level.indent) {
- _set_error("Invalid indentation.");
- return;
+ pattern->array.push_back(sub_pattern);
+ } while (match(GDScriptTokenizer::Token::COMMA));
+ }
+ consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
+ break;
+ }
+ case GDScriptTokenizer::Token::BRACE_OPEN: {
+ // Dictionary.
+ advance();
+ pattern->pattern_type = PatternNode::PT_DICTIONARY;
+
+ if (!check(GDScriptTokenizer::Token::BRACE_CLOSE) && !is_at_end()) {
+ do {
+ if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
+ // Rest.
+ if (pattern->rest_used) {
+ push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
+ } else {
+ PatternNode *sub_pattern = alloc_node<PatternNode>();
+ sub_pattern->pattern_type = PatternNode::PT_REST;
+ pattern->dictionary.push_back({ nullptr, sub_pattern });
+ pattern->rest_used = true;
}
-
- tokenizer->advance();
- cf_if->body_else = alloc_node<BlockNode>();
- cf_if->body_else->parent_block = p_block;
- p_block->sub_blocks.push_back(cf_if->body_else);
-
- if (!_enter_indent_block(cf_if->body_else)) {
- _set_error("Expected an indented block after \"else\".");
- p_block->end_line = tokenizer->get_token_line();
- return;
+ } else {
+ ExpressionNode *key = parse_expression(false);
+ if (key == nullptr) {
+ push_error(R"(Expected expression as key for dictionary pattern.)");
}
- current_block = cf_if->body_else;
- _parse_block(cf_if->body_else, p_static);
- current_block = p_block;
- if (error_set)
- return;
-
- all_have_return = all_have_return && cf_if->body_else->has_return;
- have_else = true;
-
- break; //after else, exit
-
- } else
- break;
- }
-
- cf_if->body->has_return = all_have_return;
- // If there's no else block, path out of the if might not have a return
- p_block->has_return = all_have_return && have_else;
-
- } break;
- case GDScriptTokenizer::TK_CF_WHILE: {
-
- tokenizer->advance();
- Node *condition2 = _parse_and_reduce_expression(p_block, p_static);
- if (!condition2) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- ControlFlowNode *cf_while = alloc_node<ControlFlowNode>();
-
- cf_while->cf_type = ControlFlowNode::CF_WHILE;
- cf_while->arguments.push_back(condition2);
-
- cf_while->body = alloc_node<BlockNode>();
- cf_while->body->parent_block = p_block;
- p_block->sub_blocks.push_back(cf_while->body);
-
- if (!_enter_indent_block(cf_while->body)) {
- _set_error("Expected an indented block after \"while\".");
- p_block->end_line = tokenizer->get_token_line();
- return;
- }
-
- current_block = cf_while->body;
- _parse_block(cf_while->body, p_static);
- current_block = p_block;
- if (error_set)
- return;
- p_block->has_return = cf_while->body->has_return;
- p_block->statements.push_back(cf_while);
- } break;
- case GDScriptTokenizer::TK_CF_FOR: {
-
- tokenizer->advance();
-
- if (!tokenizer->is_token_literal(0, true)) {
-
- _set_error("Identifier expected after \"for\".");
- }
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = tokenizer->get_token_identifier();
-
- tokenizer->advance();
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_IN) {
- _set_error("\"in\" expected after identifier.");
- return;
- }
-
- tokenizer->advance();
-
- Node *container = _parse_and_reduce_expression(p_block, p_static);
- if (!container) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- DataType iter_type;
-
- if (container->type == Node::TYPE_OPERATOR) {
-
- OperatorNode *op = static_cast<OperatorNode *>(container);
- if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && static_cast<BuiltInFunctionNode *>(op->arguments[0])->function == GDScriptFunctions::GEN_RANGE) {
- //iterating a range, so see if range() can be optimized without allocating memory, by replacing it by vectors (which can work as iterable too!)
-
- Vector<Node *> args;
- Vector<double> constants;
-
- bool constant = true;
-
- for (int i = 1; i < op->arguments.size(); i++) {
- args.push_back(op->arguments[i]);
- if (op->arguments[i]->type == Node::TYPE_CONSTANT) {
- ConstantNode *c = static_cast<ConstantNode *>(op->arguments[i]);
- if (c->value.get_type() == Variant::FLOAT || c->value.get_type() == Variant::INT) {
- constants.push_back(c->value);
- }
- } else {
- constant = false;
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ // Value pattern.
+ PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
+ if (sub_pattern == nullptr) {
+ continue;
}
- }
-
- if (args.size() > 0 && args.size() < 4) {
-
- if (constant) {
-
- ConstantNode *cn = alloc_node<ConstantNode>();
- switch (args.size()) {
- case 1: cn->value = (int)constants[0]; break;
- case 2: cn->value = Vector2(constants[0], constants[1]); break;
- case 3: cn->value = Vector3(constants[0], constants[1], constants[2]); break;
- }
- cn->datatype = _type_from_variant(cn->value);
- container = cn;
+ if (pattern->rest_used) {
+ push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
+ } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
+ push_error(R"(The ".." pattern cannot be used as a value.)");
} else {
- OperatorNode *on = alloc_node<OperatorNode>();
- on->op = OperatorNode::OP_CALL;
-
- TypeNode *tn = alloc_node<TypeNode>();
- on->arguments.push_back(tn);
-
- switch (args.size()) {
- case 1: tn->vtype = Variant::INT; break;
- case 2: tn->vtype = Variant::VECTOR2; break;
- case 3: tn->vtype = Variant::VECTOR3; break;
- }
-
- for (int i = 0; i < args.size(); i++) {
- on->arguments.push_back(args[i]);
- }
-
- container = on;
+ pattern->dictionary.push_back({ key, sub_pattern });
}
+ } else {
+ // Key match only.
+ pattern->dictionary.push_back({ key, nullptr });
}
-
- iter_type.has_type = true;
- iter_type.kind = DataType::BUILTIN;
- iter_type.builtin_type = Variant::INT;
- }
- }
-
- ControlFlowNode *cf_for = alloc_node<ControlFlowNode>();
-
- cf_for->cf_type = ControlFlowNode::CF_FOR;
- cf_for->arguments.push_back(id);
- cf_for->arguments.push_back(container);
-
- cf_for->body = alloc_node<BlockNode>();
- cf_for->body->parent_block = p_block;
- p_block->sub_blocks.push_back(cf_for->body);
-
- if (!_enter_indent_block(cf_for->body)) {
- _set_error("Expected indented block after \"for\".");
- p_block->end_line = tokenizer->get_token_line();
- return;
- }
-
- current_block = cf_for->body;
-
- // this is for checking variable for redefining
- // inside this _parse_block
- LocalVarNode *lv = alloc_node<LocalVarNode>();
- lv->name = id->name;
- lv->line = id->line;
- lv->assignments++;
- id->declared_block = cf_for->body;
- lv->set_datatype(iter_type);
- id->set_datatype(iter_type);
- cf_for->body->variables.insert(id->name, lv);
- _parse_block(cf_for->body, p_static);
- current_block = p_block;
-
- if (error_set)
- return;
- p_block->has_return = cf_for->body->has_return;
- p_block->statements.push_back(cf_for);
- } break;
- case GDScriptTokenizer::TK_CF_CONTINUE: {
-
- _mark_line_as_safe(tokenizer->get_token_line());
- tokenizer->advance();
- ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>();
- cf_continue->cf_type = ControlFlowNode::CF_CONTINUE;
- p_block->statements.push_back(cf_continue);
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"continue\").");
- return;
- }
- } break;
- case GDScriptTokenizer::TK_CF_BREAK: {
-
- _mark_line_as_safe(tokenizer->get_token_line());
- tokenizer->advance();
- ControlFlowNode *cf_break = alloc_node<ControlFlowNode>();
- cf_break->cf_type = ControlFlowNode::CF_BREAK;
- p_block->statements.push_back(cf_break);
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"break\").");
- return;
- }
- } break;
- case GDScriptTokenizer::TK_CF_RETURN: {
-
- tokenizer->advance();
- ControlFlowNode *cf_return = alloc_node<ControlFlowNode>();
- cf_return->cf_type = ControlFlowNode::CF_RETURN;
- cf_return->line = tokenizer->get_token_line(-1);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE || tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
- //expect end of statement
- p_block->statements.push_back(cf_return);
- if (!_end_statement()) {
- return;
- }
- } else {
- //expect expression
- Node *retexpr = _parse_and_reduce_expression(p_block, p_static);
- if (!retexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
- cf_return->arguments.push_back(retexpr);
- p_block->statements.push_back(cf_return);
- if (!_end_statement()) {
- _set_error("Expected end of statement after return expression.");
- return;
}
- }
- p_block->has_return = true;
-
- } break;
- case GDScriptTokenizer::TK_CF_MATCH: {
-
- tokenizer->advance();
-
- MatchNode *match_node = alloc_node<MatchNode>();
-
- Node *val_to_match = _parse_and_reduce_expression(p_block, p_static);
-
- if (!val_to_match) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- match_node->val_to_match = val_to_match;
-
- if (!_enter_indent_block()) {
- _set_error("Expected indented pattern matching block after \"match\".");
- return;
- }
-
- BlockNode *compiled_branches = alloc_node<BlockNode>();
- compiled_branches->parent_block = p_block;
- compiled_branches->parent_class = p_block->parent_class;
-
- p_block->sub_blocks.push_back(compiled_branches);
-
- _parse_pattern_block(compiled_branches, match_node->branches, p_static);
-
- if (error_set) return;
-
- ControlFlowNode *match_cf_node = alloc_node<ControlFlowNode>();
- match_cf_node->cf_type = ControlFlowNode::CF_MATCH;
- match_cf_node->match = match_node;
- match_cf_node->body = compiled_branches;
-
- p_block->has_return = p_block->has_return || compiled_branches->has_return;
- p_block->statements.push_back(match_cf_node);
-
- _end_statement();
- } break;
- case GDScriptTokenizer::TK_PR_ASSERT: {
-
- tokenizer->advance();
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected '(' after assert");
- return;
- }
-
- int assert_line = tokenizer->get_token_line();
-
- tokenizer->advance();
-
- Vector<Node *> args;
- const bool result = _parse_arguments(p_block, args, p_static);
- if (!result) {
- return;
- }
-
- if (args.empty() || args.size() > 2) {
- _set_error("Wrong number of arguments, expected 1 or 2", assert_line);
- return;
- }
-
- AssertNode *an = alloc_node<AssertNode>();
- an->condition = _reduce_expression(args[0], p_static);
- an->line = assert_line;
-
- if (args.size() == 2) {
- an->message = _reduce_expression(args[1], p_static);
- } else {
- ConstantNode *message_node = alloc_node<ConstantNode>();
- message_node->value = String();
- message_node->datatype = _type_from_variant(message_node->value);
- an->message = message_node;
- }
-
- p_block->statements.push_back(an);
-
- if (!_end_statement()) {
- _set_error("Expected end of statement after \"assert\".", assert_line);
- return;
- }
- } break;
- case GDScriptTokenizer::TK_PR_BREAKPOINT: {
-
- tokenizer->advance();
- BreakpointNode *bn = alloc_node<BreakpointNode>();
- p_block->statements.push_back(bn);
-
- if (!_end_statement()) {
- _set_error("Expected end of statement after \"breakpoint\".");
- return;
- }
- } break;
- default: {
-
- Node *expression = _parse_and_reduce_expression(p_block, p_static, false, true);
- if (!expression) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
- p_block->statements.push_back(expression);
- if (!_end_statement()) {
- // Attempt to guess a better error message if the user "retypes" a variable
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON && tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- _set_error("Unexpected ':=', use '=' instead. Expected end of statement after expression.");
- } else {
- _set_error(String() + "Expected end of statement after expression, got " + tokenizer->get_token_name(tokenizer->get_token()) + " instead");
- }
- return;
- }
-
- } break;
- }
- }
-}
-
-bool GDScriptParser::_parse_newline() {
-
- if (tokenizer->get_token(1) != GDScriptTokenizer::TK_EOF && tokenizer->get_token(1) != GDScriptTokenizer::TK_NEWLINE) {
-
- IndentLevel current_level = indent_level.back()->get();
- int indent = tokenizer->get_token_line_indent();
- int tabs = tokenizer->get_token_line_tab_indent();
- IndentLevel new_level(indent, tabs);
-
- if (new_level.is_mixed(current_level)) {
- _set_error("Mixed tabs and spaces in indentation.");
- return false;
- }
-
- if (indent > current_level.indent) {
- _set_error("Unexpected indentation.");
- return false;
+ } while (match(GDScriptTokenizer::Token::COMMA));
+ }
+ consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
+ break;
}
-
- if (indent < current_level.indent) {
-
- while (indent < current_level.indent) {
-
- //exit block
- if (indent_level.size() == 1) {
- _set_error("Invalid indentation. Bug?");
- return false;
- }
-
- indent_level.pop_back();
-
- if (indent_level.back()->get().indent < indent) {
-
- _set_error("Unindent does not match any outer indentation level.");
- return false;
- }
-
- if (indent_level.back()->get().is_mixed(current_level)) {
- _set_error("Mixed tabs and spaces in indentation.");
- return false;
- }
-
- current_level = indent_level.back()->get();
+ default: {
+ // Expression.
+ ExpressionNode *expression = parse_expression(false);
+ if (expression == nullptr) {
+ push_error(R"(Expected expression for match pattern.)");
+ } else {
+ pattern->pattern_type = PatternNode::PT_EXPRESSION;
+ pattern->expression = expression;
}
-
- tokenizer->advance();
- return false;
+ break;
}
}
- tokenizer->advance();
- return true;
+ return pattern;
}
-void GDScriptParser::_parse_extends(ClassNode *p_class) {
-
- if (p_class->extends_used) {
+bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
+ return binds.has(p_name);
+}
- _set_error("\"extends\" can only be present once per script.");
- return;
- }
+GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
+ return binds[p_name];
+}
- if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty()) {
+GDScriptParser::WhileNode *GDScriptParser::parse_while() {
+ WhileNode *n_while = alloc_node<WhileNode>();
- _set_error("\"extends\" must be used before anything else.");
- return;
+ n_while->condition = parse_expression(false);
+ if (n_while->condition == nullptr) {
+ push_error(R"(Expected conditional expression after "while".)");
}
- p_class->extends_used = true;
-
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type() == Variant::OBJECT) {
- p_class->extends_class.push_back(Variant::get_type_name(Variant::OBJECT));
- tokenizer->advance();
- return;
- }
+ consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
- // see if inheritance happens from a file
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) {
+ // Save break/continue state.
+ bool could_break = can_break;
+ bool could_continue = can_continue;
+ bool was_continue_match = is_continue_match;
- Variant constant = tokenizer->get_token_constant();
- if (constant.get_type() != Variant::STRING) {
+ // Allow break/continue.
+ can_break = true;
+ can_continue = true;
+ is_continue_match = false;
- _set_error("\"extends\" constant must be a string.");
- return;
- }
+ n_while->loop = parse_suite(R"("while" block)");
- p_class->extends_file = constant;
- tokenizer->advance();
+ // Reset break/continue state.
+ can_break = could_break;
+ can_continue = could_continue;
+ is_continue_match = was_continue_match;
- // Add parent script as a dependency
- String parent = constant;
- if (parent.is_rel_path()) {
- parent = base_path.plus_file(parent).simplify_path();
- }
- dependencies.push_back(parent);
+ return n_while;
+}
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PERIOD) {
- return;
- } else
- tokenizer->advance();
+GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
+ // Switch multiline mode on for grouping tokens.
+ // Do this early to avoid the tokenizer generating whitespace tokens.
+ switch (current.type) {
+ case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
+ case GDScriptTokenizer::Token::BRACE_OPEN:
+ case GDScriptTokenizer::Token::BRACKET_OPEN:
+ push_multiline(true);
+ break;
+ default:
+ break; // Nothing to do.
}
- while (true) {
+ // Completion can appear whenever an expression is expected.
+ make_completion_context(COMPLETION_IDENTIFIER, nullptr);
- switch (tokenizer->get_token()) {
+ GDScriptTokenizer::Token token = advance();
+ ParseFunction prefix_rule = get_rule(token.type)->prefix;
- case GDScriptTokenizer::TK_IDENTIFIER: {
-
- StringName identifier = tokenizer->get_token_identifier();
- p_class->extends_class.push_back(identifier);
- } break;
-
- case GDScriptTokenizer::TK_PERIOD:
- break;
+ if (prefix_rule == nullptr) {
+ // Expected expression. Let the caller give the proper error message.
+ return nullptr;
+ }
- default: {
+ ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
- _set_error("Invalid \"extends\" syntax, expected string constant (path) and/or identifier (parent class).");
- return;
- }
+ while (p_precedence <= get_rule(current.type)->precedence) {
+ if (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) {
+ return previous_operand;
}
-
- tokenizer->advance(1);
-
- switch (tokenizer->get_token()) {
-
- case GDScriptTokenizer::TK_IDENTIFIER:
- case GDScriptTokenizer::TK_PERIOD:
- continue;
-
+ // Also switch multiline mode on here for infix operators.
+ switch (current.type) {
+ // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
+ case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
+ case GDScriptTokenizer::Token::BRACKET_OPEN:
+ push_multiline(true);
+ break;
default:
- return;
+ break; // Nothing to do.
}
+ token = advance();
+ ParseFunction infix_rule = get_rule(token.type)->infix;
+ previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
}
-}
-void GDScriptParser::_parse_class(ClassNode *p_class) {
+ return previous_operand;
+}
- IndentLevel current_level = indent_level.back()->get();
+GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
+ return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
+}
- while (true) {
+GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
+ return static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
+}
- GDScriptTokenizer::Token token = tokenizer->get_token();
- if (error_set)
- return;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ if (!previous.is_identifier()) {
+ ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
+ }
+ IdentifierNode *identifier = alloc_node<IdentifierNode>();
+ identifier->name = previous.get_identifier();
- if (current_level.indent > indent_level.back()->get().indent) {
- p_class->end_line = tokenizer->get_token_line();
- return; //go back a level
+ if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
+ const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
+ switch (declaration.type) {
+ case SuiteNode::Local::CONSTANT:
+ identifier->source = IdentifierNode::LOCAL_CONSTANT;
+ identifier->constant_source = declaration.constant;
+ declaration.constant->usages++;
+ break;
+ case SuiteNode::Local::VARIABLE:
+ identifier->source = IdentifierNode::LOCAL_VARIABLE;
+ identifier->variable_source = declaration.variable;
+ declaration.variable->usages++;
+ break;
+ case SuiteNode::Local::PARAMETER:
+ identifier->source = IdentifierNode::FUNCTION_PARAMETER;
+ identifier->parameter_source = declaration.parameter;
+ declaration.parameter->usages++;
+ break;
+ case SuiteNode::Local::FOR_VARIABLE:
+ identifier->source = IdentifierNode::LOCAL_ITERATOR;
+ identifier->bind_source = declaration.bind;
+ declaration.bind->usages++;
+ break;
+ case SuiteNode::Local::PATTERN_BIND:
+ identifier->source = IdentifierNode::LOCAL_BIND;
+ identifier->bind_source = declaration.bind;
+ declaration.bind->usages++;
+ break;
+ case SuiteNode::Local::UNDEFINED:
+ ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
}
+ }
- switch (token) {
-
- case GDScriptTokenizer::TK_CURSOR: {
- tokenizer->advance();
- } break;
- case GDScriptTokenizer::TK_EOF: {
- p_class->end_line = tokenizer->get_token_line();
- return; // End of file!
- } break;
- case GDScriptTokenizer::TK_ERROR: {
- return; // Go back.
- } break;
- case GDScriptTokenizer::TK_NEWLINE: {
- if (!_parse_newline()) {
- if (!error_set) {
- p_class->end_line = tokenizer->get_token_line();
- }
- return;
- }
- } break;
- case GDScriptTokenizer::TK_PR_EXTENDS: {
-
- _mark_line_as_safe(tokenizer->get_token_line());
- _parse_extends(p_class);
- if (error_set)
- return;
- if (!_end_statement()) {
- _set_error("Expected end of statement after \"extends\".");
- return;
- }
-
- } break;
- case GDScriptTokenizer::TK_PR_CLASS_NAME: {
-
- _mark_line_as_safe(tokenizer->get_token_line());
- if (p_class->owner) {
- _set_error("\"class_name\" is only valid for the main class namespace.");
- return;
- }
- if (self_path.begins_with("res://") && self_path.find("::") != -1) {
- _set_error("\"class_name\" isn't allowed in built-in scripts.");
- return;
- }
- if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) {
-
- _set_error("\"class_name\" syntax: \"class_name <UniqueName>\"");
- return;
- }
- if (p_class->classname_used) {
- _set_error("\"class_name\" can only be present once per script.");
- return;
- }
-
- p_class->classname_used = true;
-
- p_class->name = tokenizer->get_token_identifier(1);
-
- if (self_path != String() && ScriptServer::is_global_class(p_class->name) && ScriptServer::get_global_class_path(p_class->name) != self_path) {
- _set_error("Unique global class \"" + p_class->name + "\" already exists at path: " + ScriptServer::get_global_class_path(p_class->name));
- return;
- }
-
- if (ClassDB::class_exists(p_class->name)) {
- _set_error("The class \"" + p_class->name + "\" shadows a native class.");
- return;
- }
-
- if (p_class->classname_used && ProjectSettings::get_singleton()->has_setting("autoload/" + p_class->name)) {
- const String autoload_path = ProjectSettings::get_singleton()->get_setting("autoload/" + p_class->name);
- if (autoload_path.begins_with("*")) {
- // It's a singleton, and not just a regular AutoLoad script.
- _set_error("The class \"" + p_class->name + "\" conflicts with the AutoLoad singleton of the same name, and is therefore redundant. Remove the class_name declaration to fix this error.");
- }
- return;
- }
-
- tokenizer->advance(2);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
-
- if ((tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING)) {
-#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
- Variant constant = tokenizer->get_token_constant();
- String icon_path = constant.operator String();
-
- String abs_icon_path = icon_path.is_rel_path() ? self_path.get_base_dir().plus_file(icon_path).simplify_path() : icon_path;
- if (!FileAccess::exists(abs_icon_path)) {
- _set_error("No class icon found at: " + abs_icon_path);
- return;
- }
-
- p_class->icon_path = icon_path;
- }
-#endif
-
- tokenizer->advance();
- } else {
- _set_error("The optional parameter after \"class_name\" must be a string constant file path to an icon.");
- return;
- }
-
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT) {
- _set_error("The class icon must be separated by a comma.");
- return;
- }
-
- } break;
- case GDScriptTokenizer::TK_PR_TOOL: {
-
- if (p_class->tool) {
-
- _set_error("The \"tool\" keyword can only be present once per script.");
- return;
- }
-
- p_class->tool = true;
- tokenizer->advance();
-
- } break;
- case GDScriptTokenizer::TK_PR_CLASS: {
- //class inside class :D
-
- StringName name;
-
- if (tokenizer->get_token(1) != GDScriptTokenizer::TK_IDENTIFIER) {
-
- _set_error("\"class\" syntax: \"class <Name>:\" or \"class <Name> extends <BaseClass>:\"");
- return;
- }
- name = tokenizer->get_token_identifier(1);
- tokenizer->advance(2);
-
- // Check if name is shadowing something else
- if (ClassDB::class_exists(name) || ClassDB::class_exists("_" + name.operator String())) {
- _set_error("The class \"" + String(name) + "\" shadows a native class.");
- return;
- }
- if (ScriptServer::is_global_class(name)) {
- _set_error("Can't override name of the unique global class \"" + name + "\". It already exists at: " + ScriptServer::get_global_class_path(p_class->name));
- return;
- }
- ClassNode *outer_class = p_class;
- while (outer_class) {
- for (int i = 0; i < outer_class->subclasses.size(); i++) {
- if (outer_class->subclasses[i]->name == name) {
- _set_error("Another class named \"" + String(name) + "\" already exists in this scope (at line " + itos(outer_class->subclasses[i]->line) + ").");
- return;
- }
- }
- if (outer_class->constant_expressions.has(name)) {
- _set_error("A constant named \"" + String(name) + "\" already exists in the outer class scope (at line" + itos(outer_class->constant_expressions[name].expression->line) + ").");
- return;
- }
- for (int i = 0; i < outer_class->variables.size(); i++) {
- if (outer_class->variables[i].identifier == name) {
- _set_error("A variable named \"" + String(name) + "\" already exists in the outer class scope (at line " + itos(outer_class->variables[i].line) + ").");
- return;
- }
- }
-
- outer_class = outer_class->owner;
- }
-
- ClassNode *newclass = alloc_node<ClassNode>();
- newclass->initializer = alloc_node<BlockNode>();
- newclass->initializer->parent_class = newclass;
- newclass->ready = alloc_node<BlockNode>();
- newclass->ready->parent_class = newclass;
- newclass->name = name;
- newclass->owner = p_class;
-
- p_class->subclasses.push_back(newclass);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_EXTENDS) {
-
- _parse_extends(newclass);
- if (error_set)
- return;
- }
-
- if (!_enter_indent_block()) {
-
- _set_error("Indented block expected.");
- return;
- }
- current_class = newclass;
- _parse_class(newclass);
- current_class = p_class;
-
- } break;
- /* this is for functions....
- case GDScriptTokenizer::TK_CF_PASS: {
-
- tokenizer->advance(1);
- } break;
- */
- case GDScriptTokenizer::TK_PR_STATIC: {
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
-
- _set_error("Expected \"func\".");
- return;
- }
-
- [[fallthrough]];
- }
- case GDScriptTokenizer::TK_PR_FUNCTION: {
-
- bool _static = false;
- pending_newline = -1;
-
- if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_STATIC) {
-
- _static = true;
- }
-
- tokenizer->advance();
- StringName name;
-
- if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC, name)) {
- }
-
- if (name == StringName()) {
-
- _set_error("Expected an identifier after \"func\" (syntax: \"func <identifier>([arguments]):\").");
- return;
- }
-
- for (int i = 0; i < p_class->functions.size(); i++) {
- if (p_class->functions[i]->name == name) {
- _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->functions[i]->line) + ").");
- }
- }
- for (int i = 0; i < p_class->static_functions.size(); i++) {
- if (p_class->static_functions[i]->name == name) {
- _set_error("The function \"" + String(name) + "\" already exists in this class (at line " + itos(p_class->static_functions[i]->line) + ").");
- }
- }
-
-#ifdef DEBUG_ENABLED
- if (p_class->constant_expressions.has(name)) {
- _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name);
- }
- for (int i = 0; i < p_class->variables.size(); i++) {
- if (p_class->variables[i].identifier == name) {
- _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_VARIABLE, -1, name);
- }
- }
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- if (p_class->subclasses[i]->name == name) {
- _add_warning(GDScriptWarning::FUNCTION_CONFLICTS_CONSTANT, -1, name);
- }
- }
-#endif // DEBUG_ENABLED
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
-
- _set_error("Expected \"(\" after the identifier (syntax: \"func <identifier>([arguments]):\" ).");
- return;
- }
-
- tokenizer->advance();
-
- Vector<StringName> arguments;
- Vector<DataType> argument_types;
- Vector<Node *> default_values;
-#ifdef DEBUG_ENABLED
- Vector<int> arguments_usage;
-#endif // DEBUG_ENABLED
-
- int fnline = tokenizer->get_token_line();
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- //has arguments
- bool defaulting = false;
- while (true) {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- continue;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_VAR) {
-
- tokenizer->advance(); //var before the identifier is allowed
- }
-
- if (!tokenizer->is_token_literal(0, true)) {
-
- _set_error("Expected an identifier for an argument.");
- return;
- }
-
- StringName argname = tokenizer->get_token_identifier();
- for (int i = 0; i < arguments.size(); i++) {
- if (arguments[i] == argname) {
- _set_error("The argument name \"" + String(argname) + "\" is defined multiple times.");
- return;
- }
- }
- arguments.push_back(argname);
-#ifdef DEBUG_ENABLED
- arguments_usage.push_back(0);
-#endif // DEBUG_ENABLED
-
- tokenizer->advance();
-
- DataType argtype;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- argtype.infer_type = true;
- tokenizer->advance();
- } else if (!_parse_type(argtype)) {
- _set_error("Expected a type for an argument.");
- return;
- }
- }
- argument_types.push_back(argtype);
-
- if (defaulting && tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) {
-
- _set_error("Default parameter expected.");
- return;
- }
-
- //tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) {
- defaulting = true;
- tokenizer->advance(1);
- Node *defval = _parse_and_reduce_expression(p_class, _static);
- if (!defval || error_set)
- return;
-
- OperatorNode *on = alloc_node<OperatorNode>();
- on->op = OperatorNode::OP_ASSIGN;
- on->line = fnline;
-
- IdentifierNode *in = alloc_node<IdentifierNode>();
- in->name = argname;
- in->line = fnline;
-
- on->arguments.push_back(in);
- on->arguments.push_back(defval);
- /* no ..
- if (defval->type!=Node::TYPE_CONSTANT) {
-
- _set_error("default argument must be constant");
- }
- */
- default_values.push_back(on);
- }
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- continue;
- } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
-
- _set_error("Expected \",\" or \")\".");
- return;
- }
-
- break;
- }
- }
-
- tokenizer->advance();
-
- BlockNode *block = alloc_node<BlockNode>();
- block->parent_class = p_class;
-
- FunctionNode *function = alloc_node<FunctionNode>();
- function->name = name;
- function->arguments = arguments;
- function->argument_types = argument_types;
- function->default_values = default_values;
- function->_static = _static;
- function->line = fnline;
-#ifdef DEBUG_ENABLED
- function->arguments_usage = arguments_usage;
-#endif // DEBUG_ENABLED
- function->rpc_mode = rpc_mode;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
-
- if (name == "_init") {
-
- if (_static) {
- _set_error("The constructor cannot be static.");
- return;
- }
-
- if (p_class->extends_used) {
-
- OperatorNode *cparent = alloc_node<OperatorNode>();
- cparent->op = OperatorNode::OP_PARENT_CALL;
- block->statements.push_back(cparent);
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = "_init";
- cparent->arguments.push_back(id);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) {
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- _set_error("Expected \"(\" for parent constructor arguments.");
- return;
- }
- tokenizer->advance();
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- //has arguments
- parenthesis++;
- while (true) {
-
- current_function = function;
- Node *arg = _parse_and_reduce_expression(p_class, _static);
- current_function = nullptr;
- cparent->arguments.push_back(arg);
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- continue;
- } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
-
- _set_error("Expected \",\" or \")\".");
- return;
- }
-
- break;
- }
- parenthesis--;
- }
-
- tokenizer->advance();
- }
- } else {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PERIOD) {
-
- _set_error("Parent constructor call found for a class without inheritance.");
- return;
- }
- }
- }
-
- DataType return_type;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_FORWARD_ARROW) {
-
- if (!_parse_type(return_type, true)) {
- _set_error("Expected a return type for the function.");
- return;
- }
- }
-
- if (!_enter_indent_block(block)) {
-
- _set_error(vformat("Indented block expected after declaration of \"%s\" function.", function->name));
- return;
- }
-
- function->return_type = return_type;
-
- if (_static)
- p_class->static_functions.push_back(function);
- else
- p_class->functions.push_back(function);
-
- current_function = function;
- function->body = block;
- current_block = block;
- _parse_block(block, _static);
- current_block = nullptr;
-
- //arguments
- } break;
- case GDScriptTokenizer::TK_PR_SIGNAL: {
- tokenizer->advance();
-
- if (!tokenizer->is_token_literal()) {
- _set_error("Expected an identifier after \"signal\".");
- return;
- }
-
- ClassNode::Signal sig;
- sig.name = tokenizer->get_token_identifier();
- sig.emissions = 0;
- sig.line = tokenizer->get_token_line();
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
- tokenizer->advance();
- while (true) {
- if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- continue;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- tokenizer->advance();
- break;
- }
-
- if (!tokenizer->is_token_literal(0, true)) {
- _set_error("Expected an identifier in a \"signal\" argument.");
- return;
- }
-
- sig.arguments.push_back(tokenizer->get_token_identifier());
- tokenizer->advance();
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
- tokenizer->advance();
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance();
- } else if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \",\" or \")\" after a \"signal\" parameter identifier.");
- return;
- }
- }
- }
-
- p_class->_signals.push_back(sig);
-
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"signal\").");
- return;
- }
- } break;
- case GDScriptTokenizer::TK_PR_EXPORT: {
-
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_OPEN) {
-
-#define _ADVANCE_AND_CONSUME_NEWLINES \
- do { \
- tokenizer->advance(); \
- } while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE)
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- parenthesis++;
-
- String hint_prefix = "";
- bool is_arrayed = false;
-
- while (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE &&
- tokenizer->get_token_type() == Variant::ARRAY &&
- tokenizer->get_token(1) == GDScriptTokenizer::TK_COMMA) {
- tokenizer->advance(); // Array
- tokenizer->advance(); // Comma
- if (is_arrayed) {
- hint_prefix += itos(Variant::ARRAY) + ":";
- } else {
- is_arrayed = true;
- }
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_TYPE) {
-
- Variant::Type type = tokenizer->get_token_type();
- if (type == Variant::NIL) {
- _set_error("Can't export null type.");
- return;
- }
- if (type == Variant::OBJECT) {
- _set_error("Can't export raw object type.");
- return;
- }
- current_export.type = type;
- current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- // hint expected next!
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- switch (type) {
-
- case Variant::INT: {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected \",\" in the bit flags hint.");
- return;
- }
-
- current_export.hint = PROPERTY_HINT_FLAGS;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- bool first = true;
- while (true) {
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
- current_export = PropertyInfo();
- _set_error("Expected a string constant in the named bit flags hint.");
- return;
- }
-
- String c = tokenizer->get_token_constant();
- if (!first)
- current_export.hint_string += ",";
- else
- first = false;
-
- current_export.hint_string += c.xml_escape();
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- current_export = PropertyInfo();
- _set_error("Expected \")\" or \",\" in the named bit flags hint.");
- return;
- }
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_RENDER") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the 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") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the 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") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the 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") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the 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;
- bool first = true;
- while (true) {
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
-
- current_export = PropertyInfo();
- _set_error("Expected a string constant in the enumeration hint.");
- return;
- }
-
- String c = tokenizer->get_token_constant();
- if (!first)
- current_export.hint_string += ",";
- else
- first = false;
-
- current_export.hint_string += c.xml_escape();
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- current_export = PropertyInfo();
- _set_error("Expected \")\" or \",\" in the enumeration hint.");
- return;
- }
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- break;
- }
-
- [[fallthrough]];
- }
- case Variant::FLOAT: {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EASE") {
- current_export.hint = PROPERTY_HINT_EXP_EASING;
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the hint.");
- return;
- }
- break;
- }
-
- // range
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EXP") {
-
- current_export.hint = PROPERTY_HINT_EXP_RANGE;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
- else if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- _set_error("Expected \")\" or \",\" in the exponential range hint.");
- return;
- }
- _ADVANCE_AND_CONSUME_NEWLINES;
- } else
- current_export.hint = PROPERTY_HINT_RANGE;
-
- float sign = 1.0;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) {
- sign = -1;
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
-
- current_export = PropertyInfo();
- _set_error("Expected a range in the numeric hint.");
- return;
- }
-
- current_export.hint_string = rtos(sign * double(tokenizer->get_token_constant()));
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- current_export.hint_string = "0," + current_export.hint_string;
- break;
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
-
- current_export = PropertyInfo();
- _set_error("Expected \",\" or \")\" in the numeric range hint.");
- return;
- }
-
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- sign = 1.0;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) {
- sign = -1;
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
-
- current_export = PropertyInfo();
- _set_error("Expected a number as upper bound in the numeric range hint.");
- return;
- }
-
- current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant()));
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
-
- current_export = PropertyInfo();
- _set_error("Expected \",\" or \")\" in the numeric range hint.");
- return;
- }
-
- _ADVANCE_AND_CONSUME_NEWLINES;
- sign = 1.0;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_SUB) {
- sign = -1;
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
-
- current_export = PropertyInfo();
- _set_error("Expected a number as step in the numeric range hint.");
- return;
- }
-
- current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant()));
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- } break;
- case Variant::STRING: {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) {
- //enumeration
- current_export.hint = PROPERTY_HINT_ENUM;
- bool first = true;
- while (true) {
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
-
- current_export = PropertyInfo();
- _set_error("Expected a string constant in the enumeration hint.");
- return;
- }
-
- String c = tokenizer->get_token_constant();
- if (!first)
- current_export.hint_string += ",";
- else
- first = false;
-
- current_export.hint_string += c.xml_escape();
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- current_export = PropertyInfo();
- _set_error("Expected \")\" or \",\" in the enumeration hint.");
- return;
- }
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "DIR") {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- current_export.hint = PROPERTY_HINT_DIR;
- else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) {
- _set_error("Expected \"GLOBAL\" after comma in the directory hint.");
- return;
- }
- if (!p_class->tool) {
- _set_error("Global filesystem hints may only be used in tool scripts.");
- return;
- }
- current_export.hint = PROPERTY_HINT_GLOBAL_DIR;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the hint.");
- return;
- }
- } else {
- _set_error("Expected \")\" or \",\" in the hint.");
- return;
- }
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FILE") {
-
- current_export.hint = PROPERTY_HINT_FILE;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
-
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "GLOBAL") {
-
- if (!p_class->tool) {
- _set_error("Global filesystem hints may only be used in tool scripts.");
- return;
- }
- current_export.hint = PROPERTY_HINT_GLOBAL_FILE;
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE)
- break;
- else if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA)
- _ADVANCE_AND_CONSUME_NEWLINES;
- else {
- _set_error("Expected \")\" or \",\" in the hint.");
- return;
- }
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
-
- if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE)
- _set_error("Expected string constant with filter.");
- else
- _set_error("Expected \"GLOBAL\" or string constant with filter.");
- return;
- }
- current_export.hint_string = tokenizer->get_token_constant();
- _ADVANCE_AND_CONSUME_NEWLINES;
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the hint.");
- return;
- }
- break;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "MULTILINE") {
-
- current_export.hint = PROPERTY_HINT_MULTILINE_TEXT;
- _ADVANCE_AND_CONSUME_NEWLINES;
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
- _set_error("Expected \")\" in the hint.");
- return;
- }
- break;
- }
- } break;
- case Variant::COLOR: {
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_IDENTIFIER) {
-
- current_export = PropertyInfo();
- _set_error("Color type hint expects RGB or RGBA as hints.");
- return;
- }
-
- String identifier = tokenizer->get_token_identifier();
- if (identifier == "RGB") {
- current_export.hint = PROPERTY_HINT_COLOR_NO_ALPHA;
- } else if (identifier == "RGBA") {
- //none
- } else {
- current_export = PropertyInfo();
- _set_error("Color type hint expects RGB or RGBA as hints.");
- return;
- }
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- } break;
- default: {
-
- current_export = PropertyInfo();
- _set_error("Type \"" + Variant::get_type_name(type) + "\" can't take hints.");
- return;
- } break;
- }
- }
-
- } else {
-
- parenthesis++;
- Node *subexpr = _parse_and_reduce_expression(p_class, true, true);
- if (!subexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
- parenthesis--;
-
- if (subexpr->type != Node::TYPE_CONSTANT) {
- current_export = PropertyInfo();
- _set_error("Expected a constant expression.");
- }
-
- Variant constant = static_cast<ConstantNode *>(subexpr)->value;
-
- if (constant.get_type() == Variant::OBJECT) {
- GDScriptNativeClass *native_class = Object::cast_to<GDScriptNativeClass>(constant);
-
- if (native_class && ClassDB::is_parent_class(native_class->get_name(), "Resource")) {
- current_export.type = Variant::OBJECT;
- current_export.hint = PROPERTY_HINT_RESOURCE_TYPE;
- current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
-
- current_export.hint_string = native_class->get_name();
- current_export.class_name = native_class->get_name();
-
- } else {
- current_export = PropertyInfo();
- _set_error("The export hint isn't a resource type.");
- }
- } else if (constant.get_type() == Variant::DICTIONARY) {
- // Enumeration
- bool is_flags = false;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- _ADVANCE_AND_CONSUME_NEWLINES;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") {
- is_flags = true;
- _ADVANCE_AND_CONSUME_NEWLINES;
- } else {
- current_export = PropertyInfo();
- _set_error("Expected \"FLAGS\" after comma.");
- }
- }
-
- current_export.type = Variant::INT;
- current_export.hint = is_flags ? PROPERTY_HINT_FLAGS : PROPERTY_HINT_ENUM;
- current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- Dictionary enum_values = constant;
-
- List<Variant> keys;
- enum_values.get_key_list(&keys);
-
- bool first = true;
- for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
- if (enum_values[E->get()].get_type() == Variant::INT) {
- if (!first)
- current_export.hint_string += ",";
- else
- first = false;
-
- current_export.hint_string += E->get().operator String().camelcase_to_underscore(true).capitalize().xml_escape();
- if (!is_flags) {
- current_export.hint_string += ":";
- current_export.hint_string += enum_values[E->get()].operator String().xml_escape();
- }
- }
- }
- } else {
- current_export = PropertyInfo();
- _set_error("Expected type for export.");
- return;
- }
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
-
- current_export = PropertyInfo();
- _set_error("Expected \")\" or \",\" after the export hint.");
- return;
- }
-
- tokenizer->advance();
- parenthesis--;
-
- if (is_arrayed) {
- hint_prefix += itos(current_export.type);
- if (current_export.hint) {
- hint_prefix += "/" + itos(current_export.hint);
- }
- current_export.hint_string = hint_prefix + ":" + current_export.hint_string;
- current_export.hint = PROPERTY_HINT_TYPE_STRING;
- current_export.type = Variant::ARRAY;
- }
-#undef _ADVANCE_AND_CONSUME_NEWLINES
- }
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPET && tokenizer->get_token() != GDScriptTokenizer::TK_PR_REMOTESYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_MASTERSYNC && tokenizer->get_token() != GDScriptTokenizer::TK_PR_PUPPETSYNC) {
+ return identifier;
+}
- current_export = PropertyInfo();
- _set_error("Expected \"var\", \"onready\", \"remote\", \"master\", \"puppet\", \"remotesync\", \"mastersync\", \"puppetsync\".");
- return;
- }
+GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
+ return static_cast<LiteralNode *>(parse_literal(nullptr, false));
+}
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_ONREADY: {
+GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ if (previous.type != GDScriptTokenizer::Token::LITERAL) {
+ push_error("Parser bug: parsing literal node without literal token.");
+ ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
+ }
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected \"var\".");
- return;
- }
+ LiteralNode *literal = alloc_node<LiteralNode>();
+ literal->value = previous.literal;
+ return literal;
+}
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_REMOTE: {
+GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ if (current_function && current_function->is_static) {
+ push_error(R"(Cannot use "self" inside a static function.)");
+ }
+ SelfNode *self = alloc_node<SelfNode>();
+ self->current_class = current_class;
+ return self;
+}
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected \"var\".");
- return;
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ GDScriptTokenizer::Token::Type op_type = previous.type;
+ LiteralNode *constant = alloc_node<LiteralNode>();
- } else {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
- }
- rpc_mode = MultiplayerAPI::RPC_MODE_REMOTE;
-
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_MASTER: {
-
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected \"var\".");
- return;
- }
+ switch (op_type) {
+ case GDScriptTokenizer::Token::CONST_PI:
+ constant->value = Math_PI;
+ break;
+ case GDScriptTokenizer::Token::CONST_TAU:
+ constant->value = Math_TAU;
+ break;
+ case GDScriptTokenizer::Token::CONST_INF:
+ constant->value = Math_INF;
+ break;
+ case GDScriptTokenizer::Token::CONST_NAN:
+ constant->value = Math_NAN;
+ break;
+ default:
+ return nullptr; // Unreachable.
+ }
- } else {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
- }
+ return constant;
+}
- rpc_mode = MultiplayerAPI::RPC_MODE_MASTER;
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_PUPPET: {
-
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR) {
- _set_error("Expected \"var\".");
- return;
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ GDScriptTokenizer::Token::Type op_type = previous.type;
+ UnaryOpNode *operation = alloc_node<UnaryOpNode>();
- } else {
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
- }
+ switch (op_type) {
+ case GDScriptTokenizer::Token::MINUS:
+ operation->operation = UnaryOpNode::OP_NEGATIVE;
+ operation->variant_op = Variant::OP_NEGATE;
+ operation->operand = parse_precedence(PREC_SIGN, false);
+ break;
+ case GDScriptTokenizer::Token::PLUS:
+ operation->operation = UnaryOpNode::OP_POSITIVE;
+ operation->variant_op = Variant::OP_POSITIVE;
+ operation->operand = parse_precedence(PREC_SIGN, false);
+ break;
+ case GDScriptTokenizer::Token::TILDE:
+ operation->operation = UnaryOpNode::OP_COMPLEMENT;
+ operation->variant_op = Variant::OP_BIT_NEGATE;
+ operation->operand = parse_precedence(PREC_BIT_NOT, false);
+ break;
+ case GDScriptTokenizer::Token::NOT:
+ case GDScriptTokenizer::Token::BANG:
+ operation->operation = UnaryOpNode::OP_LOGIC_NOT;
+ operation->variant_op = Variant::OP_NOT;
+ operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
+ break;
+ default:
+ return nullptr; // Unreachable.
+ }
- rpc_mode = MultiplayerAPI::RPC_MODE_PUPPET;
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_REMOTESYNC: {
-
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- if (current_export.type)
- _set_error("Expected \"var\".");
- else
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
+ return operation;
+}
- rpc_mode = MultiplayerAPI::RPC_MODE_REMOTESYNC;
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_MASTERSYNC: {
-
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- if (current_export.type)
- _set_error("Expected \"var\".");
- else
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ GDScriptTokenizer::Token op = previous;
+ BinaryOpNode *operation = alloc_node<BinaryOpNode>();
- rpc_mode = MultiplayerAPI::RPC_MODE_MASTERSYNC;
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_PUPPETSYNC: {
-
- //may be fallthrough from export, ignore if so
- tokenizer->advance();
- if (tokenizer->get_token() != GDScriptTokenizer::TK_PR_VAR && tokenizer->get_token() != GDScriptTokenizer::TK_PR_FUNCTION) {
- if (current_export.type)
- _set_error("Expected \"var\".");
- else
- _set_error("Expected \"var\" or \"func\".");
- return;
- }
+ Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
+ operation->left_operand = p_previous_operand;
+ operation->right_operand = parse_precedence(precedence, false);
- rpc_mode = MultiplayerAPI::RPC_MODE_PUPPETSYNC;
- continue;
- } break;
- case GDScriptTokenizer::TK_PR_VAR: {
- // variable declaration and (eventual) initialization
+ if (operation->right_operand == nullptr) {
+ push_error(vformat(R"(Expected expression after "%s" operator.")", op.get_name()));
+ }
- ClassNode::Member member;
+ // TODO: Also for unary, ternary, and assignment.
+ switch (op.type) {
+ case GDScriptTokenizer::Token::PLUS:
+ operation->operation = BinaryOpNode::OP_ADDITION;
+ operation->variant_op = Variant::OP_ADD;
+ break;
+ case GDScriptTokenizer::Token::MINUS:
+ operation->operation = BinaryOpNode::OP_SUBTRACTION;
+ operation->variant_op = Variant::OP_SUBTRACT;
+ break;
+ case GDScriptTokenizer::Token::STAR:
+ operation->operation = BinaryOpNode::OP_MULTIPLICATION;
+ operation->variant_op = Variant::OP_MULTIPLY;
+ break;
+ case GDScriptTokenizer::Token::SLASH:
+ operation->operation = BinaryOpNode::OP_DIVISION;
+ operation->variant_op = Variant::OP_DIVIDE;
+ break;
+ case GDScriptTokenizer::Token::PERCENT:
+ operation->operation = BinaryOpNode::OP_MODULO;
+ operation->variant_op = Variant::OP_MODULE;
+ break;
+ case GDScriptTokenizer::Token::LESS_LESS:
+ operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
+ operation->variant_op = Variant::OP_SHIFT_LEFT;
+ break;
+ case GDScriptTokenizer::Token::GREATER_GREATER:
+ operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
+ operation->variant_op = Variant::OP_SHIFT_RIGHT;
+ break;
+ case GDScriptTokenizer::Token::AMPERSAND:
+ operation->operation = BinaryOpNode::OP_BIT_AND;
+ operation->variant_op = Variant::OP_BIT_AND;
+ break;
+ case GDScriptTokenizer::Token::PIPE:
+ operation->operation = BinaryOpNode::OP_BIT_OR;
+ operation->variant_op = Variant::OP_BIT_OR;
+ break;
+ case GDScriptTokenizer::Token::CARET:
+ operation->operation = BinaryOpNode::OP_BIT_XOR;
+ operation->variant_op = Variant::OP_BIT_XOR;
+ break;
+ case GDScriptTokenizer::Token::AND:
+ case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
+ operation->operation = BinaryOpNode::OP_LOGIC_AND;
+ operation->variant_op = Variant::OP_AND;
+ break;
+ case GDScriptTokenizer::Token::OR:
+ case GDScriptTokenizer::Token::PIPE_PIPE:
+ operation->operation = BinaryOpNode::OP_LOGIC_OR;
+ operation->variant_op = Variant::OP_OR;
+ break;
+ case GDScriptTokenizer::Token::IS:
+ operation->operation = BinaryOpNode::OP_TYPE_TEST;
+ break;
+ case GDScriptTokenizer::Token::IN:
+ operation->operation = BinaryOpNode::OP_CONTENT_TEST;
+ operation->variant_op = Variant::OP_IN;
+ break;
+ case GDScriptTokenizer::Token::EQUAL_EQUAL:
+ operation->operation = BinaryOpNode::OP_COMP_EQUAL;
+ operation->variant_op = Variant::OP_EQUAL;
+ break;
+ case GDScriptTokenizer::Token::BANG_EQUAL:
+ operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
+ operation->variant_op = Variant::OP_NOT_EQUAL;
+ break;
+ case GDScriptTokenizer::Token::LESS:
+ operation->operation = BinaryOpNode::OP_COMP_LESS;
+ operation->variant_op = Variant::OP_LESS;
+ break;
+ case GDScriptTokenizer::Token::LESS_EQUAL:
+ operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
+ operation->variant_op = Variant::OP_LESS_EQUAL;
+ break;
+ case GDScriptTokenizer::Token::GREATER:
+ operation->operation = BinaryOpNode::OP_COMP_GREATER;
+ operation->variant_op = Variant::OP_GREATER;
+ break;
+ case GDScriptTokenizer::Token::GREATER_EQUAL:
+ operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
+ operation->variant_op = Variant::OP_GREATER_EQUAL;
+ break;
+ default:
+ return nullptr; // Unreachable.
+ }
- bool autoexport = tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_EXPORT;
- if (current_export.type != Variant::NIL) {
- member._export = current_export;
- current_export = PropertyInfo();
- }
+ return operation;
+}
- bool onready = tokenizer->get_token(-1) == GDScriptTokenizer::TK_PR_ONREADY;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ // Only one ternary operation exists, so no abstraction here.
+ TernaryOpNode *operation = alloc_node<TernaryOpNode>();
+ operation->true_expr = p_previous_operand;
- tokenizer->advance();
- if (!tokenizer->is_token_literal(0, true)) {
+ operation->condition = parse_precedence(PREC_TERNARY, false);
- _set_error("Expected an identifier for the member variable name.");
- return;
- }
+ if (operation->condition == nullptr) {
+ push_error(R"(Expected expression as ternary condition after "if".)");
+ }
- member.identifier = tokenizer->get_token_literal();
- member.expression = nullptr;
- member._export.name = member.identifier;
- member.line = tokenizer->get_token_line();
- member.usages = 0;
- member.rpc_mode = rpc_mode;
-
- if (current_class->constant_expressions.has(member.identifier)) {
- _set_error("A constant named \"" + String(member.identifier) + "\" already exists in this class (at line: " +
- itos(current_class->constant_expressions[member.identifier].expression->line) + ").");
- return;
- }
+ consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
- for (int i = 0; i < current_class->variables.size(); i++) {
- if (current_class->variables[i].identifier == member.identifier) {
- _set_error("Variable \"" + String(member.identifier) + "\" already exists in this class (at line: " +
- itos(current_class->variables[i].line) + ").");
- return;
- }
- }
+ operation->false_expr = parse_precedence(PREC_TERNARY, false);
- for (int i = 0; i < current_class->subclasses.size(); i++) {
- if (current_class->subclasses[i]->name == member.identifier) {
- _set_error("A class named \"" + String(member.identifier) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
- return;
- }
- }
-#ifdef DEBUG_ENABLED
- for (int i = 0; i < current_class->functions.size(); i++) {
- if (current_class->functions[i]->name == member.identifier) {
- _add_warning(GDScriptWarning::VARIABLE_CONFLICTS_FUNCTION, member.line, member.identifier);
- break;
- }
- }
- for (int i = 0; i < current_class->static_functions.size(); i++) {
- if (current_class->static_functions[i]->name == member.identifier) {
- _add_warning(GDScriptWarning::VARIABLE_CONFLICTS_FUNCTION, member.line, member.identifier);
- break;
- }
- }
-#endif // DEBUG_ENABLED
- tokenizer->advance();
+ return operation;
+}
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ if (!p_can_assign) {
+ push_error("Assignment is not allowed inside an expression.");
+ return parse_expression(false); // Return the following expression.
+ }
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- member.data_type = DataType();
#ifdef DEBUG_ENABLED
- member.data_type.infer_type = true;
-#endif
- tokenizer->advance();
- } else if (!_parse_type(member.data_type)) {
- _set_error("Expected a type for the class variable.");
- return;
- }
- }
-
- if (autoexport && member.data_type.has_type) {
- if (member.data_type.kind == DataType::BUILTIN) {
- member._export.type = member.data_type.builtin_type;
- } else if (member.data_type.kind == DataType::NATIVE) {
- if (ClassDB::is_parent_class(member.data_type.native_type, "Resource")) {
- member._export.type = Variant::OBJECT;
- member._export.hint = PROPERTY_HINT_RESOURCE_TYPE;
- member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- member._export.hint_string = member.data_type.native_type;
- member._export.class_name = member.data_type.native_type;
- } else {
- _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line);
- return;
- }
-
- } else {
- _set_error("Invalid export type. Only built-in and native resource types can be exported.", member.line);
- return;
- }
- }
-
-#ifdef TOOLS_ENABLED
- Callable::CallError ce;
- member.default_value = Variant::construct(member._export.type, nullptr, 0, ce);
+ VariableNode *source_variable = nullptr;
#endif
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) {
-
+ switch (p_previous_operand->type) {
+ case Node::IDENTIFIER: {
#ifdef DEBUG_ENABLED
- int line = tokenizer->get_token_line();
+ // Get source to store assignment count.
+ // Also remove one usage since assignment isn't usage.
+ IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
+ switch (id->source) {
+ case IdentifierNode::LOCAL_VARIABLE:
+
+ source_variable = id->variable_source;
+ id->variable_source->usages--;
+ break;
+ case IdentifierNode::LOCAL_CONSTANT:
+ id->constant_source->usages--;
+ break;
+ case IdentifierNode::FUNCTION_PARAMETER:
+ id->parameter_source->usages--;
+ break;
+ case IdentifierNode::LOCAL_ITERATOR:
+ case IdentifierNode::LOCAL_BIND:
+ id->bind_source->usages--;
+ break;
+ default:
+ break;
+ }
#endif
- tokenizer->advance();
-
- Node *subexpr = _parse_and_reduce_expression(p_class, false, autoexport || member._export.type != Variant::NIL);
- if (!subexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- //discourage common error
- if (!onready && subexpr->type == Node::TYPE_OPERATOR) {
-
- OperatorNode *op = static_cast<OperatorNode *>(subexpr);
- if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_SELF && op->arguments[1]->type == Node::TYPE_IDENTIFIER) {
- IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]);
- if (id->name == "get_node") {
-
- _set_error("Use \"onready var " + String(member.identifier) + " = get_node(...)\" instead.");
- return;
- }
- }
- }
-
- member.expression = subexpr;
-
- if (autoexport && !member.data_type.has_type) {
-
- if (subexpr->type != Node::TYPE_CONSTANT) {
-
- _set_error("Type-less export needs a constant expression assigned to infer type.");
- return;
- }
-
- ConstantNode *cn = static_cast<ConstantNode *>(subexpr);
- if (cn->value.get_type() == Variant::NIL) {
-
- _set_error("Can't accept a null constant expression for inferring export type.");
- return;
- }
-
- if (!_reduce_export_var_type(cn->value, member.line)) return;
+ } break;
+ case Node::SUBSCRIPT:
+ // Okay.
+ break;
+ default:
+ push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
+ return parse_expression(false); // Return the following expression.
+ }
- member._export.type = cn->value.get_type();
- member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- if (cn->value.get_type() == Variant::OBJECT) {
- Object *obj = cn->value;
- Resource *res = Object::cast_to<Resource>(obj);
- if (res == nullptr) {
- _set_error("The exported constant isn't a type or resource.");
- return;
- }
- member._export.hint = PROPERTY_HINT_RESOURCE_TYPE;
- member._export.hint_string = res->get_class();
- }
- }
-#ifdef TOOLS_ENABLED
- if (subexpr->type == Node::TYPE_CONSTANT && (member._export.type != Variant::NIL || member.data_type.has_type)) {
-
- ConstantNode *cn = static_cast<ConstantNode *>(subexpr);
- if (cn->value.get_type() != Variant::NIL) {
- if (member._export.type != Variant::NIL && cn->value.get_type() != member._export.type) {
- if (Variant::can_convert(cn->value.get_type(), member._export.type)) {
- Callable::CallError err;
- const Variant *args = &cn->value;
- cn->value = Variant::construct(member._export.type, &args, 1, err);
- } else {
- _set_error("Can't convert the provided value to the export type.");
- return;
- }
- }
- member.default_value = cn->value;
- }
- }
+ AssignmentNode *assignment = alloc_node<AssignmentNode>();
+ make_completion_context(COMPLETION_ASSIGN, assignment);
+#ifdef DEBUG_ENABLED
+ bool has_operator = true;
#endif
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = member.identifier;
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_INIT_ASSIGN;
- op->arguments.push_back(id);
- op->arguments.push_back(subexpr);
-
+ switch (previous.type) {
+ case GDScriptTokenizer::Token::EQUAL:
+ assignment->operation = AssignmentNode::OP_NONE;
+ assignment->variant_op = Variant::OP_MAX;
#ifdef DEBUG_ENABLED
- NewLineNode *nl2 = alloc_node<NewLineNode>();
- nl2->line = line;
- if (onready)
- p_class->ready->statements.push_back(nl2);
- else
- p_class->initializer->statements.push_back(nl2);
+ has_operator = false;
#endif
- if (onready)
- p_class->ready->statements.push_back(op);
- else
- p_class->initializer->statements.push_back(op);
-
- member.initial_assignment = op;
-
- } else {
-
- if (autoexport && !member.data_type.has_type) {
- _set_error("Type-less export needs a constant expression assigned to infer type.");
- return;
- }
-
- Node *expr;
-
- if (member.data_type.has_type) {
- expr = _get_default_value_for_type(member.data_type);
- } else {
- DataType exported_type;
- exported_type.has_type = true;
- exported_type.kind = DataType::BUILTIN;
- exported_type.builtin_type = member._export.type;
- expr = _get_default_value_for_type(exported_type);
- }
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = member.identifier;
-
- OperatorNode *op = alloc_node<OperatorNode>();
- op->op = OperatorNode::OP_INIT_ASSIGN;
- op->arguments.push_back(id);
- op->arguments.push_back(expr);
-
- p_class->initializer->statements.push_back(op);
-
- member.initial_assignment = op;
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_PR_SETGET) {
-
- tokenizer->advance();
-
- if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
- //just comma means using only getter
- if (!tokenizer->is_token_literal()) {
- _set_error("Expected an identifier for the setter function after \"setget\".");
- }
-
- member.setter = tokenizer->get_token_literal();
-
- tokenizer->advance();
- }
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
- //there is a getter
- tokenizer->advance();
-
- if (!tokenizer->is_token_literal()) {
- _set_error("Expected an identifier for the getter function after \",\".");
- }
-
- member.getter = tokenizer->get_token_literal();
- tokenizer->advance();
- }
- }
-
- p_class->variables.push_back(member);
-
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"continue\").");
- return;
- }
- } break;
- case GDScriptTokenizer::TK_PR_CONST: {
- // constant declaration and initialization
-
- ClassNode::Constant constant;
-
- tokenizer->advance();
- if (!tokenizer->is_token_literal(0, true)) {
-
- _set_error("Expected an identifier for the constant.");
- return;
- }
-
- StringName const_id = tokenizer->get_token_literal();
- int line = tokenizer->get_token_line();
-
- if (current_class->constant_expressions.has(const_id)) {
- _set_error("Constant \"" + String(const_id) + "\" already exists in this class (at line " +
- itos(current_class->constant_expressions[const_id].expression->line) + ").");
- return;
- }
-
- for (int i = 0; i < current_class->variables.size(); i++) {
- if (current_class->variables[i].identifier == const_id) {
- _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " +
- itos(current_class->variables[i].line) + ").");
- return;
- }
- }
-
- for (int i = 0; i < current_class->subclasses.size(); i++) {
- if (current_class->subclasses[i]->name == const_id) {
- _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
- return;
- }
- }
-
- tokenizer->advance();
+ break;
+ case GDScriptTokenizer::Token::PLUS_EQUAL:
+ assignment->operation = AssignmentNode::OP_ADDITION;
+ assignment->variant_op = Variant::OP_ADD;
+ break;
+ case GDScriptTokenizer::Token::MINUS_EQUAL:
+ assignment->operation = AssignmentNode::OP_SUBTRACTION;
+ assignment->variant_op = Variant::OP_SUBTRACT;
+ break;
+ case GDScriptTokenizer::Token::STAR_EQUAL:
+ assignment->operation = AssignmentNode::OP_MULTIPLICATION;
+ assignment->variant_op = Variant::OP_MULTIPLY;
+ break;
+ case GDScriptTokenizer::Token::SLASH_EQUAL:
+ assignment->operation = AssignmentNode::OP_DIVISION;
+ assignment->variant_op = Variant::OP_DIVIDE;
+ break;
+ case GDScriptTokenizer::Token::PERCENT_EQUAL:
+ assignment->operation = AssignmentNode::OP_MODULO;
+ assignment->variant_op = Variant::OP_MODULE;
+ break;
+ case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
+ assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
+ assignment->variant_op = Variant::OP_SHIFT_LEFT;
+ break;
+ case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
+ assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
+ assignment->variant_op = Variant::OP_SHIFT_RIGHT;
+ break;
+ case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
+ assignment->operation = AssignmentNode::OP_BIT_AND;
+ assignment->variant_op = Variant::OP_BIT_AND;
+ break;
+ case GDScriptTokenizer::Token::PIPE_EQUAL:
+ assignment->operation = AssignmentNode::OP_BIT_OR;
+ assignment->variant_op = Variant::OP_BIT_OR;
+ break;
+ case GDScriptTokenizer::Token::CARET_EQUAL:
+ assignment->operation = AssignmentNode::OP_BIT_XOR;
+ assignment->variant_op = Variant::OP_BIT_XOR;
+ break;
+ default:
+ break; // Unreachable.
+ }
+ assignment->assignee = p_previous_operand;
+ assignment->assigned_value = parse_expression(false);
- if (tokenizer->get_token() == GDScriptTokenizer::TK_COLON) {
- if (tokenizer->get_token(1) == GDScriptTokenizer::TK_OP_ASSIGN) {
- constant.type = DataType();
#ifdef DEBUG_ENABLED
- constant.type.infer_type = true;
+ if (has_operator && source_variable != nullptr && source_variable->assignments == 0) {
+ push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
+ }
#endif
- tokenizer->advance();
- } else if (!_parse_type(constant.type)) {
- _set_error("Expected a type for the class constant.");
- return;
- }
- }
- if (tokenizer->get_token() != GDScriptTokenizer::TK_OP_ASSIGN) {
- _set_error("Constants must be assigned immediately.");
- return;
- }
-
- tokenizer->advance();
-
- Node *subexpr = _parse_and_reduce_expression(p_class, true, true);
- if (!subexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- if (subexpr->type != Node::TYPE_CONSTANT) {
- _set_error("Expected a constant expression.", line);
- return;
- }
- subexpr->line = line;
- constant.expression = subexpr;
-
- p_class->constant_expressions.insert(const_id, constant);
-
- if (!_end_statement()) {
- _set_error("Expected end of statement (constant).", line);
- return;
- }
-
- } break;
- case GDScriptTokenizer::TK_PR_ENUM: {
- //multiple constant declarations..
-
- int last_assign = -1; // Incremented by 1 right before the assignment.
- String enum_name;
- Dictionary enum_dict;
-
- tokenizer->advance();
- if (tokenizer->is_token_literal(0, true)) {
- enum_name = tokenizer->get_token_literal();
-
- if (current_class->constant_expressions.has(enum_name)) {
- _set_error("A constant named \"" + String(enum_name) + "\" already exists in this class (at line " +
- itos(current_class->constant_expressions[enum_name].expression->line) + ").");
- return;
- }
-
- for (int i = 0; i < current_class->variables.size(); i++) {
- if (current_class->variables[i].identifier == enum_name) {
- _set_error("A variable named \"" + String(enum_name) + "\" already exists in this class (at line " +
- itos(current_class->variables[i].line) + ").");
- return;
- }
- }
-
- for (int i = 0; i < current_class->subclasses.size(); i++) {
- if (current_class->subclasses[i]->name == enum_name) {
- _set_error("A class named \"" + String(enum_name) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
- return;
- }
- }
-
- tokenizer->advance();
- }
- if (tokenizer->get_token() != GDScriptTokenizer::TK_CURLY_BRACKET_OPEN) {
- _set_error("Expected \"{\" in the enum declaration.");
- return;
- }
- tokenizer->advance();
-
- while (true) {
- if (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE) {
-
- tokenizer->advance(); // Ignore newlines
- } else if (tokenizer->get_token() == GDScriptTokenizer::TK_CURLY_BRACKET_CLOSE) {
-
- tokenizer->advance();
- break; // End of enum
- } else if (!tokenizer->is_token_literal(0, true)) {
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_EOF) {
- _set_error("Unexpected end of file.");
- } else {
- _set_error(String("Unexpected ") + GDScriptTokenizer::get_token_name(tokenizer->get_token()) + ", expected an identifier.");
- }
-
- return;
- } else { // tokenizer->is_token_literal(0, true)
- StringName const_id = tokenizer->get_token_literal();
-
- tokenizer->advance();
-
- ConstantNode *enum_value_expr;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) {
- tokenizer->advance();
-
- Node *subexpr = _parse_and_reduce_expression(p_class, true, true);
- if (!subexpr) {
- if (_recover_from_completion()) {
- break;
- }
- return;
- }
-
- if (subexpr->type != Node::TYPE_CONSTANT) {
- _set_error("Expected a constant expression.");
- return;
- }
-
- enum_value_expr = static_cast<ConstantNode *>(subexpr);
-
- if (enum_value_expr->value.get_type() != Variant::INT) {
- _set_error("Expected an integer value for \"enum\".");
- return;
- }
-
- last_assign = enum_value_expr->value;
-
- } else {
- last_assign = last_assign + 1;
- enum_value_expr = alloc_node<ConstantNode>();
- enum_value_expr->value = last_assign;
- enum_value_expr->datatype = _type_from_variant(enum_value_expr->value);
- }
-
- 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 != "") {
- enum_dict[const_id] = enum_value_expr->value;
- } else {
- if (current_class->constant_expressions.has(const_id)) {
- _set_error("A constant named \"" + String(const_id) + "\" already exists in this class (at line " +
- itos(current_class->constant_expressions[const_id].expression->line) + ").");
- return;
- }
-
- for (int i = 0; i < current_class->variables.size(); i++) {
- if (current_class->variables[i].identifier == const_id) {
- _set_error("A variable named \"" + String(const_id) + "\" already exists in this class (at line " +
- itos(current_class->variables[i].line) + ").");
- return;
- }
- }
-
- for (int i = 0; i < current_class->subclasses.size(); i++) {
- if (current_class->subclasses[i]->name == const_id) {
- _set_error("A class named \"" + String(const_id) + "\" already exists in this class (at line " + itos(current_class->subclasses[i]->line) + ").");
- return;
- }
- }
-
- ClassNode::Constant constant;
- constant.type.has_type = true;
- constant.type.kind = DataType::BUILTIN;
- constant.type.builtin_type = Variant::INT;
- constant.expression = enum_value_expr;
- p_class->constant_expressions.insert(const_id, constant);
- }
- }
- }
-
- if (enum_name != "") {
- ClassNode::Constant enum_constant;
- ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value = enum_dict;
- cn->datatype = _type_from_variant(cn->value);
-
- enum_constant.expression = cn;
- enum_constant.type = cn->datatype;
- p_class->constant_expressions.insert(enum_name, enum_constant);
- }
-
- if (!_end_statement()) {
- _set_error("Expected end of statement (\"enum\").");
- return;
- }
-
- } break;
-
- case GDScriptTokenizer::TK_CONSTANT: {
- if (tokenizer->get_token_constant().get_type() == Variant::STRING) {
- tokenizer->advance();
- // Ignore
- } else {
- _set_error(String() + "Unexpected constant of type: " + Variant::get_type_name(tokenizer->get_token_constant().get_type()));
- return;
- }
- } break;
-
- case GDScriptTokenizer::TK_CF_PASS: {
- tokenizer->advance();
- } break;
-
- default: {
-
- _set_error(String() + "Unexpected token: " + tokenizer->get_token_name(tokenizer->get_token()) + ":" + tokenizer->get_token_identifier());
- return;
-
- } break;
- }
- }
+ return assignment;
}
-void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive) {
-
- if (p_class->base_type.has_type) {
- // Already determined
- } else if (p_class->extends_used) {
- //do inheritance
- String path = p_class->extends_file;
-
- Ref<GDScript> script;
- StringName native;
- ClassNode *base_class = nullptr;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ AwaitNode *await = alloc_node<AwaitNode>();
+ await->to_await = parse_precedence(PREC_AWAIT, false);
- if (path != "") {
- //path (and optionally subclasses)
+ current_function->is_coroutine = true;
- if (path.is_rel_path()) {
+ return await;
+}
- String base = base_path;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ ArrayNode *array = alloc_node<ArrayNode>();
- if (base == "" || base.is_rel_path()) {
- _set_error("Couldn't resolve relative path for the parent class: " + path, p_class->line);
- return;
- }
- path = base.plus_file(path).simplify_path();
- }
- script = ResourceLoader::load(path);
- if (script.is_null()) {
- _set_error("Couldn't load the base class: " + path, p_class->line);
- return;
+ if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
+ do {
+ if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
+ // Allow for trailing comma.
+ break;
}
- if (!script->is_valid()) {
- _set_error("Script isn't fully loaded (cyclic preload?): " + path, p_class->line);
- return;
+ ExpressionNode *element = parse_expression(false);
+ if (element == nullptr) {
+ push_error(R"(Expected expression as array element.)");
+ } else {
+ array->elements.push_back(element);
}
+ } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
+ }
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
- if (p_class->extends_class.size()) {
-
- for (int i = 0; i < p_class->extends_class.size(); i++) {
+ return array;
+}
- String sub = p_class->extends_class[i];
- if (script->get_subclasses().has(sub)) {
+GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ DictionaryNode *dictionary = alloc_node<DictionaryNode>();
- Ref<Script> subclass = script->get_subclasses()[sub]; //avoid reference from disappearing
- script = subclass;
- } else {
-
- _set_error("Couldn't find the subclass: " + sub, p_class->line);
- return;
- }
- }
+ bool decided_style = false;
+ if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
+ do {
+ if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
+ // Allow for trailing comma.
+ break;
}
- } else {
+ // Key.
+ ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
- if (p_class->extends_class.size() == 0) {
- _set_error("Parser bug: undecidable inheritance.", p_class->line);
- ERR_FAIL();
+ if (key == nullptr) {
+ push_error(R"(Expected expression as dictionary key.)");
}
- //look around for the subclasses
-
- int extend_iter = 1;
- String base = p_class->extends_class[0];
- ClassNode *p = p_class->owner;
- Ref<GDScript> base_script;
-
- if (ScriptServer::is_global_class(base)) {
- base_script = ResourceLoader::load(ScriptServer::get_global_class_path(base));
- if (!base_script.is_valid()) {
- _set_error("The class \"" + base + "\" couldn't be fully loaded (script error or cyclic dependency).", p_class->line);
- return;
- }
- p = nullptr;
- } else {
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
- }
- String name = s.get_slice("/", 1);
- if (name == base) {
- String singleton_path = ProjectSettings::get_singleton()->get(s);
- if (singleton_path.begins_with("*")) {
- singleton_path = singleton_path.right(1);
- }
- if (!singleton_path.begins_with("res://")) {
- singleton_path = "res://" + singleton_path;
- }
- base_script = ResourceLoader::load(singleton_path);
- if (!base_script.is_valid()) {
- _set_error("Class '" + base + "' could not be fully loaded (script error or cyclic inheritance).", p_class->line);
- return;
- }
- p = nullptr;
- }
- }
- }
-
- while (p) {
-
- bool found = false;
- for (int i = 0; i < p->subclasses.size(); i++) {
- if (p->subclasses[i]->name == base) {
- ClassNode *test = p->subclasses[i];
- while (test) {
- if (test == p_class) {
- _set_error("Cyclic inheritance.", test->line);
- return;
- }
- if (test->base_type.kind == DataType::CLASS) {
- test = test->base_type.class_type;
- } else {
- break;
- }
- }
- found = true;
- if (extend_iter < p_class->extends_class.size()) {
- // Keep looking at current classes if possible
- base = p_class->extends_class[extend_iter++];
- p = p->subclasses[i];
- } else {
- base_class = p->subclasses[i];
- }
+ if (!decided_style) {
+ switch (current.type) {
+ case GDScriptTokenizer::Token::COLON:
+ dictionary->style = DictionaryNode::PYTHON_DICT;
+ break;
+ case GDScriptTokenizer::Token::EQUAL:
+ dictionary->style = DictionaryNode::LUA_TABLE;
+ break;
+ default:
+ push_error(R"(Expected ":" or "=" after dictionary key.)");
break;
- }
}
+ decided_style = true;
+ }
- if (base_class) break;
- if (found) continue;
-
- if (p->constant_expressions.has(base)) {
- if (p->constant_expressions[base].expression->type != Node::TYPE_CONSTANT) {
- _set_error("Couldn't resolve the constant \"" + base + "\".", p_class->line);
- return;
+ switch (dictionary->style) {
+ case DictionaryNode::LUA_TABLE:
+ if (key != nullptr && key->type != Node::IDENTIFIER) {
+ push_error("Expected identifier as dictionary key.");
}
- const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[base].expression);
- base_script = cn->value;
- if (base_script.is_null()) {
- _set_error("Constant isn't a class: " + base, p_class->line);
- return;
+ if (!match(GDScriptTokenizer::Token::EQUAL)) {
+ if (match(GDScriptTokenizer::Token::COLON)) {
+ push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
+ advance(); // Consume wrong separator anyway.
+ } else {
+ push_error(R"(Expected "=" after dictionary key.)");
+ }
}
break;
- }
-
- p = p->owner;
- }
-
- if (base_script.is_valid()) {
-
- String ident = base;
- Ref<GDScript> find_subclass = base_script;
-
- for (int i = extend_iter; i < p_class->extends_class.size(); i++) {
-
- String subclass = p_class->extends_class[i];
-
- ident += ("." + subclass);
-
- if (find_subclass->get_subclasses().has(subclass)) {
-
- find_subclass = find_subclass->get_subclasses()[subclass];
- } else if (find_subclass->get_constants().has(subclass)) {
-
- Ref<GDScript> new_base_class = find_subclass->get_constants()[subclass];
- if (new_base_class.is_null()) {
- _set_error("Constant isn't a class: " + ident, p_class->line);
- return;
+ case DictionaryNode::PYTHON_DICT:
+ if (!match(GDScriptTokenizer::Token::COLON)) {
+ if (match(GDScriptTokenizer::Token::EQUAL)) {
+ push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
+ advance(); // Consume wrong separator anyway.
+ } else {
+ push_error(R"(Expected ":" after dictionary key.)");
}
- find_subclass = new_base_class;
- } else {
-
- _set_error("Couldn't find the subclass: " + ident, p_class->line);
- return;
}
- }
-
- script = find_subclass;
-
- } else if (!base_class) {
-
- if (p_class->extends_class.size() > 1) {
-
- _set_error("Invalid inheritance (unknown class + subclasses).", p_class->line);
- return;
- }
- //if not found, try engine classes
- if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {
-
- _set_error("Unknown class: \"" + base + "\"", p_class->line);
- return;
- }
-
- native = base;
+ break;
}
- }
-
- if (base_class) {
- p_class->base_type.has_type = true;
- p_class->base_type.kind = DataType::CLASS;
- p_class->base_type.class_type = base_class;
- } else if (script.is_valid()) {
- p_class->base_type.has_type = true;
- p_class->base_type.kind = DataType::GDSCRIPT;
- p_class->base_type.script_type = script;
- p_class->base_type.native_type = script->get_instance_base_type();
- } else if (native != StringName()) {
- p_class->base_type.has_type = true;
- p_class->base_type.kind = DataType::NATIVE;
- p_class->base_type.native_type = native;
- } else {
- _set_error("Couldn't determine inheritance.", p_class->line);
- return;
- }
- } else {
- // without extends, implicitly extend Reference
- p_class->base_type.has_type = true;
- p_class->base_type.kind = DataType::NATIVE;
- p_class->base_type.native_type = "Reference";
- }
-
- if (p_recursive) {
- // Recursively determine subclasses
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- _determine_inheritance(p_class->subclasses[i], p_recursive);
- }
- }
-}
-
-String GDScriptParser::DataType::to_string() const {
- if (!has_type) return "var";
- switch (kind) {
- case BUILTIN: {
- if (builtin_type == Variant::NIL) return "null";
- return Variant::get_type_name(builtin_type);
- } break;
- case NATIVE: {
- if (is_meta_type) {
- return "GDScriptNativeClass";
+ // Value.
+ ExpressionNode *value = parse_expression(false);
+ if (value == nullptr) {
+ push_error(R"(Expected expression as dictionary value.)");
}
- return native_type.operator String();
- } break;
- case GDSCRIPT: {
- Ref<GDScript> gds = script_type;
- const String &gds_class = gds->get_script_class_name();
- if (!gds_class.empty()) {
- return gds_class;
- }
- [[fallthrough]];
- }
- case SCRIPT: {
- if (is_meta_type) {
- return script_type->get_class_name().operator String();
- }
- String name = script_type->get_name();
- if (name != String()) {
- return name;
+ if (key != nullptr && value != nullptr) {
+ dictionary->elements.push_back({ key, value });
}
- name = script_type->get_path().get_file();
- if (name != String()) {
- return name;
- }
- return native_type.operator String();
- } break;
- case CLASS: {
- ERR_FAIL_COND_V(!class_type, String());
- if (is_meta_type) {
- return "GDScript";
- }
- if (class_type->name == StringName()) {
- return "self";
- }
- return class_type->name.operator String();
- } break;
- case UNRESOLVED: {
- } break;
+ } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
}
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
- return "Unresolved";
+ return dictionary;
}
-bool GDScriptParser::_parse_type(DataType &r_type, bool p_can_be_void) {
- tokenizer->advance();
- r_type.has_type = true;
-
- bool finished = false;
- bool can_index = false;
- String full_name;
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- completion_cursor = StringName();
- completion_type = COMPLETION_TYPE_HINT;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_argument = 0;
- completion_block = current_block;
- completion_found = true;
- completion_ident_is_call = p_can_be_void;
- tokenizer->advance();
- }
-
- switch (tokenizer->get_token()) {
- case GDScriptTokenizer::TK_PR_VOID: {
- if (!p_can_be_void) {
- return false;
- }
- r_type.kind = DataType::BUILTIN;
- r_type.builtin_type = Variant::NIL;
- } break;
- case GDScriptTokenizer::TK_BUILT_IN_TYPE: {
- r_type.builtin_type = tokenizer->get_token_type();
- if (tokenizer->get_token_type() == Variant::OBJECT) {
- r_type.kind = DataType::NATIVE;
- r_type.native_type = "Object";
- } else {
- r_type.kind = DataType::BUILTIN;
- }
- } break;
- case GDScriptTokenizer::TK_IDENTIFIER: {
- r_type.native_type = tokenizer->get_token_identifier();
- if (ClassDB::class_exists(r_type.native_type) || ClassDB::class_exists("_" + r_type.native_type.operator String())) {
- r_type.kind = DataType::NATIVE;
- } else {
- r_type.kind = DataType::UNRESOLVED;
- can_index = true;
- full_name = r_type.native_type;
- }
- } break;
- default: {
- return false;
- }
- }
-
- tokenizer->advance();
-
- if (tokenizer->get_token() == GDScriptTokenizer::TK_CURSOR) {
- completion_cursor = r_type.native_type;
- completion_type = COMPLETION_TYPE_HINT;
- completion_class = current_class;
- completion_function = current_function;
- completion_line = tokenizer->get_token_line();
- completion_argument = 0;
- completion_block = current_block;
- completion_found = true;
- completion_ident_is_call = p_can_be_void;
- tokenizer->advance();
+GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ ExpressionNode *grouped = parse_expression(false);
+ pop_multiline();
+ if (grouped == nullptr) {
+ push_error(R"(Expected grouping expression.)");
+ } else {
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
}
+ return grouped;
+}
- if (can_index) {
- while (!finished) {
- switch (tokenizer->get_token()) {
- case GDScriptTokenizer::TK_PERIOD: {
- if (!can_index) {
- _set_error("Unexpected \".\".");
- return false;
- }
- can_index = false;
- tokenizer->advance();
- } break;
- case GDScriptTokenizer::TK_IDENTIFIER: {
- if (can_index) {
- _set_error("Unexpected identifier.");
- return false;
- }
-
- StringName id;
- bool has_completion = _get_completable_identifier(COMPLETION_TYPE_HINT_INDEX, id);
- if (id == StringName()) {
- id = "@temp";
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ SubscriptNode *attribute = alloc_node<SubscriptNode>();
- full_name += "." + id.operator String();
- can_index = true;
- if (has_completion) {
- completion_cursor = full_name;
- }
- } break;
- default: {
- finished = true;
- } break;
+ if (for_completion) {
+ bool is_builtin = false;
+ if (p_previous_operand->type == Node::IDENTIFIER) {
+ const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
+ Variant::Type builtin_type = get_builtin_type(id->name);
+ if (builtin_type < Variant::VARIANT_MAX) {
+ make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT, builtin_type, true);
+ is_builtin = true;
}
}
-
- if (tokenizer->get_token(-1) == GDScriptTokenizer::TK_PERIOD) {
- _set_error("Expected a subclass identifier.");
- return false;
+ if (!is_builtin) {
+ make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
}
-
- r_type.native_type = full_name;
}
- return true;
-}
-
-GDScriptParser::DataType GDScriptParser::_resolve_type(const DataType &p_source, int p_line) {
- if (!p_source.has_type) return p_source;
- if (p_source.kind != DataType::UNRESOLVED) return p_source;
+ attribute->is_attribute = true;
+ attribute->base = p_previous_operand;
- Vector<String> full_name = p_source.native_type.operator String().split(".", false);
- int name_part = 0;
-
- DataType result;
- result.has_type = true;
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
+ return attribute;
+ }
+ attribute->attribute = parse_identifier();
- while (name_part < full_name.size()) {
+ return attribute;
+}
- bool found = false;
- StringName id = full_name[name_part];
- DataType base_type = result;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ SubscriptNode *subscript = alloc_node<SubscriptNode>();
- ClassNode *p = nullptr;
- if (name_part == 0) {
- if (ScriptServer::is_global_class(id)) {
- String script_path = ScriptServer::get_global_class_path(id);
- if (script_path == self_path) {
- result.kind = DataType::CLASS;
- result.class_type = static_cast<ClassNode *>(head);
- } else {
- Ref<Script> script = ResourceLoader::load(script_path);
- Ref<GDScript> gds = script;
- if (gds.is_valid()) {
- if (!gds->is_valid()) {
- _set_error("The class \"" + id + "\" couldn't be fully loaded (script error or cyclic dependency).", p_line);
- return DataType();
- }
- result.kind = DataType::GDSCRIPT;
- result.script_type = gds;
- } else if (script.is_valid()) {
- result.kind = DataType::SCRIPT;
- result.script_type = script;
- } else {
- _set_error("The class \"" + id + "\" was found in global scope, but its script couldn't be loaded.", p_line);
- return DataType();
- }
- }
- name_part++;
- continue;
- }
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
- String singleton_path;
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
- }
- String name = s.get_slice("/", 1);
- if (name == id) {
- singleton_path = ProjectSettings::get_singleton()->get(s);
- if (singleton_path.begins_with("*")) {
- singleton_path = singleton_path.right(1);
- }
- if (!singleton_path.begins_with("res://")) {
- singleton_path = "res://" + singleton_path;
- }
- break;
- }
- }
- if (!singleton_path.empty()) {
- Ref<Script> script = ResourceLoader::load(singleton_path);
- Ref<GDScript> gds = script;
- if (gds.is_valid()) {
- if (!gds->is_valid()) {
- _set_error("Class '" + id + "' could not be fully loaded (script error or cyclic inheritance).", p_line);
- return DataType();
- }
- result.kind = DataType::GDSCRIPT;
- result.script_type = gds;
- } else if (script.is_valid()) {
- result.kind = DataType::SCRIPT;
- result.script_type = script;
- } else {
- _set_error("Couldn't fully load singleton script '" + id + "' (possible cyclic reference or parse error).", p_line);
- return DataType();
- }
- name_part++;
- continue;
- }
+ make_completion_context(COMPLETION_SUBSCRIPT, subscript);
- p = current_class;
- } else if (base_type.kind == DataType::CLASS) {
- p = base_type.class_type;
- }
- while (p) {
- if (p->constant_expressions.has(id)) {
- if (p->constant_expressions[id].expression->type != Node::TYPE_CONSTANT) {
- _set_error("Parser bug: unresolved constant.", p_line);
- ERR_FAIL_V(result);
- }
- const ConstantNode *cn = static_cast<const ConstantNode *>(p->constant_expressions[id].expression);
- Ref<GDScript> gds = cn->value;
- if (gds.is_valid()) {
- result.kind = DataType::GDSCRIPT;
- result.script_type = gds;
- found = true;
- } else {
- Ref<Script> scr = cn->value;
- if (scr.is_valid()) {
- result.kind = DataType::SCRIPT;
- result.script_type = scr;
- found = true;
- }
- }
- break;
- }
+ subscript->base = p_previous_operand;
+ subscript->index = parse_expression(false);
- // Inner classes
- ClassNode *outer_class = p;
- while (outer_class) {
- if (outer_class->name == id) {
- found = true;
- result.kind = DataType::CLASS;
- result.class_type = outer_class;
- break;
- }
- for (int i = 0; i < outer_class->subclasses.size(); i++) {
- if (outer_class->subclasses[i] == p) {
- continue;
- }
- if (outer_class->subclasses[i]->name == id) {
- found = true;
- result.kind = DataType::CLASS;
- result.class_type = outer_class->subclasses[i];
- break;
- }
- }
- if (found) {
- break;
- }
- outer_class = outer_class->owner;
- }
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
- if (!found && p->base_type.kind == DataType::CLASS) {
- p = p->base_type.class_type;
- } else {
- base_type = p->base_type;
- break;
- }
- }
+ return subscript;
+}
- // Still look for class constants in parent scripts
- if (!found && (base_type.kind == DataType::GDSCRIPT || base_type.kind == DataType::SCRIPT)) {
- Ref<Script> scr = base_type.script_type;
- ERR_FAIL_COND_V(scr.is_null(), result);
- while (scr.is_valid()) {
- Map<StringName, Variant> constants;
- scr->get_constants(&constants);
-
- if (constants.has(id)) {
- Ref<GDScript> gds = constants[id];
-
- if (gds.is_valid()) {
- result.kind = DataType::GDSCRIPT;
- result.script_type = gds;
- found = true;
- } else {
- Ref<Script> scr2 = constants[id];
- if (scr2.is_valid()) {
- result.kind = DataType::SCRIPT;
- result.script_type = scr2;
- found = true;
- }
- }
- }
- if (found) {
- break;
- } else {
- scr = scr->get_base_script();
- }
- }
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ CastNode *cast = alloc_node<CastNode>();
- if (!found && !for_completion) {
- String base;
- if (name_part == 0) {
- base = "self";
- } else {
- base = result.to_string();
- }
- _set_error("The identifier \"" + String(id) + "\" isn't a valid type (not a script or class), or couldn't be found on base \"" +
- base + "\".",
- p_line);
- return DataType();
- }
+ cast->operand = p_previous_operand;
+ cast->cast_type = parse_type();
- name_part++;
+ if (cast->cast_type == nullptr) {
+ push_error(R"(Expected type specifier after "as".)");
+ return p_previous_operand;
}
- return result;
+ return cast;
}
-GDScriptParser::DataType GDScriptParser::_type_from_variant(const Variant &p_value) const {
- DataType result;
- result.has_type = true;
- result.is_constant = true;
- result.kind = DataType::BUILTIN;
- result.builtin_type = p_value.get_type();
-
- if (result.builtin_type == Variant::OBJECT) {
- Object *obj = p_value.operator Object *();
- if (!obj) {
- return DataType();
- }
- result.native_type = obj->get_class_name();
- Ref<Script> scr = p_value;
- if (scr.is_valid()) {
- result.is_meta_type = true;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ CallNode *call = alloc_node<CallNode>();
+
+ if (previous.type == GDScriptTokenizer::Token::SUPER) {
+ // Super call.
+ call->is_super = true;
+ push_multiline(true);
+ if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
+ // Implicit call to the parent method of the same name.
+ if (current_function == nullptr) {
+ push_error(R"(Cannot use implicit "super" call outside of a function.)");
+ pop_multiline();
+ return nullptr;
+ }
+ call->function_name = current_function->identifier->name;
} else {
- result.is_meta_type = false;
- scr = obj->get_script();
+ consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
+ make_completion_context(COMPLETION_SUPER_METHOD, call, true);
+ if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
+ pop_multiline();
+ return nullptr;
+ }
+ IdentifierNode *identifier = parse_identifier();
+ call->callee = identifier;
+ call->function_name = identifier->name;
+ consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
}
- if (scr.is_valid()) {
- result.script_type = scr;
- Ref<GDScript> gds = scr;
- if (gds.is_valid()) {
- result.kind = DataType::GDSCRIPT;
+ } else {
+ call->callee = p_previous_operand;
+
+ if (call->callee == nullptr) {
+ push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
+ } else if (call->callee->type == Node::IDENTIFIER) {
+ call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
+ make_completion_context(COMPLETION_METHOD, call->callee);
+ } else if (call->callee->type == Node::SUBSCRIPT) {
+ SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
+ if (attribute->is_attribute) {
+ if (attribute->attribute) {
+ call->function_name = attribute->attribute->name;
+ }
+ make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
} else {
- result.kind = DataType::SCRIPT;
+ // TODO: The analyzer can see if this is actually a Callable and give better error message.
+ push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
}
- result.native_type = scr->get_instance_base_type();
} else {
- result.kind = DataType::NATIVE;
+ push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
}
}
- return result;
-}
-
-GDScriptParser::DataType GDScriptParser::_type_from_property(const PropertyInfo &p_property, bool p_nil_is_variant) const {
- DataType ret;
- if (p_property.type == Variant::NIL && (p_nil_is_variant || (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {
- // Variant
- return ret;
+ // Arguments.
+ CompletionType ct = COMPLETION_CALL_ARGUMENTS;
+ if (call->function_name == "load") {
+ ct = COMPLETION_RESOURCE_PATH;
}
- ret.has_type = true;
- ret.builtin_type = p_property.type;
- if (p_property.type == Variant::OBJECT) {
- ret.kind = DataType::NATIVE;
- ret.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
- } else {
- ret.kind = DataType::BUILTIN;
- }
- return ret;
-}
-
-GDScriptParser::DataType GDScriptParser::_type_from_gdtype(const GDScriptDataType &p_gdtype) const {
- DataType result;
- if (!p_gdtype.has_type) {
- return result;
- }
-
- result.has_type = true;
- result.builtin_type = p_gdtype.builtin_type;
- result.native_type = p_gdtype.native_type;
- result.script_type = p_gdtype.script_type;
-
- switch (p_gdtype.kind) {
- case GDScriptDataType::UNINITIALIZED: {
- ERR_PRINT("Uninitialized datatype. Please report a bug.");
- } break;
- case GDScriptDataType::BUILTIN: {
- result.kind = DataType::BUILTIN;
- } break;
- case GDScriptDataType::NATIVE: {
- result.kind = DataType::NATIVE;
- } break;
- case GDScriptDataType::GDSCRIPT: {
- result.kind = DataType::GDSCRIPT;
- } break;
- case GDScriptDataType::SCRIPT: {
- result.kind = DataType::SCRIPT;
- } break;
- }
- return result;
-}
-
-GDScriptParser::DataType GDScriptParser::_get_operation_type(const Variant::Operator p_op, const DataType &p_a, const DataType &p_b, bool &r_valid) const {
- if (!p_a.has_type || !p_b.has_type) {
- r_valid = true;
- return DataType();
- }
-
- Variant::Type a_type = p_a.kind == DataType::BUILTIN ? p_a.builtin_type : Variant::OBJECT;
- Variant::Type b_type = p_b.kind == DataType::BUILTIN ? p_b.builtin_type : Variant::OBJECT;
-
- Variant a;
- REF a_ref;
- if (a_type == Variant::OBJECT) {
- a_ref.instance();
- a = a_ref;
- } else {
- Callable::CallError err;
- a = Variant::construct(a_type, nullptr, 0, err);
- if (err.error != Callable::CallError::CALL_OK) {
- r_valid = false;
- return DataType();
+ push_completion_call(call);
+ int argument_index = 0;
+ do {
+ make_completion_context(ct, call, argument_index++, true);
+ if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
+ // Allow for trailing comma.
+ break;
}
- }
- Variant b;
- REF b_ref;
- if (b_type == Variant::OBJECT) {
- b_ref.instance();
- b = b_ref;
- } else {
- Callable::CallError err;
- b = Variant::construct(b_type, nullptr, 0, err);
- if (err.error != Callable::CallError::CALL_OK) {
- r_valid = false;
- return DataType();
+ ExpressionNode *argument = parse_expression(false);
+ if (argument == nullptr) {
+ push_error(R"(Expected expression as the function argument.)");
+ } else {
+ call->arguments.push_back(argument);
}
- }
+ ct = COMPLETION_CALL_ARGUMENTS;
+ } while (match(GDScriptTokenizer::Token::COMMA));
+ pop_completion_call();
- // Avoid division by zero
- if (a_type == Variant::INT || a_type == Variant::FLOAT) {
- Variant::evaluate(Variant::OP_ADD, a, 1, a, r_valid);
- }
- if (b_type == Variant::INT || b_type == Variant::FLOAT) {
- Variant::evaluate(Variant::OP_ADD, b, 1, b, r_valid);
- }
- if (a_type == Variant::STRING && b_type != Variant::ARRAY) {
- a = "%s"; // Work around for formatting operator (%)
- }
-
- Variant ret;
- Variant::evaluate(p_op, a, b, ret, r_valid);
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
- if (r_valid) {
- return _type_from_variant(ret);
- }
-
- return DataType();
+ return call;
}
-Variant::Operator GDScriptParser::_get_variant_operation(const OperatorNode::Operator &p_op) const {
- switch (p_op) {
- case OperatorNode::OP_NEG: {
- return Variant::OP_NEGATE;
- } break;
- case OperatorNode::OP_POS: {
- return Variant::OP_POSITIVE;
- } break;
- case OperatorNode::OP_NOT: {
- return Variant::OP_NOT;
- } break;
- case OperatorNode::OP_BIT_INVERT: {
- return Variant::OP_BIT_NEGATE;
- } break;
- case OperatorNode::OP_IN: {
- return Variant::OP_IN;
- } break;
- case OperatorNode::OP_EQUAL: {
- return Variant::OP_EQUAL;
- } break;
- case OperatorNode::OP_NOT_EQUAL: {
- return Variant::OP_NOT_EQUAL;
- } break;
- case OperatorNode::OP_LESS: {
- return Variant::OP_LESS;
- } break;
- case OperatorNode::OP_LESS_EQUAL: {
- return Variant::OP_LESS_EQUAL;
- } break;
- case OperatorNode::OP_GREATER: {
- return Variant::OP_GREATER;
- } break;
- case OperatorNode::OP_GREATER_EQUAL: {
- return Variant::OP_GREATER_EQUAL;
- } break;
- case OperatorNode::OP_AND: {
- return Variant::OP_AND;
- } break;
- case OperatorNode::OP_OR: {
- return Variant::OP_OR;
- } break;
- case OperatorNode::OP_ASSIGN_ADD:
- case OperatorNode::OP_ADD: {
- return Variant::OP_ADD;
- } break;
- case OperatorNode::OP_ASSIGN_SUB:
- case OperatorNode::OP_SUB: {
- return Variant::OP_SUBTRACT;
- } break;
- case OperatorNode::OP_ASSIGN_MUL:
- case OperatorNode::OP_MUL: {
- return Variant::OP_MULTIPLY;
- } break;
- case OperatorNode::OP_ASSIGN_DIV:
- case OperatorNode::OP_DIV: {
- return Variant::OP_DIVIDE;
- } break;
- case OperatorNode::OP_ASSIGN_MOD:
- case OperatorNode::OP_MOD: {
- return Variant::OP_MODULE;
- } break;
- case OperatorNode::OP_ASSIGN_BIT_AND:
- case OperatorNode::OP_BIT_AND: {
- return Variant::OP_BIT_AND;
- } break;
- case OperatorNode::OP_ASSIGN_BIT_OR:
- case OperatorNode::OP_BIT_OR: {
- return Variant::OP_BIT_OR;
- } break;
- case OperatorNode::OP_ASSIGN_BIT_XOR:
- case OperatorNode::OP_BIT_XOR: {
- return Variant::OP_BIT_XOR;
- } break;
- case OperatorNode::OP_ASSIGN_SHIFT_LEFT:
- case OperatorNode::OP_SHIFT_LEFT: {
- return Variant::OP_SHIFT_LEFT;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ if (match(GDScriptTokenizer::Token::LITERAL)) {
+ if (previous.literal.get_type() != Variant::STRING) {
+ push_error(R"(Expect node path as string or identifier after "$".)");
+ return nullptr;
}
- case OperatorNode::OP_ASSIGN_SHIFT_RIGHT:
- case OperatorNode::OP_SHIFT_RIGHT: {
- return Variant::OP_SHIFT_RIGHT;
- }
- default: {
- return Variant::OP_MAX;
- } break;
+ GetNodeNode *get_node = alloc_node<GetNodeNode>();
+ make_completion_context(COMPLETION_GET_NODE, get_node);
+ get_node->string = parse_literal();
+ return get_node;
+ } else if (current.is_node_name()) {
+ GetNodeNode *get_node = alloc_node<GetNodeNode>();
+ int chain_position = 0;
+ do {
+ make_completion_context(COMPLETION_GET_NODE, get_node, chain_position++);
+ if (!current.is_node_name()) {
+ push_error(R"(Expect node path after "/".)");
+ return nullptr;
+ }
+ advance();
+ IdentifierNode *identifier = alloc_node<IdentifierNode>();
+ identifier->name = previous.get_identifier();
+ get_node->chain.push_back(identifier);
+ } while (match(GDScriptTokenizer::Token::SLASH));
+ return get_node;
+ } else {
+ push_error(R"(Expect node path as string or identifier after "$".)");
+ return nullptr;
}
}
-bool GDScriptParser::_is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion) const {
- // Ignore for completion
- if (!check_types || for_completion) {
- return true;
- }
- // Can't test if not all have type
- if (!p_container.has_type || !p_expression.has_type) {
- return true;
- }
-
- // Should never get here unresolved
- ERR_FAIL_COND_V(p_container.kind == DataType::UNRESOLVED, false);
- ERR_FAIL_COND_V(p_expression.kind == DataType::UNRESOLVED, false);
-
- if (p_container.kind == DataType::BUILTIN && p_expression.kind == DataType::BUILTIN) {
- bool valid = p_container.builtin_type == p_expression.builtin_type;
- if (p_allow_implicit_conversion) {
- valid = valid || Variant::can_convert_strict(p_expression.builtin_type, p_container.builtin_type);
- }
- return valid;
- }
+GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ PreloadNode *preload = alloc_node<PreloadNode>();
+ preload->resolved_path = "<missing path>";
- 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) {
- return p_expression.builtin_type == Variant::NIL;
- }
- // If it's not a built-in, must be an object
- return true;
- }
+ push_multiline(true);
+ consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
- if (p_container.kind == DataType::BUILTIN || (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type != Variant::NIL)) {
- // Can't mix built-ins with objects
- return false;
- }
-
- // From now on everything is objects, check polymorphism
- // The container must be the same class or a superclass of the expression
-
- if (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type == Variant::NIL) {
- // Null can be assigned to object types
- return true;
- }
+ make_completion_context(COMPLETION_RESOURCE_PATH, preload);
+ push_completion_call(preload);
- StringName expr_native;
- Ref<Script> expr_script;
- ClassNode *expr_class = nullptr;
+ preload->path = parse_expression(false);
- switch (p_expression.kind) {
- case DataType::NATIVE: {
- if (p_container.kind != DataType::NATIVE) {
- // Non-native type can't be a superclass of a native type
- return false;
- }
- if (p_expression.is_meta_type) {
- expr_native = GDScriptNativeClass::get_class_static();
- } else {
- expr_native = p_expression.native_type;
- }
- } break;
- case DataType::SCRIPT:
- case DataType::GDSCRIPT: {
- if (p_container.kind == DataType::CLASS) {
- // This cannot be resolved without cyclic dependencies, so just bail out
- return false;
- }
- if (p_expression.is_meta_type) {
- expr_native = p_expression.script_type->get_class_name();
- } else {
- expr_script = p_expression.script_type;
- expr_native = expr_script->get_instance_base_type();
- }
- } break;
- case DataType::CLASS: {
- if (p_expression.is_meta_type) {
- expr_native = GDScript::get_class_static();
- } else {
- expr_class = p_expression.class_type;
- ClassNode *base = expr_class;
- while (base->base_type.kind == DataType::CLASS) {
- base = base->base_type.class_type;
- }
- expr_native = base->base_type.native_type;
- expr_script = base->base_type.script_type;
- }
- } break;
- case DataType::BUILTIN: // Already handled above
- case DataType::UNRESOLVED: // Not allowed, see above
- break;
+ if (preload->path == nullptr) {
+ push_error(R"(Expected resource path after "(".)");
}
- // Some classes are prefixed with `_` internally
- if (!ClassDB::class_exists(expr_native)) {
- expr_native = "_" + expr_native;
- }
+ pop_completion_call();
- switch (p_container.kind) {
- case DataType::NATIVE: {
- if (p_container.is_meta_type) {
- return ClassDB::is_parent_class(expr_native, GDScriptNativeClass::get_class_static());
- } else {
- StringName container_native = ClassDB::class_exists(p_container.native_type) ? p_container.native_type : StringName("_" + p_container.native_type);
- return ClassDB::is_parent_class(expr_native, container_native);
- }
- } break;
- case DataType::SCRIPT:
- case DataType::GDSCRIPT: {
- if (p_container.is_meta_type) {
- return ClassDB::is_parent_class(expr_native, GDScript::get_class_static());
- }
- if (expr_class == head && p_container.script_type->get_path() == self_path) {
- // Special case: container is self script and expression is self
- return true;
- }
- while (expr_script.is_valid()) {
- if (expr_script == p_container.script_type) {
- return true;
- }
- expr_script = expr_script->get_base_script();
- }
- return false;
- } break;
- case DataType::CLASS: {
- if (p_container.is_meta_type) {
- return ClassDB::is_parent_class(expr_native, GDScript::get_class_static());
- }
- if (p_container.class_type == head && expr_script.is_valid() && expr_script->get_path() == self_path) {
- // Special case: container is self and expression is self script
- return true;
- }
- while (expr_class) {
- if (expr_class == p_container.class_type) {
- return true;
- }
- expr_class = expr_class->base_type.class_type;
- }
- return false;
- } break;
- case DataType::BUILTIN: // Already handled above
- case DataType::UNRESOLVED: // Not allowed, see above
- break;
- }
+ pop_multiline();
+ consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
- return false;
+ return preload;
}
-GDScriptParser::Node *GDScriptParser::_get_default_value_for_type(const DataType &p_type, int p_line) {
- Node *result;
+GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
+ // Just for better error messages.
+ GDScriptTokenizer::Token::Type invalid = previous.type;
- if (p_type.has_type && p_type.kind == DataType::BUILTIN && p_type.builtin_type != Variant::NIL && p_type.builtin_type != Variant::OBJECT) {
- if (p_type.builtin_type == Variant::ARRAY) {
- result = alloc_node<ArrayNode>();
- } else if (p_type.builtin_type == Variant::DICTIONARY) {
- result = alloc_node<DictionaryNode>();
- } else {
- ConstantNode *c = alloc_node<ConstantNode>();
- Callable::CallError err;
- c->value = Variant::construct(p_type.builtin_type, nullptr, 0, err);
- c->datatype = _type_from_variant(c->value);
- result = c;
- }
- } else {
- ConstantNode *c = alloc_node<ConstantNode>();
- c->value = Variant();
- c->datatype = _type_from_variant(c->value);
- result = c;
+ switch (invalid) {
+ case GDScriptTokenizer::Token::QUESTION_MARK:
+ push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
+ break;
+ default:
+ return nullptr; // Unreachable.
}
- result->line = p_line;
-
- return result;
+ // Return the previous expression.
+ return p_previous_operand;
}
-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();
- }
-
- DataType node_type;
-
- switch (p_node->type) {
- case Node::TYPE_CONSTANT: {
- node_type = _type_from_variant(static_cast<ConstantNode *>(p_node)->value);
- } break;
- case Node::TYPE_TYPE: {
- TypeNode *tn = static_cast<TypeNode *>(p_node);
- node_type.has_type = true;
- node_type.is_meta_type = true;
- node_type.kind = DataType::BUILTIN;
- node_type.builtin_type = tn->vtype;
- } break;
- case Node::TYPE_ARRAY: {
- node_type.has_type = true;
- node_type.kind = DataType::BUILTIN;
- node_type.builtin_type = Variant::ARRAY;
-#ifdef DEBUG_ENABLED
- // Check stuff inside the array
- ArrayNode *an = static_cast<ArrayNode *>(p_node);
- for (int i = 0; i < an->elements.size(); i++) {
- _reduce_node_type(an->elements[i]);
- }
-#endif // DEBUG_ENABLED
- } break;
- case Node::TYPE_DICTIONARY: {
- node_type.has_type = true;
- node_type.kind = DataType::BUILTIN;
- node_type.builtin_type = Variant::DICTIONARY;
-#ifdef DEBUG_ENABLED
- // Check stuff inside the dictionarty
- DictionaryNode *dn = static_cast<DictionaryNode *>(p_node);
- for (int i = 0; i < dn->elements.size(); i++) {
- _reduce_node_type(dn->elements[i].key);
- _reduce_node_type(dn->elements[i].value);
- }
-#endif // DEBUG_ENABLED
- } break;
- case Node::TYPE_SELF: {
- node_type.has_type = true;
- node_type.kind = DataType::CLASS;
- node_type.class_type = current_class;
- node_type.is_constant = true;
- } break;
- case Node::TYPE_IDENTIFIER: {
- IdentifierNode *id = static_cast<IdentifierNode *>(p_node);
- if (id->declared_block) {
- node_type = id->declared_block->variables[id->name]->get_datatype();
- id->declared_block->variables[id->name]->usages += 1;
- } else if (id->name == "#match_value") {
- // It's a special id just for the match statetement, ignore
- break;
- } else if (current_function && current_function->arguments.find(id->name) >= 0) {
- int idx = current_function->arguments.find(id->name);
- node_type = current_function->argument_types[idx];
+GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
+ TypeNode *type = alloc_node<TypeNode>();
+ make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
+ if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
+ if (match(GDScriptTokenizer::Token::VOID)) {
+ if (p_allow_void) {
+ TypeNode *void_type = alloc_node<TypeNode>();
+ return void_type;
} else {
- node_type = _reduce_identifier_type(nullptr, id->name, id->line, false);
+ push_error(R"("void" is only allowed for a function return type.)");
}
- } break;
- case Node::TYPE_CAST: {
- CastNode *cn = static_cast<CastNode *>(p_node);
-
- DataType source_type = _reduce_node_type(cn->source_node);
- cn->cast_type = _resolve_type(cn->cast_type, cn->line);
- if (source_type.has_type) {
-
- bool valid = false;
- if (check_types) {
- if (cn->cast_type.kind == DataType::BUILTIN && source_type.kind == DataType::BUILTIN) {
- valid = Variant::can_convert(source_type.builtin_type, cn->cast_type.builtin_type);
- }
- if (cn->cast_type.kind != DataType::BUILTIN && source_type.kind != DataType::BUILTIN) {
- valid = _is_type_compatible(cn->cast_type, source_type) || _is_type_compatible(source_type, cn->cast_type);
- }
-
- if (!valid) {
- _set_error("Invalid cast. Cannot convert from \"" + source_type.to_string() +
- "\" to \"" + cn->cast_type.to_string() + "\".",
- cn->line);
- return DataType();
- }
- }
- } else {
-#ifdef DEBUG_ENABLED
- _add_warning(GDScriptWarning::UNSAFE_CAST, cn->line, cn->cast_type.to_string());
-#endif // DEBUG_ENABLED
- _mark_line_as_unsafe(cn->line);
- }
-
- node_type = cn->cast_type;
-
- } break;
- case Node::TYPE_OPERATOR: {
- OperatorNode *op = static_cast<OperatorNode *>(p_node);
-
- switch (op->op) {
- case OperatorNode::OP_CALL:
- case OperatorNode::OP_PARENT_CALL: {
- node_type = _reduce_function_call_type(op);
- } break;
- case OperatorNode::OP_YIELD: {
- if (op->arguments.size() == 2) {
- DataType base_type = _reduce_node_type(op->arguments[0]);
- DataType signal_type = _reduce_node_type(op->arguments[1]);
- // TODO: Check if signal exists when it's a constant
- if (base_type.has_type && base_type.kind == DataType::BUILTIN && base_type.builtin_type != Variant::NIL && base_type.builtin_type != Variant::OBJECT) {
- _set_error("The first argument of \"yield()\" must be an object.", op->line);
- return DataType();
- }
- if (signal_type.has_type && (signal_type.kind != DataType::BUILTIN || signal_type.builtin_type != Variant::STRING)) {
- _set_error("The second argument of \"yield()\" must be a string.", op->line);
- return DataType();
- }
- }
- // yield can return anything
- node_type.has_type = false;
- } break;
- case OperatorNode::OP_IS:
- case OperatorNode::OP_IS_BUILTIN: {
-
- if (op->arguments.size() != 2) {
- _set_error("Parser bug: binary operation without 2 arguments.", op->line);
- ERR_FAIL_V(DataType());
- }
-
- DataType value_type = _reduce_node_type(op->arguments[0]);
- DataType type_type = _reduce_node_type(op->arguments[1]);
-
- if (check_types && type_type.has_type) {
- if (!type_type.is_meta_type && (type_type.kind != DataType::NATIVE || !ClassDB::is_parent_class(type_type.native_type, "Script"))) {
- _set_error("Invalid \"is\" test: the right operand isn't a type (neither a native type nor a script).", op->line);
- return DataType();
- }
- type_type.is_meta_type = false; // Test the actual type
- if (!_is_type_compatible(type_type, value_type) && !_is_type_compatible(value_type, type_type)) {
- if (op->op == OperatorNode::OP_IS) {
- _set_error("A value of type \"" + value_type.to_string() + "\" will never be an instance of \"" + type_type.to_string() + "\".", op->line);
- } else {
- _set_error("A value of type \"" + value_type.to_string() + "\" will never be of type \"" + type_type.to_string() + "\".", op->line);
- }
- return DataType();
- }
- }
-
- node_type.has_type = true;
- node_type.is_constant = true;
- node_type.is_meta_type = false;
- node_type.kind = DataType::BUILTIN;
- node_type.builtin_type = Variant::BOOL;
- } break;
- // Unary operators
- case OperatorNode::OP_NEG:
- case OperatorNode::OP_POS:
- case OperatorNode::OP_NOT:
- case OperatorNode::OP_BIT_INVERT: {
-
- DataType argument_type = _reduce_node_type(op->arguments[0]);
- if (!argument_type.has_type) {
- break;
- }
-
- Variant::Operator var_op = _get_variant_operation(op->op);
- bool valid = false;
- node_type = _get_operation_type(var_op, argument_type, argument_type, valid);
-
- if (check_types && !valid) {
- _set_error("Invalid operand type (\"" + argument_type.to_string() +
- "\") to unary operator \"" + Variant::get_operator_name(var_op) + "\".",
- op->line, op->column);
- return DataType();
- }
-
- } break;
- // Binary operators
- case OperatorNode::OP_IN:
- case OperatorNode::OP_EQUAL:
- case OperatorNode::OP_NOT_EQUAL:
- case OperatorNode::OP_LESS:
- case OperatorNode::OP_LESS_EQUAL:
- case OperatorNode::OP_GREATER:
- case OperatorNode::OP_GREATER_EQUAL:
- case OperatorNode::OP_AND:
- case OperatorNode::OP_OR:
- case OperatorNode::OP_ADD:
- case OperatorNode::OP_SUB:
- case OperatorNode::OP_MUL:
- case OperatorNode::OP_DIV:
- case OperatorNode::OP_MOD:
- case OperatorNode::OP_SHIFT_LEFT:
- case OperatorNode::OP_SHIFT_RIGHT:
- case OperatorNode::OP_BIT_AND:
- case OperatorNode::OP_BIT_OR:
- case OperatorNode::OP_BIT_XOR: {
-
- if (op->arguments.size() != 2) {
- _set_error("Parser bug: binary operation without 2 arguments.", op->line);
- ERR_FAIL_V(DataType());
- }
-
- DataType argument_a_type = _reduce_node_type(op->arguments[0]);
- DataType argument_b_type = _reduce_node_type(op->arguments[1]);
- if (!argument_a_type.has_type || !argument_b_type.has_type) {
- _mark_line_as_unsafe(op->line);
- break;
- }
-
- Variant::Operator var_op = _get_variant_operation(op->op);
- bool valid = false;
- node_type = _get_operation_type(var_op, argument_a_type, argument_b_type, valid);
-
- if (check_types && !valid) {
- _set_error("Invalid operand types (\"" + argument_a_type.to_string() + "\" and \"" +
- argument_b_type.to_string() + "\") to operator \"" + Variant::get_operator_name(var_op) + "\".",
- op->line, op->column);
- return DataType();
- }
-#ifdef DEBUG_ENABLED
- if (var_op == Variant::OP_DIVIDE && argument_a_type.kind == DataType::BUILTIN && argument_a_type.builtin_type == Variant::INT &&
- argument_b_type.kind == DataType::BUILTIN && argument_b_type.builtin_type == Variant::INT) {
- _add_warning(GDScriptWarning::INTEGER_DIVISION, op->line);
- }
-#endif // DEBUG_ENABLED
-
- } break;
- // Ternary operators
- case OperatorNode::OP_TERNARY_IF: {
- if (op->arguments.size() != 3) {
- _set_error("Parser bug: ternary operation without 3 arguments.");
- ERR_FAIL_V(DataType());
- }
-
- DataType true_type = _reduce_node_type(op->arguments[1]);
- DataType false_type = _reduce_node_type(op->arguments[2]);
- // Check arguments[0] errors.
- _reduce_node_type(op->arguments[0]);
-
- // If types are equal, then the expression is of the same type
- // If they are compatible, return the broader type
- if (true_type == false_type || _is_type_compatible(true_type, false_type)) {
- node_type = true_type;
- } else if (_is_type_compatible(false_type, true_type)) {
- node_type = false_type;
- } else {
-#ifdef DEBUG_ENABLED
- _add_warning(GDScriptWarning::INCOMPATIBLE_TERNARY, op->line);
-#endif // DEBUG_ENABLED
- }
- } break;
- // Assignment should never happen within an expression
- case OperatorNode::OP_ASSIGN:
- case OperatorNode::OP_ASSIGN_ADD:
- case OperatorNode::OP_ASSIGN_SUB:
- case OperatorNode::OP_ASSIGN_MUL:
- case OperatorNode::OP_ASSIGN_DIV:
- case OperatorNode::OP_ASSIGN_MOD:
- case OperatorNode::OP_ASSIGN_SHIFT_LEFT:
- case OperatorNode::OP_ASSIGN_SHIFT_RIGHT:
- case OperatorNode::OP_ASSIGN_BIT_AND:
- case OperatorNode::OP_ASSIGN_BIT_OR:
- case OperatorNode::OP_ASSIGN_BIT_XOR:
- case OperatorNode::OP_INIT_ASSIGN: {
-
- _set_error("Assignment inside an expression isn't allowed (parser bug?).", op->line);
- return DataType();
-
- } break;
- case OperatorNode::OP_INDEX_NAMED: {
- if (op->arguments.size() != 2) {
- _set_error("Parser bug: named index with invalid arguments.", op->line);
- ERR_FAIL_V(DataType());
- }
- if (op->arguments[1]->type != Node::TYPE_IDENTIFIER) {
- _set_error("Parser bug: named index without identifier argument.", op->line);
- ERR_FAIL_V(DataType());
- }
-
- DataType base_type = _reduce_node_type(op->arguments[0]);
- IdentifierNode *member_id = static_cast<IdentifierNode *>(op->arguments[1]);
-
- if (base_type.has_type) {
- if (check_types && base_type.kind == DataType::BUILTIN) {
- // Variant type, just test if it's possible
- DataType result;
- switch (base_type.builtin_type) {
- case Variant::NIL:
- case Variant::DICTIONARY: {
- result.has_type = false;
- } break;
- default: {
- Callable::CallError err;
- Variant temp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
-
- bool valid = false;
- Variant res = temp.get(member_id->name.operator String(), &valid);
-
- if (valid) {
- result = _type_from_variant(res);
- } else if (check_types) {
- _set_error("Can't get index \"" + String(member_id->name.operator String()) + "\" on base \"" +
- base_type.to_string() + "\".",
- op->line);
- return DataType();
- }
- } break;
- }
- result.is_constant = false;
- node_type = result;
- } else {
- node_type = _reduce_identifier_type(&base_type, member_id->name, op->line, true);
-#ifdef DEBUG_ENABLED
- if (!node_type.has_type) {
- _mark_line_as_unsafe(op->line);
- _add_warning(GDScriptWarning::UNSAFE_PROPERTY_ACCESS, op->line, member_id->name.operator String(), base_type.to_string());
- }
-#endif // DEBUG_ENABLED
- }
- } else {
- _mark_line_as_unsafe(op->line);
- }
- if (error_set) {
- return DataType();
- }
- } break;
- case OperatorNode::OP_INDEX: {
-
- if (op->arguments[1]->type == Node::TYPE_CONSTANT) {
- ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]);
- if (cn->value.get_type() == Variant::STRING) {
- // Treat this as named indexing
-
- IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name = cn->value.operator StringName();
-
- op->op = OperatorNode::OP_INDEX_NAMED;
- op->arguments.write[1] = id;
-
- return _reduce_node_type(op);
- }
- }
+ }
+ // Leave error message to the caller who knows the context.
+ return nullptr;
+ }
- DataType base_type = _reduce_node_type(op->arguments[0]);
- DataType index_type = _reduce_node_type(op->arguments[1]);
+ IdentifierNode *type_element = parse_identifier();
- if (!base_type.has_type) {
- _mark_line_as_unsafe(op->line);
- break;
- }
+ type->type_chain.push_back(type_element);
- if (check_types && index_type.has_type) {
- if (base_type.kind == DataType::BUILTIN) {
- // Check if indexing is valid
- bool error = index_type.kind != DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
- if (!error) {
- switch (base_type.builtin_type) {
- // Expect int or real as index
- case Variant::PACKED_BYTE_ARRAY:
- case Variant::PACKED_COLOR_ARRAY:
- case Variant::PACKED_INT32_ARRAY:
- case Variant::PACKED_INT64_ARRAY:
- case Variant::PACKED_FLOAT32_ARRAY:
- case Variant::PACKED_FLOAT64_ARRAY:
- case Variant::PACKED_STRING_ARRAY:
- case Variant::PACKED_VECTOR2_ARRAY:
- case Variant::PACKED_VECTOR3_ARRAY:
- case Variant::ARRAY:
- case Variant::STRING: {
- error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
- } break;
- // Expect String only
- case Variant::RECT2:
- case Variant::PLANE:
- case Variant::QUAT:
- case Variant::AABB:
- case Variant::OBJECT: {
- error = index_type.builtin_type != Variant::STRING;
- } break;
- // Expect String or number
- case Variant::VECTOR2:
- case Variant::VECTOR3:
- case Variant::TRANSFORM2D:
- case Variant::BASIS:
- case Variant::TRANSFORM: {
- error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
- index_type.builtin_type != Variant::STRING;
- } break;
- // Expect String or int
- case Variant::COLOR: {
- error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
- } break;
- default: {
- }
- }
- }
- if (error) {
- _set_error("Invalid index type (" + index_type.to_string() + ") for base \"" + base_type.to_string() + "\".",
- op->line);
- return DataType();
- }
-
- if (op->arguments[1]->type == GDScriptParser::Node::TYPE_CONSTANT) {
- ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[1]);
- // Index is a constant, just try it if possible
- switch (base_type.builtin_type) {
- // Arrays/string have variable indexing, can't test directly
- case Variant::STRING:
- case Variant::ARRAY:
- case Variant::DICTIONARY:
- case Variant::PACKED_BYTE_ARRAY:
- case Variant::PACKED_COLOR_ARRAY:
- case Variant::PACKED_INT32_ARRAY:
- case Variant::PACKED_INT64_ARRAY:
- case Variant::PACKED_FLOAT32_ARRAY:
- case Variant::PACKED_FLOAT64_ARRAY:
- case Variant::PACKED_STRING_ARRAY:
- case Variant::PACKED_VECTOR2_ARRAY:
- case Variant::PACKED_VECTOR3_ARRAY: {
- break;
- }
- default: {
- Callable::CallError err;
- Variant temp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
-
- bool valid = false;
- Variant res = temp.get(cn->value, &valid);
-
- if (valid) {
- node_type = _type_from_variant(res);
- node_type.is_constant = false;
- } else if (check_types) {
- _set_error("Can't get index \"" + String(cn->value) + "\" on base \"" +
- base_type.to_string() + "\".",
- op->line);
- return DataType();
- }
- } break;
- }
- } else {
- _mark_line_as_unsafe(op->line);
- }
- } else if (!for_completion && (index_type.kind != DataType::BUILTIN || index_type.builtin_type != Variant::STRING)) {
- _set_error("Only strings can be used as an index in the base type \"" + base_type.to_string() + "\".", op->line);
- return DataType();
- }
- }
- if (check_types && !node_type.has_type && base_type.kind == DataType::BUILTIN) {
- // Can infer indexing type for some variant types
- DataType result;
- result.has_type = true;
- result.kind = DataType::BUILTIN;
- switch (base_type.builtin_type) {
- // Can't index at all
- case Variant::NIL:
- case Variant::BOOL:
- case Variant::INT:
- case Variant::FLOAT:
- case Variant::NODE_PATH:
- case Variant::_RID: {
- _set_error("Can't index on a value of type \"" + base_type.to_string() + "\".", op->line);
- return DataType();
- } break;
- // Return int
- case Variant::PACKED_BYTE_ARRAY:
- case Variant::PACKED_INT32_ARRAY:
- case Variant::PACKED_INT64_ARRAY: {
- result.builtin_type = Variant::INT;
- } break;
- // Return real
- case Variant::PACKED_FLOAT32_ARRAY:
- case Variant::PACKED_FLOAT64_ARRAY:
- case Variant::VECTOR2:
- case Variant::VECTOR3:
- case Variant::QUAT: {
- result.builtin_type = Variant::FLOAT;
- } break;
- // Return color
- case Variant::PACKED_COLOR_ARRAY: {
- result.builtin_type = Variant::COLOR;
- } break;
- // Return string
- case Variant::PACKED_STRING_ARRAY:
- case Variant::STRING: {
- result.builtin_type = Variant::STRING;
- } break;
- // Return Vector2
- case Variant::PACKED_VECTOR2_ARRAY:
- case Variant::TRANSFORM2D:
- case Variant::RECT2: {
- result.builtin_type = Variant::VECTOR2;
- } break;
- // Return Vector3
- case Variant::PACKED_VECTOR3_ARRAY:
- case Variant::AABB:
- case Variant::BASIS: {
- result.builtin_type = Variant::VECTOR3;
- } break;
- // Depends on the index
- case Variant::TRANSFORM:
- case Variant::PLANE:
- case Variant::COLOR:
- default: {
- result.has_type = false;
- } break;
- }
- node_type = result;
- }
- } break;
- default: {
- _set_error("Parser bug: unhandled operation.", op->line);
- ERR_FAIL_V(DataType());
- }
- }
- } break;
- default: {
+ int chain_index = 1;
+ while (match(GDScriptTokenizer::Token::PERIOD)) {
+ make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
+ if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
+ type_element = parse_identifier();
+ type->type_chain.push_back(type_element);
}
}
- node_type = _resolve_type(node_type, p_node->line);
- p_node->set_datatype(node_type);
- return node_type;
+ return type;
}
-bool GDScriptParser::_get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const {
-
- r_static = false;
- r_default_arg_count = 0;
-
- DataType original_type = p_base_type;
- ClassNode *base = nullptr;
- FunctionNode *callee = nullptr;
+#ifdef TOOLS_ENABLED
+static bool _in_codeblock(String p_line, bool p_already_in, int *r_block_begins = nullptr) {
+ int start_block = p_line.rfind("[codeblock]");
+ int end_block = p_line.rfind("[/codeblock]");
- if (p_base_type.kind == DataType::CLASS) {
- base = p_base_type.class_type;
+ if (start_block != -1 && r_block_begins) {
+ *r_block_begins = start_block;
}
- // Look up the current file (parse tree)
- while (!callee && base) {
- for (int i = 0; i < base->static_functions.size(); i++) {
- FunctionNode *func = base->static_functions[i];
- if (p_function == func->name) {
- r_static = true;
- callee = func;
- break;
- }
- }
- if (!callee && !p_base_type.is_meta_type) {
- for (int i = 0; i < base->functions.size(); i++) {
- FunctionNode *func = base->functions[i];
- if (p_function == func->name) {
- callee = func;
- break;
- }
- }
- }
- p_base_type = base->base_type;
- if (p_base_type.kind == DataType::CLASS) {
- base = p_base_type.class_type;
+ if (p_already_in) {
+ if (end_block == -1) {
+ return true;
+ } else if (start_block == -1) {
+ return false;
} else {
- break;
+ return start_block > end_block;
}
- }
-
- if (callee) {
- r_return_type = callee->get_datatype();
- for (int i = 0; i < callee->argument_types.size(); i++) {
- r_arg_types.push_back(callee->argument_types[i]);
- }
- r_default_arg_count = callee->default_values.size();
- return true;
- }
-
- // Nothing in current file, check parent script
- Ref<GDScript> base_gdscript;
- Ref<Script> base_script;
- StringName native;
- if (p_base_type.kind == DataType::GDSCRIPT) {
- base_gdscript = p_base_type.script_type;
- if (base_gdscript.is_null() || !base_gdscript->is_valid()) {
- // GDScript wasn't properly compíled, don't bother trying
+ } else {
+ if (start_block == -1) {
return false;
- }
- } else if (p_base_type.kind == DataType::SCRIPT) {
- base_script = p_base_type.script_type;
- } else if (p_base_type.kind == DataType::NATIVE) {
- native = p_base_type.native_type;
- }
-
- while (base_gdscript.is_valid()) {
- native = base_gdscript->get_instance_base_type();
-
- Map<StringName, GDScriptFunction *> funcs = base_gdscript->get_member_functions();
-
- if (funcs.has(p_function)) {
- GDScriptFunction *f = funcs[p_function];
- r_static = f->is_static();
- r_default_arg_count = f->get_default_argument_count();
- r_return_type = _type_from_gdtype(f->get_return_type());
- for (int i = 0; i < f->get_argument_count(); i++) {
- r_arg_types.push_back(_type_from_gdtype(f->get_argument_type(i)));
- }
+ } else if (end_block == -1) {
return true;
+ } else {
+ return start_block > end_block;
}
-
- base_gdscript = base_gdscript->get_base_script();
}
+}
- while (base_script.is_valid()) {
- native = base_script->get_instance_base_type();
- MethodInfo mi = base_script->get_method_info(p_function);
+bool GDScriptParser::has_comment(int p_line) {
+ return tokenizer.get_comments().has(p_line);
+}
- if (!(mi == MethodInfo())) {
- r_return_type = _type_from_property(mi.return_val, false);
- r_default_arg_count = mi.default_arguments.size();
- for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) {
- r_arg_types.push_back(_type_from_property(E->get()));
- }
- return true;
+String GDScriptParser::get_doc_comment(int p_line, bool p_single_line) {
+ const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
+ ERR_FAIL_COND_V(!comments.has(p_line), String());
+
+ if (p_single_line) {
+ if (comments[p_line].comment.begins_with("##")) {
+ return comments[p_line].comment.trim_prefix("##").strip_edges();
}
- base_script = base_script->get_base_script();
+ return "";
}
- if (native == StringName()) {
- // Empty native class, might happen in some Script implementations
- // Just ignore it
- return false;
- }
+ String doc;
-#ifdef DEBUG_METHODS_ENABLED
+ int line = p_line;
+ bool in_codeblock = false;
- // Only native remains
- if (!ClassDB::class_exists(native)) {
- native = "_" + native.operator String();
- }
- if (!ClassDB::class_exists(native)) {
- if (!check_types) return false;
- ERR_FAIL_V_MSG(false, "Parser bug: Class '" + String(native) + "' not found.");
+ while (comments.has(line - 1)) {
+ if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
+ break;
+ }
+ line--;
}
- MethodBind *method = ClassDB::get_method(native, p_function);
-
- if (!method) {
- // Try virtual methods
- List<MethodInfo> virtuals;
- ClassDB::get_virtual_methods(native, &virtuals);
-
- for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) {
- const MethodInfo &mi = E->get();
- if (mi.name == p_function) {
- r_default_arg_count = mi.default_arguments.size();
- for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) {
- r_arg_types.push_back(_type_from_property(pi->get()));
- }
- r_return_type = _type_from_property(mi.return_val, false);
- r_vararg = mi.flags & METHOD_FLAG_VARARG;
- return true;
- }
+ int codeblock_begins = 0;
+ while (comments.has(line)) {
+ if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
+ break;
}
+ String doc_line = comments[line].comment.trim_prefix("##");
- // If the base is a script, it might be trying to access members of the Script class itself
- if (original_type.is_meta_type && !(p_function == "new") && (original_type.kind == DataType::SCRIPT || original_type.kind == DataType::GDSCRIPT)) {
- method = ClassDB::get_method(original_type.script_type->get_class_name(), p_function);
+ in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
- if (method) {
- r_static = true;
- } else {
- // Try virtual methods of the script type
- virtuals.clear();
- ClassDB::get_virtual_methods(original_type.script_type->get_class_name(), &virtuals);
- for (const List<MethodInfo>::Element *E = virtuals.front(); E; E = E->next()) {
- const MethodInfo &mi = E->get();
- if (mi.name == p_function) {
- r_default_arg_count = mi.default_arguments.size();
- for (const List<PropertyInfo>::Element *pi = mi.arguments.front(); pi; pi = pi->next()) {
- r_arg_types.push_back(_type_from_property(pi->get()));
- }
- r_return_type = _type_from_property(mi.return_val, false);
- r_static = true;
- r_vararg = mi.flags & METHOD_FLAG_VARARG;
- return true;
- }
+ if (in_codeblock) {
+ int i = 0;
+ for (; i < codeblock_begins; i++) {
+ if (doc_line[i] != ' ') {
+ break;
}
- return false;
}
+ doc_line = doc_line.substr(i);
} else {
- return false;
+ doc_line = doc_line.strip_edges();
}
- }
+ String line_join = (in_codeblock) ? "\n" : " ";
- r_default_arg_count = method->get_default_argument_count();
- r_return_type = _type_from_property(method->get_return_info(), false);
- r_vararg = method->is_vararg();
-
- for (int i = 0; i < method->get_argument_count(); i++) {
- r_arg_types.push_back(_type_from_property(method->get_argument_info(i)));
+ doc = (doc.is_empty()) ? doc_line : doc + line_join + doc_line;
+ line++;
}
- return true;
-#else
- return false;
-#endif
+
+ return doc;
}
-GDScriptParser::DataType GDScriptParser::_reduce_function_call_type(const OperatorNode *p_call) {
- if (p_call->arguments.size() < 1) {
- _set_error("Parser bug: function call without enough arguments.", p_call->line);
- ERR_FAIL_V(DataType());
+void GDScriptParser::get_class_doc_comment(int p_line, String &p_brief, String &p_desc, Vector<Pair<String, String>> &p_tutorials, bool p_inner_class) {
+ const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
+ if (!comments.has(p_line)) {
+ return;
}
-
- DataType return_type;
- List<DataType> arg_types;
- int default_args_count = 0;
- int arg_count = p_call->arguments.size();
- String callee_name;
- bool is_vararg = false;
-
- switch (p_call->arguments[0]->type) {
- case GDScriptParser::Node::TYPE_TYPE: {
- // Built-in constructor, special case
- TypeNode *tn = static_cast<TypeNode *>(p_call->arguments[0]);
-
- Vector<DataType> par_types;
- par_types.resize(p_call->arguments.size() - 1);
- for (int i = 1; i < p_call->arguments.size(); i++) {
- par_types.write[i - 1] = _reduce_node_type(p_call->arguments[i]);
- }
-
- if (error_set) return DataType();
-
- // Special case: check copy constructor. Those are defined implicitly in Variant.
- if (par_types.size() == 1) {
- if (!par_types[0].has_type || (par_types[0].kind == DataType::BUILTIN && par_types[0].builtin_type == tn->vtype)) {
- DataType result;
- result.has_type = true;
- result.kind = DataType::BUILTIN;
- result.builtin_type = tn->vtype;
- return result;
- }
- }
-
- bool match = false;
- List<MethodInfo> constructors;
- Variant::get_constructor_list(tn->vtype, &constructors);
- PropertyInfo return_type2;
-
- for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) {
- MethodInfo &mi = E->get();
-
- if (p_call->arguments.size() - 1 < mi.arguments.size() - mi.default_arguments.size()) {
- continue;
- }
- if (p_call->arguments.size() - 1 > mi.arguments.size()) {
- continue;
- }
-
- bool types_match = true;
- for (int i = 0; i < par_types.size(); i++) {
- DataType arg_type;
- if (mi.arguments[i].type != Variant::NIL) {
- arg_type.has_type = true;
- arg_type.kind = mi.arguments[i].type == Variant::OBJECT ? DataType::NATIVE : DataType::BUILTIN;
- arg_type.builtin_type = mi.arguments[i].type;
- arg_type.native_type = mi.arguments[i].class_name;
- }
-
- if (!_is_type_compatible(arg_type, par_types[i], true)) {
- types_match = false;
- break;
- } else {
-#ifdef DEBUG_ENABLED
- if (arg_type.kind == DataType::BUILTIN && arg_type.builtin_type == Variant::INT && par_types[i].kind == DataType::BUILTIN && par_types[i].builtin_type == Variant::FLOAT) {
- _add_warning(GDScriptWarning::NARROWING_CONVERSION, p_call->line, Variant::get_type_name(tn->vtype));
- }
- if (par_types[i].may_yield && p_call->arguments[i + 1]->type == Node::TYPE_OPERATOR) {
- _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, p_call->line, _find_function_name(static_cast<OperatorNode *>(p_call->arguments[i + 1])));
- }
-#endif // DEBUG_ENABLED
- }
- }
-
- if (types_match) {
- match = true;
- return_type2 = mi.return_val;
- break;
- }
- }
-
- if (match) {
- return _type_from_property(return_type2, false);
- } else if (check_types) {
- String err = "No constructor of '";
- err += Variant::get_type_name(tn->vtype);
- err += "' matches the signature '";
- err += Variant::get_type_name(tn->vtype) + "(";
- for (int i = 0; i < par_types.size(); i++) {
- if (i > 0) err += ", ";
- err += par_types[i].to_string();
- }
- err += ")'.";
- _set_error(err, p_call->line, p_call->column);
- return DataType();
- }
- return DataType();
- } break;
- case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: {
- BuiltInFunctionNode *func = static_cast<BuiltInFunctionNode *>(p_call->arguments[0]);
- MethodInfo mi = GDScriptFunctions::get_info(func->function);
-
- return_type = _type_from_property(mi.return_val, false);
-
- // Check all arguments beforehand to solve warnings
- for (int i = 1; i < p_call->arguments.size(); i++) {
- _reduce_node_type(p_call->arguments[i]);
+ ERR_FAIL_COND(p_brief != "" || p_desc != "" || p_tutorials.size() != 0);
+
+ int line = p_line;
+ bool in_codeblock = false;
+ enum Mode {
+ BRIEF,
+ DESC,
+ TUTORIALS,
+ DONE,
+ };
+ Mode mode = BRIEF;
+
+ if (p_inner_class) {
+ while (comments.has(line - 1)) {
+ if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
+ break;
}
+ line--;
+ }
+ }
- // Check arguments
-
- is_vararg = mi.flags & METHOD_FLAG_VARARG;
-
- default_args_count = mi.default_arguments.size();
- callee_name = mi.name;
- arg_count -= 1;
-
- // Check each argument type
- for (List<PropertyInfo>::Element *E = mi.arguments.front(); E; E = E->next()) {
- arg_types.push_back(_type_from_property(E->get()));
- }
- } break;
- default: {
- if (p_call->op == OperatorNode::OP_CALL && p_call->arguments.size() < 2) {
- _set_error("Parser bug: self method call without enough arguments.", p_call->line);
- ERR_FAIL_V(DataType());
- }
+ int codeblock_begins = 0;
+ while (comments.has(line)) {
+ if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
+ break;
+ }
- int arg_id = p_call->op == OperatorNode::OP_CALL ? 1 : 0;
+ String title, link; // For tutorials.
+ String doc_line = comments[line++].comment.trim_prefix("##");
+ String striped_line = doc_line.strip_edges();
- if (p_call->arguments[arg_id]->type != Node::TYPE_IDENTIFIER) {
- _set_error("Parser bug: invalid function call argument.", p_call->line);
- ERR_FAIL_V(DataType());
- }
+ // Set the read mode.
+ if (striped_line.begins_with("@desc:") && p_desc == "") {
+ mode = DESC;
+ striped_line = striped_line.trim_prefix("@desc:");
+ in_codeblock = _in_codeblock(doc_line, in_codeblock);
- // Check all arguments beforehand to solve warnings
- for (int i = arg_id + 1; i < p_call->arguments.size(); i++) {
- _reduce_node_type(p_call->arguments[i]);
+ } else if (striped_line.begins_with("@tutorial")) {
+ int begin_scan = String("@tutorial").length();
+ if (begin_scan >= striped_line.length()) {
+ continue; // invalid syntax.
}
- IdentifierNode *func_id = static_cast<IdentifierNode *>(p_call->arguments[arg_id]);
- callee_name = func_id->name;
- arg_count -= 1 + arg_id;
+ if (striped_line[begin_scan] == ':') { // No title.
+ // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
+ title = "";
+ link = striped_line.trim_prefix("@tutorial:").strip_edges();
- DataType base_type;
- if (p_call->op == OperatorNode::OP_PARENT_CALL) {
- base_type = current_class->base_type;
} else {
- base_type = _reduce_node_type(p_call->arguments[0]);
- }
-
- if (!base_type.has_type || (base_type.kind == DataType::BUILTIN && base_type.builtin_type == Variant::NIL)) {
- _mark_line_as_unsafe(p_call->line);
- return DataType();
- }
-
- if (base_type.kind == DataType::BUILTIN) {
- Callable::CallError err;
- Variant tmp = Variant::construct(base_type.builtin_type, nullptr, 0, err);
-
- if (check_types) {
- if (!tmp.has_method(callee_name)) {
- _set_error("The method \"" + callee_name + "\" isn't declared on base \"" + base_type.to_string() + "\".", p_call->line);
- return DataType();
- }
-
- default_args_count = Variant::get_method_default_arguments(base_type.builtin_type, callee_name).size();
- const Vector<Variant::Type> &var_arg_types = Variant::get_method_argument_types(base_type.builtin_type, callee_name);
-
- for (int i = 0; i < var_arg_types.size(); i++) {
- DataType argtype;
- if (var_arg_types[i] != Variant::NIL) {
- argtype.has_type = true;
- argtype.kind = DataType::BUILTIN;
- argtype.builtin_type = var_arg_types[i];
- }
- arg_types.push_back(argtype);
- }
+ /* Syntax:
+ @tutorial ( The Title Here ) : http://the.url/
+ ^ open ^ close ^ colon ^ url
+ */
+ int open_bracket_pos = begin_scan, close_bracket_pos = 0;
+ while (open_bracket_pos < striped_line.length() && (striped_line[open_bracket_pos] == ' ' || striped_line[open_bracket_pos] == '\t')) {
+ open_bracket_pos++;
}
-
- bool rets = false;
- return_type.has_type = true;
- return_type.kind = DataType::BUILTIN;
- return_type.builtin_type = Variant::get_method_return_type(base_type.builtin_type, callee_name, &rets);
- // If the method returns, but it might return any type, (Variant::NIL), pretend we don't know the type.
- // At least make sure we know that it returns
- if (rets && return_type.builtin_type == Variant::NIL) {
- return_type.has_type = false;
+ if (open_bracket_pos == striped_line.length() || striped_line[open_bracket_pos++] != '(') {
+ continue; // invalid syntax.
}
- break;
- }
-
- DataType original_type = base_type;
- bool is_initializer = callee_name == "new";
- bool is_static = false;
- bool valid = false;
-
- if (is_initializer && original_type.is_meta_type) {
- // Try to check it as initializer
- base_type = original_type;
- callee_name = "_init";
- base_type.is_meta_type = false;
-
- valid = _get_function_signature(base_type, callee_name, return_type, arg_types,
- default_args_count, is_static, is_vararg);
-
- return_type = original_type;
- return_type.is_meta_type = false;
-
- valid = true; // There's always an initializer, we can assume this is true
- }
-
- if (!valid) {
- base_type = original_type;
- return_type = DataType();
- valid = _get_function_signature(base_type, callee_name, return_type, arg_types,
- default_args_count, is_static, is_vararg);
- }
-
- if (!valid) {
-#ifdef DEBUG_ENABLED
- if (p_call->arguments[0]->type == Node::TYPE_SELF) {
- _set_error("The method \"" + callee_name + "\" isn't declared in the current class.", p_call->line);
- return DataType();
+ close_bracket_pos = open_bracket_pos;
+ while (close_bracket_pos < striped_line.length() && striped_line[close_bracket_pos] != ')') {
+ close_bracket_pos++;
}
- DataType tmp_type;
- valid = _get_member_type(original_type, func_id->name, tmp_type);
- if (valid) {
- if (tmp_type.is_constant) {
- _add_warning(GDScriptWarning::CONSTANT_USED_AS_FUNCTION, p_call->line, callee_name, original_type.to_string());
- } else {
- _add_warning(GDScriptWarning::PROPERTY_USED_AS_FUNCTION, p_call->line, callee_name, original_type.to_string());
- }
+ if (close_bracket_pos == striped_line.length()) {
+ continue; // invalid syntax.
}
- _add_warning(GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->line, callee_name, original_type.to_string());
- _mark_line_as_unsafe(p_call->line);
-#endif // DEBUG_ENABLED
- return DataType();
- }
-
-#ifdef DEBUG_ENABLED
- if (current_function && !for_completion && !is_static && p_call->arguments[0]->type == Node::TYPE_SELF && current_function->_static) {
- _set_error("Can't call non-static function from a static function.", p_call->line);
- return DataType();
- }
-
- if (check_types && !is_static && !is_initializer && base_type.is_meta_type) {
- _set_error("Non-static function \"" + String(callee_name) + "\" can only be called from an instance.", p_call->line);
- return DataType();
- }
- // Check signal emission for warnings
- if (callee_name == "emit_signal" && p_call->op == OperatorNode::OP_CALL && p_call->arguments[0]->type == Node::TYPE_SELF && p_call->arguments.size() >= 3 && p_call->arguments[2]->type == Node::TYPE_CONSTANT) {
- ConstantNode *sig = static_cast<ConstantNode *>(p_call->arguments[2]);
- String emitted = sig->value.get_type() == Variant::STRING ? sig->value.operator String() : "";
- for (int i = 0; i < current_class->_signals.size(); i++) {
- if (current_class->_signals[i].name == emitted) {
- current_class->_signals.write[i].emissions += 1;
- break;
- }
+ int colon_pos = close_bracket_pos + 1;
+ while (colon_pos < striped_line.length() && (striped_line[colon_pos] == ' ' || striped_line[colon_pos] == '\t')) {
+ colon_pos++;
+ }
+ if (colon_pos == striped_line.length() || striped_line[colon_pos++] != ':') {
+ continue; // invalid syntax.
}
- }
-#endif // DEBUG_ENABLED
- } break;
- }
-
-#ifdef DEBUG_ENABLED
- if (!check_types) {
- return return_type;
- }
-
- if (arg_count < arg_types.size() - default_args_count) {
- _set_error("Too few arguments for \"" + callee_name + "()\" call. Expected at least " + itos(arg_types.size() - default_args_count) + ".", p_call->line);
- return return_type;
- }
- if (!is_vararg && arg_count > arg_types.size()) {
- _set_error("Too many arguments for \"" + callee_name + "()\" call. Expected at most " + itos(arg_types.size()) + ".", p_call->line);
- return return_type;
- }
- int arg_diff = p_call->arguments.size() - arg_count;
- for (int i = arg_diff; i < p_call->arguments.size(); i++) {
- DataType par_type = _reduce_node_type(p_call->arguments[i]);
+ title = striped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
+ link = striped_line.substr(colon_pos).strip_edges();
+ }
- if ((i - arg_diff) >= arg_types.size()) {
+ mode = TUTORIALS;
+ in_codeblock = false;
+ } else if (striped_line.is_empty()) {
continue;
- }
-
- DataType arg_type = arg_types[i - arg_diff];
-
- if (!par_type.has_type) {
- _mark_line_as_unsafe(p_call->line);
- if (par_type.may_yield && p_call->arguments[i]->type == Node::TYPE_OPERATOR) {
- _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, p_call->line, _find_function_name(static_cast<OperatorNode *>(p_call->arguments[i])));
- }
- } else if (!_is_type_compatible(arg_types[i - arg_diff], par_type, true)) {
- // Supertypes are acceptable for dynamic compliance
- if (!_is_type_compatible(par_type, arg_types[i - arg_diff])) {
- _set_error("At \"" + callee_name + "()\" call, argument " + itos(i - arg_diff + 1) + ". Assigned type (" +
- par_type.to_string() + ") doesn't match the function argument's type (" +
- arg_types[i - arg_diff].to_string() + ").",
- p_call->line);
- return DataType();
- } else {
- _mark_line_as_unsafe(p_call->line);
- }
} else {
- if (arg_type.kind == DataType::BUILTIN && arg_type.builtin_type == Variant::INT && par_type.kind == DataType::BUILTIN && par_type.builtin_type == Variant::FLOAT) {
- _add_warning(GDScriptWarning::NARROWING_CONVERSION, p_call->line, callee_name);
+ // Tutorial docs are single line, we need a @tag after it.
+ if (mode == TUTORIALS) {
+ mode = DONE;
}
- }
- }
-#endif // DEBUG_ENABLED
-
- return return_type;
-}
-
-bool GDScriptParser::_get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type) const {
- DataType base_type = p_base_type;
-
- // Check classes in current file
- ClassNode *base = nullptr;
- if (base_type.kind == DataType::CLASS) {
- base = base_type.class_type;
- }
-
- while (base) {
- if (base->constant_expressions.has(p_member)) {
- r_member_type = base->constant_expressions[p_member].expression->get_datatype();
- return true;
+ in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
}
- if (!base_type.is_meta_type) {
- for (int i = 0; i < base->variables.size(); i++) {
- if (base->variables[i].identifier == p_member) {
- r_member_type = base->variables[i].data_type;
- base->variables.write[i].usages += 1;
- return true;
+ if (in_codeblock) {
+ int i = 0;
+ for (; i < codeblock_begins; i++) {
+ if (doc_line[i] != ' ') {
+ break;
}
}
+ doc_line = doc_line.substr(i);
} else {
- for (int i = 0; i < base->subclasses.size(); i++) {
- ClassNode *c = base->subclasses[i];
- if (c->name == p_member) {
- DataType class_type;
- class_type.has_type = true;
- class_type.is_constant = true;
- class_type.is_meta_type = true;
- class_type.kind = DataType::CLASS;
- class_type.class_type = c;
- r_member_type = class_type;
- return true;
- }
- }
+ doc_line = striped_line;
}
+ String line_join = (in_codeblock) ? "\n" : " ";
- base_type = base->base_type;
- if (base_type.kind == DataType::CLASS) {
- base = base_type.class_type;
- } else {
- break;
+ switch (mode) {
+ case BRIEF:
+ p_brief = (p_brief.length() == 0) ? doc_line : p_brief + line_join + doc_line;
+ break;
+ case DESC:
+ p_desc = (p_desc.length() == 0) ? doc_line : p_desc + line_join + doc_line;
+ break;
+ case TUTORIALS:
+ p_tutorials.append(Pair<String, String>(title, link));
+ break;
+ case DONE:
+ return;
}
}
+}
+#endif // TOOLS_ENABLED
+
+GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
+ // Function table for expression parsing.
+ // clang-format destroys the alignment here, so turn off for the table.
+ /* clang-format off */
+ static ParseRule rules[] = {
+ // PREFIX INFIX PRECEDENCE (for infix)
+ { nullptr, nullptr, PREC_NONE }, // EMPTY,
+ // Basic
+ { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
+ { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
+ { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
+ // Comparison
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
+ // Logical
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
+ { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // NOT,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
+ { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
+ // Bitwise
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
+ { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
+ // Math
+ { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
+ { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
+ // Assignment
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
+ { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
+ // Control flow
+ { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
+ { nullptr, nullptr, PREC_NONE }, // ELIF,
+ { nullptr, nullptr, PREC_NONE }, // ELSE,
+ { nullptr, nullptr, PREC_NONE }, // FOR,
+ { nullptr, nullptr, PREC_NONE }, // WHILE,
+ { nullptr, nullptr, PREC_NONE }, // BREAK,
+ { nullptr, nullptr, PREC_NONE }, // CONTINUE,
+ { nullptr, nullptr, PREC_NONE }, // PASS,
+ { nullptr, nullptr, PREC_NONE }, // RETURN,
+ { nullptr, nullptr, PREC_NONE }, // MATCH,
+ // Keywords
+ { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
+ { nullptr, nullptr, PREC_NONE }, // ASSERT,
+ { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
+ { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
+ { nullptr, nullptr, PREC_NONE }, // CLASS,
+ { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
+ { nullptr, nullptr, PREC_NONE }, // CONST,
+ { nullptr, nullptr, PREC_NONE }, // ENUM,
+ { nullptr, nullptr, PREC_NONE }, // EXTENDS,
+ { nullptr, nullptr, PREC_NONE }, // FUNC,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
+ { nullptr, &GDScriptParser::parse_binary_operator, PREC_TYPE_TEST }, // IS,
+ { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
+ { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
+ { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
+ { nullptr, nullptr, PREC_NONE }, // SIGNAL,
+ { nullptr, nullptr, PREC_NONE }, // STATIC,
+ { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
+ { nullptr, nullptr, PREC_NONE }, // TRAIT,
+ { nullptr, nullptr, PREC_NONE }, // VAR,
+ { nullptr, nullptr, PREC_NONE }, // VOID,
+ { nullptr, nullptr, PREC_NONE }, // YIELD,
+ // Punctuation
+ { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
+ { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
+ { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
+ { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
+ { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
+ { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
+ { nullptr, nullptr, PREC_NONE }, // COMMA,
+ { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
+ { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
+ { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
+ { nullptr, nullptr, PREC_NONE }, // COLON,
+ { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
+ { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
+ { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
+ // Whitespace
+ { nullptr, nullptr, PREC_NONE }, // NEWLINE,
+ { nullptr, nullptr, PREC_NONE }, // INDENT,
+ { nullptr, nullptr, PREC_NONE }, // DEDENT,
+ // Constants
+ { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
+ { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
+ { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
+ { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
+ // Error message improvement
+ { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
+ { nullptr, nullptr, PREC_NONE }, // BACKTICK,
+ { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
+ // Special
+ { nullptr, nullptr, PREC_NONE }, // ERROR,
+ { nullptr, nullptr, PREC_NONE }, // TK_EOF,
+ };
+ /* clang-format on */
+ // Avoid desync.
+ static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
+
+ // Let's assume this this never invalid, since nothing generates a TK_MAX.
+ return &rules[p_token_type];
+}
- Ref<GDScript> gds;
- if (base_type.kind == DataType::GDSCRIPT) {
- gds = base_type.script_type;
- if (gds.is_null() || !gds->is_valid()) {
- // GDScript wasn't properly compíled, don't bother trying
- return false;
- }
+bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
+ if (locals_indices.has(p_name)) {
+ return true;
}
-
- Ref<Script> scr;
- if (base_type.kind == DataType::SCRIPT) {
- scr = base_type.script_type;
+ if (parent_block != nullptr) {
+ return parent_block->has_local(p_name);
}
+ return false;
+}
- StringName native;
- if (base_type.kind == DataType::NATIVE) {
- native = base_type.native_type;
+const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
+ if (locals_indices.has(p_name)) {
+ return locals[locals_indices[p_name]];
}
-
- // Check GDScripts
- while (gds.is_valid()) {
- if (gds->get_constants().has(p_member)) {
- Variant c = gds->get_constants()[p_member];
- r_member_type = _type_from_variant(c);
- return true;
- }
-
- if (!base_type.is_meta_type) {
- if (gds->get_members().has(p_member)) {
- r_member_type = _type_from_gdtype(gds->get_member_type(p_member));
- return true;
- }
- }
-
- native = gds->get_instance_base_type();
- if (gds->get_base_script().is_valid()) {
- gds = gds->get_base_script();
- scr = gds->get_base_script();
- bool is_meta = base_type.is_meta_type;
- base_type = _type_from_variant(scr.operator Variant());
- base_type.is_meta_type = is_meta;
- } else {
- break;
- }
+ if (parent_block != nullptr) {
+ return parent_block->get_local(p_name);
}
+ return empty;
+}
-#define IS_USAGE_MEMBER(m_usage) (!(m_usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_SUBGROUP | PROPERTY_USAGE_CATEGORY)))
+bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) const {
+ return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
+}
- // Check other script types
- while (scr.is_valid()) {
- Map<StringName, Variant> constants;
- scr->get_constants(&constants);
- if (constants.has(p_member)) {
- r_member_type = _type_from_variant(constants[p_member]);
- return true;
- }
+bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
+ return (info->target_kind & p_target_kinds) > 0;
+}
- List<PropertyInfo> properties;
- scr->get_script_property_list(&properties);
- for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) {
- r_member_type = _type_from_property(E->get());
- return true;
- }
- }
+bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
+ ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
- base_type = _type_from_variant(scr.operator Variant());
- native = scr->get_instance_base_type();
- scr = scr->get_base_script();
- }
+ const MethodInfo &info = valid_annotations[p_annotation->name].info;
- if (native == StringName()) {
- // Empty native class, might happen in some Script implementations
- // Just ignore it
+ if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
+ push_error(vformat(R"(Annotation "%s" requires at most %d arguments, but %d were given.)", p_annotation->name, info.arguments.size(), p_annotation->arguments.size()));
return false;
}
- // Check ClassDB
- if (!ClassDB::class_exists(native)) {
- native = "_" + native.operator String();
- }
- if (!ClassDB::class_exists(native)) {
- if (!check_types) return false;
- ERR_FAIL_V_MSG(false, "Parser bug: Class \"" + String(native) + "\" not found.");
+ if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
+ push_error(vformat(R"(Annotation "%s" requires at least %d arguments, but %d were given.)", p_annotation->name, info.arguments.size() - info.default_arguments.size(), p_annotation->arguments.size()));
+ return false;
}
- bool valid = false;
- ClassDB::get_integer_constant(native, p_member, &valid);
- if (valid) {
- DataType ct;
- ct.has_type = true;
- ct.is_constant = true;
- ct.kind = DataType::BUILTIN;
- ct.builtin_type = Variant::INT;
- r_member_type = ct;
- return true;
- }
+ const List<PropertyInfo>::Element *E = info.arguments.front();
+ for (int i = 0; i < p_annotation->arguments.size(); i++) {
+ ExpressionNode *argument = p_annotation->arguments[i];
+ const PropertyInfo &parameter = E->get();
- if (!base_type.is_meta_type) {
- List<PropertyInfo> properties;
- ClassDB::get_property_list(native, &properties);
- for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) {
- // Check if a getter exists
- StringName getter_name = ClassDB::get_property_getter(native, p_member);
- if (getter_name != StringName()) {
- // Use the getter return type
-#ifdef DEBUG_METHODS_ENABLED
- MethodBind *getter_method = ClassDB::get_method(native, getter_name);
- if (getter_method) {
- r_member_type = _type_from_property(getter_method->get_return_info());
- } else {
- r_member_type = DataType();
- }
-#else
- r_member_type = DataType();
-#endif
- } else {
- r_member_type = _type_from_property(E->get());
- }
- return true;
- }
+ if (E->next() != nullptr) {
+ E = E->next();
}
- }
- // If the base is a script, it might be trying to access members of the Script class itself
- if (p_base_type.is_meta_type && (p_base_type.kind == DataType::SCRIPT || p_base_type.kind == DataType::GDSCRIPT)) {
- native = p_base_type.script_type->get_class_name();
- ClassDB::get_integer_constant(native, p_member, &valid);
- if (valid) {
- DataType ct;
- ct.has_type = true;
- ct.is_constant = true;
- ct.kind = DataType::BUILTIN;
- ct.builtin_type = Variant::INT;
- r_member_type = ct;
- return true;
- }
-
- List<PropertyInfo> properties;
- ClassDB::get_property_list(native, &properties);
- for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().name == p_member && IS_USAGE_MEMBER(E->get().usage)) {
- // Check if a getter exists
- StringName getter_name = ClassDB::get_property_getter(native, p_member);
- if (getter_name != StringName()) {
- // Use the getter return type
-#ifdef DEBUG_METHODS_ENABLED
- MethodBind *getter_method = ClassDB::get_method(native, getter_name);
- if (getter_method) {
- r_member_type = _type_from_property(getter_method->get_return_info());
- } else {
- r_member_type = DataType();
+ switch (parameter.type) {
+ case Variant::STRING:
+ case Variant::STRING_NAME:
+ case Variant::NODE_PATH:
+ // Allow "quote-less strings", as long as they are recognized as identifiers.
+ if (argument->type == Node::IDENTIFIER) {
+ IdentifierNode *string = static_cast<IdentifierNode *>(argument);
+ Callable::CallError error;
+ Vector<Variant> args = varray(string->name);
+ const Variant *name = args.ptr();
+ Variant r;
+ Variant::construct(parameter.type, r, &(name), 1, error);
+ p_annotation->resolved_arguments.push_back(r);
+ if (error.error != Callable::CallError::CALL_OK) {
+ push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
+ p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
+ return false;
}
-#else
- r_member_type = DataType();
-#endif
- } else {
- r_member_type = _type_from_property(E->get());
+ break;
+ }
+ [[fallthrough]];
+ default: {
+ if (argument->type != Node::LITERAL) {
+ push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
+ return false;
}
- return true;
+
+ Variant value = static_cast<LiteralNode *>(argument)->value;
+ if (!Variant::can_convert_strict(value.get_type(), parameter.type)) {
+ push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
+ return false;
+ }
+ Callable::CallError error;
+ const Variant *args = &value;
+ Variant r;
+ Variant::construct(parameter.type, r, &(args), 1, error);
+ p_annotation->resolved_arguments.push_back(r);
+ if (error.error != Callable::CallError::CALL_OK) {
+ push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
+ p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
+ return false;
+ }
+ break;
}
}
}
-#undef IS_USAGE_MEMBER
- return false;
+ return true;
}
-GDScriptParser::DataType GDScriptParser::_reduce_identifier_type(const DataType *p_base_type, const StringName &p_identifier, int p_line, bool p_is_indexing) {
+bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
+ this->_is_tool = true;
+ return true;
+}
- if (p_base_type && !p_base_type->has_type) {
- return DataType();
- }
+bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
+ ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
+ ClassNode *p_class = static_cast<ClassNode *>(p_node);
+ p_class->icon_path = p_annotation->resolved_arguments[0];
+ return true;
+}
- DataType base_type;
- DataType member_type;
+bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
+ ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
- if (!p_base_type) {
- base_type.has_type = true;
- base_type.is_constant = true;
- base_type.kind = DataType::CLASS;
- base_type.class_type = current_class;
- } else {
- base_type = DataType(*p_base_type);
+ VariableNode *variable = static_cast<VariableNode *>(p_node);
+ if (variable->onready) {
+ push_error(R"("@onready" annotation can only be used once per variable.)");
+ return false;
}
+ variable->onready = true;
+ current_class->onready_used = true;
+ return true;
+}
- if (_get_member_type(base_type, p_identifier, member_type)) {
- return member_type;
- }
+template <PropertyHint t_hint, Variant::Type t_type>
+bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
+ ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
- if (p_is_indexing) {
- // Don't look for globals since this is an indexed identifier
- return DataType();
+ VariableNode *variable = static_cast<VariableNode *>(p_node);
+ if (variable->exported) {
+ push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
+ return false;
}
- if (!p_base_type) {
- // Possibly this is a global, check before failing
-
- if (ClassDB::class_exists(p_identifier) || ClassDB::class_exists("_" + p_identifier.operator String())) {
- DataType result;
- result.has_type = true;
- result.is_constant = true;
- result.is_meta_type = true;
- if (Engine::get_singleton()->has_singleton(p_identifier) || Engine::get_singleton()->has_singleton("_" + p_identifier.operator String())) {
- result.is_meta_type = false;
- }
- result.kind = DataType::NATIVE;
- result.native_type = p_identifier;
- return result;
- }
-
- ClassNode *outer_class = current_class;
- while (outer_class) {
- if (outer_class->name == p_identifier) {
- DataType result;
- result.has_type = true;
- result.is_constant = true;
- result.is_meta_type = true;
- result.kind = DataType::CLASS;
- result.class_type = outer_class;
- return result;
- }
- if (outer_class->constant_expressions.has(p_identifier)) {
- return outer_class->constant_expressions[p_identifier].type;
- }
- for (int i = 0; i < outer_class->subclasses.size(); i++) {
- if (outer_class->subclasses[i] == current_class) {
- continue;
- }
- if (outer_class->subclasses[i]->name == p_identifier) {
- DataType result;
- result.has_type = true;
- result.is_constant = true;
- result.is_meta_type = true;
- result.kind = DataType::CLASS;
- result.class_type = outer_class->subclasses[i];
- return result;
- }
- }
- outer_class = outer_class->owner;
- }
-
- if (ScriptServer::is_global_class(p_identifier)) {
- Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier));
- if (scr.is_valid()) {
- DataType result;
- result.has_type = true;
- result.script_type = scr;
- result.is_constant = true;
- result.is_meta_type = true;
- Ref<GDScript> gds = scr;
- if (gds.is_valid()) {
- if (!gds->is_valid()) {
- _set_error("The class \"" + p_identifier + "\" couldn't be fully loaded (script error or cyclic dependency).");
- return DataType();
- }
- result.kind = DataType::GDSCRIPT;
- } else {
- result.kind = DataType::SCRIPT;
- }
- return result;
- }
- _set_error("The class \"" + p_identifier + "\" was found in global scope, but its script couldn't be loaded.");
- return DataType();
- }
-
- if (GDScriptLanguage::get_singleton()->get_global_map().has(p_identifier)) {
- int idx = GDScriptLanguage::get_singleton()->get_global_map()[p_identifier];
- Variant g = GDScriptLanguage::get_singleton()->get_global_array()[idx];
- return _type_from_variant(g);
- }
-
- if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(p_identifier)) {
- Variant g = GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier];
- return _type_from_variant(g);
- }
-
- // Non-tool singletons aren't loaded, check project settings
- List<PropertyInfo> props;
- ProjectSettings::get_singleton()->get_property_list(&props);
+ variable->exported = true;
+ // TODO: Improving setting type, especially for range hints, which can be int or float.
+ variable->export_info.type = t_type;
+ variable->export_info.hint = t_hint;
- for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- String s = E->get().name;
- if (!s.begins_with("autoload/")) {
- continue;
+ if (p_annotation->name == "@export") {
+ if (variable->datatype_specifier == nullptr) {
+ if (variable->initializer == nullptr) {
+ push_error(R"(Cannot use "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
+ return false;
}
- String name = s.get_slice("/", 1);
- if (name == p_identifier) {
- String script = ProjectSettings::get_singleton()->get(s);
- if (script.begins_with("*")) {
- script = script.right(1);
- }
- if (!script.begins_with("res://")) {
- script = "res://" + script;
- }
- Ref<Script> singleton = ResourceLoader::load(script);
- if (singleton.is_valid()) {
- DataType result;
- result.has_type = true;
- result.is_constant = true;
- result.script_type = singleton;
-
- Ref<GDScript> gds = singleton;
- if (gds.is_valid()) {
- if (!gds->is_valid()) {
- _set_error("Couldn't fully load the singleton script \"" + p_identifier + "\" (possible cyclic reference or parse error).", p_line);
- return DataType();
- }
- result.kind = DataType::GDSCRIPT;
- } else {
- result.kind = DataType::SCRIPT;
- }
- }
+ if (variable->initializer->type != Node::LITERAL) {
+ push_error(R"(To use "@export" annotation with type-less variable, the default value must be a literal.)", p_annotation);
+ return false;
}
- }
-
- // This means looking in the current class, which type is always known
- _set_error("The identifier \"" + p_identifier.operator String() + "\" isn't declared in the current scope.", p_line);
+ variable->export_info.type = static_cast<LiteralNode *>(variable->initializer)->value.get_type();
+ } // else: Actual type will be set by the analyzer, which can infer the proper type.
}
-#ifdef DEBUG_ENABLED
- {
- DataType tmp_type;
- List<DataType> arg_types;
- int argcount;
- bool _static;
- bool vararg;
- if (_get_function_signature(base_type, p_identifier, tmp_type, arg_types, argcount, _static, vararg)) {
- _add_warning(GDScriptWarning::FUNCTION_USED_AS_PROPERTY, p_line, p_identifier.operator String(), base_type.to_string());
+ String hint_string;
+ for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
+ if (i > 0) {
+ hint_string += ",";
}
+ hint_string += String(p_annotation->resolved_arguments[i]);
}
-#endif // DEBUG_ENABLED
- _mark_line_as_unsafe(p_line);
- return DataType();
-}
+ variable->export_info.hint_string = hint_string;
-void GDScriptParser::_check_class_level_types(ClassNode *p_class) {
-
- // Names of internal object properties that we check to avoid overriding them.
- // "__meta__" could also be in here, but since it doesn't really affect object metadata,
- // it is okay to override it on script.
- StringName script_name = CoreStringNames::get_singleton()->_script;
+ return true;
+}
- _mark_line_as_safe(p_class->line);
+bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
+ ERR_FAIL_V_MSG(false, "Not implemented.");
+}
- // Constants
- for (Map<StringName, ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
- ClassNode::Constant &c = E->get();
- _mark_line_as_safe(c.expression->line);
- DataType cont = _resolve_type(c.type, c.expression->line);
- DataType expr = _resolve_type(c.expression->get_datatype(), c.expression->line);
+template <MultiplayerAPI::RPCMode t_mode>
+bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) {
+ ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE && p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to variables and functions.)", p_annotation->name));
- if (check_types && !_is_type_compatible(cont, expr)) {
- _set_error("The constant value type (" + expr.to_string() + ") isn't compatible with declared type (" + cont.to_string() + ").",
- c.expression->line);
- return;
+ switch (p_node->type) {
+ case Node::VARIABLE: {
+ VariableNode *variable = static_cast<VariableNode *>(p_node);
+ if (variable->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) {
+ push_error(R"(RPC annotations can only be used once per variable.)", p_annotation);
+ }
+ variable->rpc_mode = t_mode;
+ break;
}
-
- expr.is_constant = true;
- c.type = expr;
- c.expression->set_datatype(expr);
-
- DataType tmp;
- const StringName &constant_name = E->key();
- if (constant_name == script_name || _get_member_type(p_class->base_type, constant_name, tmp)) {
- _set_error("The member \"" + String(constant_name) + "\" already exists in a parent class.", c.expression->line);
- return;
+ case Node::FUNCTION: {
+ FunctionNode *function = static_cast<FunctionNode *>(p_node);
+ if (function->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) {
+ push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
+ }
+ function->rpc_mode = t_mode;
+ break;
}
+ default:
+ return false; // Unreachable.
}
- // Function declarations
- for (int i = 0; i < p_class->static_functions.size(); i++) {
- _check_function_types(p_class->static_functions[i]);
- if (error_set) return;
- }
+ return true;
+}
- for (int i = 0; i < p_class->functions.size(); i++) {
- _check_function_types(p_class->functions[i]);
- if (error_set) return;
+GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
+ switch (type) {
+ case CONSTANT:
+ return constant->get_datatype();
+ case VARIABLE:
+ return variable->get_datatype();
+ case PARAMETER:
+ return parameter->get_datatype();
+ case FOR_VARIABLE:
+ case PATTERN_BIND:
+ return bind->get_datatype();
+ case UNDEFINED:
+ return DataType();
}
+ return DataType();
+}
- // Class variables
- for (int i = 0; i < p_class->variables.size(); i++) {
- ClassNode::Member &v = p_class->variables.write[i];
-
- DataType tmp;
- if (v.identifier == script_name || _get_member_type(p_class->base_type, v.identifier, tmp)) {
- _set_error("The member \"" + String(v.identifier) + "\" already exists in a parent class.", v.line);
- return;
- }
-
- _mark_line_as_safe(v.line);
- v.data_type = _resolve_type(v.data_type, v.line);
-
- if (v.expression) {
- DataType expr_type = _reduce_node_type(v.expression);
-
- if (check_types && !_is_type_compatible(v.data_type, expr_type)) {
- // Try supertype test
- if (_is_type_compatible(expr_type, v.data_type)) {
- _mark_line_as_unsafe(v.line);
- } else {
- // Try with implicit conversion
- if (v.data_type.kind != DataType::BUILTIN || !_is_type_compatible(v.data_type, expr_type, true)) {
- _set_error("The assigned expression's type (" + expr_type.to_string() + ") doesn't match the variable's type (" +
- v.data_type.to_string() + ").",
- v.line);
- return;
- }
-
- // Replace assignment with implicit conversion
- BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>();
- convert->line = v.line;
- convert->function = GDScriptFunctions::TYPE_CONVERT;
-
- ConstantNode *tgt_type = alloc_node<ConstantNode>();
- tgt_type->line = v.line;
- tgt_type->value = (int)v.data_type.builtin_type;
-
- OperatorNode *convert_call = alloc_node<OperatorNode>();
- convert_call->line = v.line;
- convert_call->op = OperatorNode::OP_CALL;
- convert_call->arguments.push_back(convert);
- convert_call->arguments.push_back(v.expression);
- convert_call->arguments.push_back(tgt_type);
+String GDScriptParser::SuiteNode::Local::get_name() const {
+ String name;
+ switch (type) {
+ case SuiteNode::Local::PARAMETER:
+ name = "parameter";
+ break;
+ case SuiteNode::Local::CONSTANT:
+ name = "constant";
+ break;
+ case SuiteNode::Local::VARIABLE:
+ name = "variable";
+ break;
+ case SuiteNode::Local::FOR_VARIABLE:
+ name = "for loop iterator";
+ break;
+ case SuiteNode::Local::PATTERN_BIND:
+ name = "pattern_bind";
+ break;
+ case SuiteNode::Local::UNDEFINED:
+ name = "<undefined>";
+ break;
+ }
+ return name;
+}
- v.expression = convert_call;
- v.initial_assignment->arguments.write[1] = convert_call;
- }
+String GDScriptParser::DataType::to_string() const {
+ switch (kind) {
+ case VARIANT:
+ return "Variant";
+ case BUILTIN:
+ if (builtin_type == Variant::NIL) {
+ return "null";
}
-
- if (v.data_type.infer_type) {
- if (!expr_type.has_type) {
- _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", v.line);
- return;
- }
- v.data_type = expr_type;
- v.data_type.is_constant = false;
+ return Variant::get_type_name(builtin_type);
+ case NATIVE:
+ if (is_meta_type) {
+ return GDScriptNativeClass::get_class_static();
}
- }
-
- // Check export hint
- if (v.data_type.has_type && v._export.type != Variant::NIL) {
- DataType export_type = _type_from_property(v._export);
- if (!_is_type_compatible(v.data_type, export_type, true)) {
- _set_error("The export hint's type (" + export_type.to_string() + ") doesn't match the variable's type (" +
- v.data_type.to_string() + ").",
- v.line);
- return;
+ return native_type.operator String();
+ case CLASS:
+ if (is_meta_type) {
+ return GDScript::get_class_static();
}
- }
-
- // Setter and getter
- if (v.setter == StringName() && v.getter == StringName()) continue;
-
- bool found_getter = false;
- bool found_setter = false;
- for (int j = 0; j < p_class->functions.size(); j++) {
- if (v.setter == p_class->functions[j]->name) {
- found_setter = true;
- FunctionNode *setter = p_class->functions[j];
-
- if (setter->get_required_argument_count() != 1 &&
- !(setter->get_required_argument_count() == 0 && setter->default_values.size() > 0)) {
- _set_error("The setter function needs to receive exactly 1 argument. See \"" + setter->name +
- "()\" definition at line " + itos(setter->line) + ".",
- v.line);
- return;
- }
- if (!_is_type_compatible(v.data_type, setter->argument_types[0])) {
- _set_error("The setter argument's type (" + setter->argument_types[0].to_string() +
- ") doesn't match the variable's type (" + v.data_type.to_string() + "). See \"" +
- setter->name + "()\" definition at line " + itos(setter->line) + ".",
- v.line);
- return;
- }
- continue;
+ if (class_type->identifier != nullptr) {
+ return class_type->identifier->name.operator String();
}
- if (v.getter == p_class->functions[j]->name) {
- found_getter = true;
- FunctionNode *getter = p_class->functions[j];
-
- if (getter->get_required_argument_count() != 0) {
- _set_error("The getter function can't receive arguments. See \"" + getter->name +
- "()\" definition at line " + itos(getter->line) + ".",
- v.line);
- return;
- }
- if (!_is_type_compatible(v.data_type, getter->get_datatype())) {
- _set_error("The getter return type (" + getter->get_datatype().to_string() +
- ") doesn't match the variable's type (" + v.data_type.to_string() +
- "). See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".",
- v.line);
- return;
- }
+ return class_type->fqcn;
+ case SCRIPT: {
+ if (is_meta_type) {
+ return script_type->get_class_name().operator String();
}
- if (found_getter && found_setter) break;
- }
-
- if ((found_getter || v.getter == StringName()) && (found_setter || v.setter == StringName())) continue;
-
- // Check for static functions
- for (int j = 0; j < p_class->static_functions.size(); j++) {
- if (v.setter == p_class->static_functions[j]->name) {
- FunctionNode *setter = p_class->static_functions[j];
- _set_error("The setter can't be a static function. See \"" + setter->name + "()\" definition at line " + itos(setter->line) + ".", v.line);
- return;
+ String name = script_type->get_name();
+ if (!name.is_empty()) {
+ return name;
}
- if (v.getter == p_class->static_functions[j]->name) {
- FunctionNode *getter = p_class->static_functions[j];
- _set_error("The getter can't be a static function. See \"" + getter->name + "()\" definition at line " + itos(getter->line) + ".", v.line);
- return;
+ name = script_path;
+ if (!name.is_empty()) {
+ return name;
}
+ return native_type.operator String();
}
-
- if (!found_setter && v.setter != StringName()) {
- _set_error("The setter function isn't defined.", v.line);
- return;
- }
-
- if (!found_getter && v.getter != StringName()) {
- _set_error("The getter function isn't defined.", v.line);
- return;
- }
+ case ENUM:
+ return enum_type.operator String() + " (enum)";
+ case ENUM_VALUE:
+ return enum_type.operator String() + " (enum value)";
+ case UNRESOLVED:
+ return "<unresolved type>";
}
- // Inner classes
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- current_class = p_class->subclasses[i];
- _check_class_level_types(current_class);
- if (error_set) return;
- current_class = p_class;
- }
+ ERR_FAIL_V_MSG("<unresolved type", "Kind set outside the enum range.");
}
-void GDScriptParser::_check_function_types(FunctionNode *p_function) {
+/*---------- PRETTY PRINT FOR DEBUG ----------*/
- p_function->return_type = _resolve_type(p_function->return_type, p_function->line);
+#ifdef DEBUG_ENABLED
- // Arguments
- int defaults_ofs = p_function->arguments.size() - p_function->default_values.size();
- for (int i = 0; i < p_function->arguments.size(); i++) {
- if (i < defaults_ofs) {
- p_function->argument_types.write[i] = _resolve_type(p_function->argument_types[i], p_function->line);
+void GDScriptParser::TreePrinter::increase_indent() {
+ indent_level++;
+ indent = "";
+ for (int i = 0; i < indent_level * 4; i++) {
+ if (i % 4 == 0) {
+ indent += "|";
} else {
- if (p_function->default_values[i - defaults_ofs]->type != Node::TYPE_OPERATOR) {
- _set_error("Parser bug: invalid argument default value.", p_function->line, p_function->column);
- return;
- }
-
- OperatorNode *op = static_cast<OperatorNode *>(p_function->default_values[i - defaults_ofs]);
-
- if (op->op != OperatorNode::OP_ASSIGN || op->arguments.size() != 2) {
- _set_error("Parser bug: invalid argument default value operation.", p_function->line);
- return;
- }
-
- DataType def_type = _reduce_node_type(op->arguments[1]);
-
- if (p_function->argument_types[i].infer_type) {
- def_type.is_constant = false;
- p_function->argument_types.write[i] = def_type;
- } else {
- p_function->argument_types.write[i] = _resolve_type(p_function->argument_types[i], p_function->line);
-
- if (!_is_type_compatible(p_function->argument_types[i], def_type, true)) {
- String arg_name = p_function->arguments[i];
- _set_error("Value type (" + def_type.to_string() + ") doesn't match the type of argument '" +
- arg_name + "' (" + p_function->argument_types[i].to_string() + ").",
- p_function->line);
- }
- }
- }
-#ifdef DEBUG_ENABLED
- if (p_function->arguments_usage[i] == 0 && !p_function->arguments[i].operator String().begins_with("_")) {
- _add_warning(GDScriptWarning::UNUSED_ARGUMENT, p_function->line, p_function->name, p_function->arguments[i].operator String());
+ indent += " ";
}
- for (int j = 0; j < current_class->variables.size(); j++) {
- if (current_class->variables[j].identifier == p_function->arguments[i]) {
- _add_warning(GDScriptWarning::SHADOWED_VARIABLE, p_function->line, p_function->arguments[i], itos(current_class->variables[j].line));
- }
+ }
+}
+
+void GDScriptParser::TreePrinter::decrease_indent() {
+ indent_level--;
+ indent = "";
+ for (int i = 0; i < indent_level * 4; i++) {
+ if (i % 4 == 0) {
+ indent += "|";
+ } else {
+ indent += " ";
}
-#endif // DEBUG_ENABLED
}
+}
- if (!(p_function->name == "_init")) {
- // Signature for the initializer may vary
-#ifdef DEBUG_ENABLED
- DataType return_type;
- List<DataType> arg_types;
- int default_arg_count = 0;
- bool _static = false;
- bool vararg = false;
-
- DataType base_type = current_class->base_type;
- if (_get_function_signature(base_type, p_function->name, return_type, arg_types, default_arg_count, _static, vararg)) {
- bool valid = _static == p_function->_static;
- valid = valid && return_type == p_function->return_type;
- int argsize_diff = p_function->arguments.size() - arg_types.size();
- valid = valid && argsize_diff >= 0;
- valid = valid && p_function->default_values.size() >= default_arg_count + argsize_diff;
- int i = 0;
- for (List<DataType>::Element *E = arg_types.front(); valid && E; E = E->next()) {
- valid = valid && E->get() == p_function->argument_types[i++];
- }
+void GDScriptParser::TreePrinter::push_line(const String &p_line) {
+ if (!p_line.is_empty()) {
+ push_text(p_line);
+ }
+ printed += "\n";
+ pending_indent = true;
+}
- if (!valid) {
- String parent_signature = return_type.has_type ? return_type.to_string() : "Variant";
- if (parent_signature == "null") {
- parent_signature = "void";
- }
- parent_signature += " " + p_function->name + "(";
- if (arg_types.size()) {
- int j = 0;
- for (List<DataType>::Element *E = arg_types.front(); E; E = E->next()) {
- if (E != arg_types.front()) {
- parent_signature += ", ";
- }
- String arg = E->get().to_string();
- if (arg == "null" || arg == "var") {
- arg = "Variant";
- }
- parent_signature += arg;
- if (j == arg_types.size() - default_arg_count) {
- parent_signature += "=default";
- }
+void GDScriptParser::TreePrinter::push_text(const String &p_text) {
+ if (pending_indent) {
+ printed += indent;
+ pending_indent = false;
+ }
+ printed += p_text;
+}
- j++;
- }
- }
- parent_signature += ")";
- _set_error("The function signature doesn't match the parent. Parent signature is: \"" + parent_signature + "\".", p_function->line);
- return;
- }
- }
-#endif // DEBUG_ENABLED
- } else {
- if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) {
- _set_error("The constructor can't return a value.", p_function->line);
- return;
+void GDScriptParser::TreePrinter::print_annotation(AnnotationNode *p_annotation) {
+ push_text(p_annotation->name);
+ push_text(" (");
+ for (int i = 0; i < p_annotation->arguments.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
}
+ print_expression(p_annotation->arguments[i]);
}
+ push_line(")");
+}
- if (p_function->return_type.has_type && (p_function->return_type.kind != DataType::BUILTIN || p_function->return_type.builtin_type != Variant::NIL)) {
- if (!p_function->body->has_return) {
- _set_error("A non-void function must return a value in all possible paths.", p_function->line);
- return;
+void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
+ push_text("[ ");
+ for (int i = 0; i < p_array->elements.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
}
+ print_expression(p_array->elements[i]);
}
+ push_text(" ]");
+}
+
+void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
+ push_text("Assert ( ");
+ print_expression(p_assert->condition);
+ push_line(" )");
+}
- if (p_function->has_yield) {
- // yield() will make the function return a GDScriptFunctionState, so the type is ambiguous
- p_function->return_type.has_type = false;
- p_function->return_type.may_yield = true;
+void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
+ switch (p_assignment->assignee->type) {
+ case Node::IDENTIFIER:
+ print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
+ break;
+ case Node::SUBSCRIPT:
+ print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
+ break;
+ default:
+ break; // Unreachable.
}
-#ifdef DEBUG_ENABLED
- for (Map<StringName, LocalVarNode *>::Element *E = p_function->body->variables.front(); E; E = E->next()) {
- LocalVarNode *lv = E->get();
- for (int i = 0; i < current_class->variables.size(); i++) {
- if (current_class->variables[i].identifier == lv->name) {
- _add_warning(GDScriptWarning::SHADOWED_VARIABLE, lv->line, lv->name, itos(current_class->variables[i].line));
- }
- }
+ push_text(" ");
+ switch (p_assignment->operation) {
+ case AssignmentNode::OP_ADDITION:
+ push_text("+");
+ break;
+ case AssignmentNode::OP_SUBTRACTION:
+ push_text("-");
+ break;
+ case AssignmentNode::OP_MULTIPLICATION:
+ push_text("*");
+ break;
+ case AssignmentNode::OP_DIVISION:
+ push_text("/");
+ break;
+ case AssignmentNode::OP_MODULO:
+ push_text("%");
+ break;
+ case AssignmentNode::OP_BIT_SHIFT_LEFT:
+ push_text("<<");
+ break;
+ case AssignmentNode::OP_BIT_SHIFT_RIGHT:
+ push_text(">>");
+ break;
+ case AssignmentNode::OP_BIT_AND:
+ push_text("&");
+ break;
+ case AssignmentNode::OP_BIT_OR:
+ push_text("|");
+ break;
+ case AssignmentNode::OP_BIT_XOR:
+ push_text("^");
+ break;
+ case AssignmentNode::OP_NONE:
+ break;
}
-#endif // DEBUG_ENABLED
+ push_text("= ");
+ print_expression(p_assignment->assigned_value);
+ push_line();
}
-void GDScriptParser::_check_class_blocks_types(ClassNode *p_class) {
-
- // Function blocks
- for (int i = 0; i < p_class->static_functions.size(); i++) {
- current_function = p_class->static_functions[i];
- current_block = current_function->body;
- _mark_line_as_safe(current_function->line);
- _check_block_types(current_block);
- current_block = nullptr;
- current_function = nullptr;
- if (error_set) return;
- }
+void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
+ push_text("Await ");
+ print_expression(p_await->to_await);
+}
- for (int i = 0; i < p_class->functions.size(); i++) {
- current_function = p_class->functions[i];
- current_block = current_function->body;
- _mark_line_as_safe(current_function->line);
- _check_block_types(current_block);
- current_block = nullptr;
- current_function = nullptr;
- if (error_set) return;
+void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
+ // Surround in parenthesis for disambiguation.
+ push_text("(");
+ print_expression(p_binary_op->left_operand);
+ switch (p_binary_op->operation) {
+ case BinaryOpNode::OP_ADDITION:
+ push_text(" + ");
+ break;
+ case BinaryOpNode::OP_SUBTRACTION:
+ push_text(" - ");
+ break;
+ case BinaryOpNode::OP_MULTIPLICATION:
+ push_text(" * ");
+ break;
+ case BinaryOpNode::OP_DIVISION:
+ push_text(" / ");
+ break;
+ case BinaryOpNode::OP_MODULO:
+ push_text(" % ");
+ break;
+ case BinaryOpNode::OP_BIT_LEFT_SHIFT:
+ push_text(" << ");
+ break;
+ case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
+ push_text(" >> ");
+ break;
+ case BinaryOpNode::OP_BIT_AND:
+ push_text(" & ");
+ break;
+ case BinaryOpNode::OP_BIT_OR:
+ push_text(" | ");
+ break;
+ case BinaryOpNode::OP_BIT_XOR:
+ push_text(" ^ ");
+ break;
+ case BinaryOpNode::OP_LOGIC_AND:
+ push_text(" AND ");
+ break;
+ case BinaryOpNode::OP_LOGIC_OR:
+ push_text(" OR ");
+ break;
+ case BinaryOpNode::OP_TYPE_TEST:
+ push_text(" IS ");
+ break;
+ case BinaryOpNode::OP_CONTENT_TEST:
+ push_text(" IN ");
+ break;
+ case BinaryOpNode::OP_COMP_EQUAL:
+ push_text(" == ");
+ break;
+ case BinaryOpNode::OP_COMP_NOT_EQUAL:
+ push_text(" != ");
+ break;
+ case BinaryOpNode::OP_COMP_LESS:
+ push_text(" < ");
+ break;
+ case BinaryOpNode::OP_COMP_LESS_EQUAL:
+ push_text(" <= ");
+ break;
+ case BinaryOpNode::OP_COMP_GREATER:
+ push_text(" > ");
+ break;
+ case BinaryOpNode::OP_COMP_GREATER_EQUAL:
+ push_text(" >= ");
+ break;
}
+ print_expression(p_binary_op->right_operand);
+ // Surround in parenthesis for disambiguation.
+ push_text(")");
+}
-#ifdef DEBUG_ENABLED
- // Warnings
- for (int i = 0; i < p_class->variables.size(); i++) {
- if (p_class->variables[i].usages == 0) {
- _add_warning(GDScriptWarning::UNUSED_CLASS_VARIABLE, p_class->variables[i].line, p_class->variables[i].identifier);
+void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
+ if (p_call->is_super) {
+ push_text("super");
+ if (p_call->callee != nullptr) {
+ push_text(".");
+ print_expression(p_call->callee);
}
+ } else {
+ print_expression(p_call->callee);
}
- for (int i = 0; i < p_class->_signals.size(); i++) {
- if (p_class->_signals[i].emissions == 0) {
- _add_warning(GDScriptWarning::UNUSED_SIGNAL, p_class->_signals[i].line, p_class->_signals[i].name);
+ push_text("( ");
+ for (int i = 0; i < p_call->arguments.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
}
+ print_expression(p_call->arguments[i]);
}
-#endif // DEBUG_ENABLED
-
- // Inner classes
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- current_class = p_class->subclasses[i];
- _check_class_blocks_types(current_class);
- if (error_set) return;
- current_class = p_class;
- }
+ push_text(" )");
}
-#ifdef DEBUG_ENABLED
-static String _find_function_name(const GDScriptParser::OperatorNode *p_call) {
- switch (p_call->arguments[0]->type) {
- case GDScriptParser::Node::TYPE_TYPE: {
- return Variant::get_type_name(static_cast<GDScriptParser::TypeNode *>(p_call->arguments[0])->vtype);
- } break;
- case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: {
- return GDScriptFunctions::get_func_name(static_cast<GDScriptParser::BuiltInFunctionNode *>(p_call->arguments[0])->function);
- } break;
- default: {
- int id_index = p_call->op == GDScriptParser::OperatorNode::OP_PARENT_CALL ? 0 : 1;
- if (p_call->arguments.size() > id_index && p_call->arguments[id_index]->type == GDScriptParser::Node::TYPE_IDENTIFIER) {
- return static_cast<GDScriptParser::IdentifierNode *>(p_call->arguments[id_index])->name;
- }
- } break;
- }
- return String();
+void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
+ print_expression(p_cast->operand);
+ push_text(" AS ");
+ print_type(p_cast->cast_type);
}
-#endif // DEBUG_ENABLED
-
-void GDScriptParser::_check_block_types(BlockNode *p_block) {
-
- Node *last_var_assign = nullptr;
-
- // Check each statement
- for (List<Node *>::Element *E = p_block->statements.front(); E; E = E->next()) {
- Node *statement = E->get();
- switch (statement->type) {
- case Node::TYPE_NEWLINE:
- case Node::TYPE_BREAKPOINT: {
- // Nothing to do
- } break;
- case Node::TYPE_ASSERT: {
- AssertNode *an = static_cast<AssertNode *>(statement);
- _mark_line_as_safe(an->line);
- _reduce_node_type(an->condition);
- _reduce_node_type(an->message);
- } break;
- case Node::TYPE_LOCAL_VAR: {
- LocalVarNode *lv = static_cast<LocalVarNode *>(statement);
- lv->datatype = _resolve_type(lv->datatype, lv->line);
- _mark_line_as_safe(lv->line);
-
- last_var_assign = lv->assign;
- if (lv->assign) {
- lv->assign_op->arguments[0]->set_datatype(lv->datatype);
- DataType assign_type = _reduce_node_type(lv->assign);
-#ifdef DEBUG_ENABLED
- if (assign_type.has_type && assign_type.kind == DataType::BUILTIN && assign_type.builtin_type == Variant::NIL) {
- if (lv->assign->type == Node::TYPE_OPERATOR) {
- OperatorNode *call = static_cast<OperatorNode *>(lv->assign);
- if (call->op == OperatorNode::OP_CALL || call->op == OperatorNode::OP_PARENT_CALL) {
- _add_warning(GDScriptWarning::VOID_ASSIGNMENT, lv->line, _find_function_name(call));
- }
- }
- }
- if (lv->datatype.has_type && assign_type.may_yield && lv->assign->type == Node::TYPE_OPERATOR) {
- _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, lv->line, _find_function_name(static_cast<OperatorNode *>(lv->assign)));
- }
-#endif // DEBUG_ENABLED
-
- if (!_is_type_compatible(lv->datatype, assign_type)) {
- // Try supertype test
- if (_is_type_compatible(assign_type, lv->datatype)) {
- _mark_line_as_unsafe(lv->line);
- } else {
- // Try implicit conversion
- if (lv->datatype.kind != DataType::BUILTIN || !_is_type_compatible(lv->datatype, assign_type, true)) {
- _set_error("The assigned value type (" + assign_type.to_string() + ") doesn't match the variable's type (" +
- lv->datatype.to_string() + ").",
- lv->line);
- return;
- }
- // Replace assignment with implicit conversion
- BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>();
- convert->line = lv->line;
- convert->function = GDScriptFunctions::TYPE_CONVERT;
-
- ConstantNode *tgt_type = alloc_node<ConstantNode>();
- tgt_type->line = lv->line;
- tgt_type->value = (int)lv->datatype.builtin_type;
- tgt_type->datatype = _type_from_variant(tgt_type->value);
-
- OperatorNode *convert_call = alloc_node<OperatorNode>();
- convert_call->line = lv->line;
- convert_call->op = OperatorNode::OP_CALL;
- convert_call->arguments.push_back(convert);
- convert_call->arguments.push_back(lv->assign);
- convert_call->arguments.push_back(tgt_type);
-
- lv->assign = convert_call;
- lv->assign_op->arguments.write[1] = convert_call;
-#ifdef DEBUG_ENABLED
- if (lv->datatype.builtin_type == Variant::INT && assign_type.builtin_type == Variant::FLOAT) {
- _add_warning(GDScriptWarning::NARROWING_CONVERSION, lv->line);
- }
-#endif // DEBUG_ENABLED
- }
- }
- if (lv->datatype.infer_type) {
- if (!assign_type.has_type) {
- _set_error("The assigned value doesn't have a set type; the variable type can't be inferred.", lv->line);
- return;
- }
- lv->datatype = assign_type;
- lv->datatype.is_constant = false;
- }
- if (lv->datatype.has_type && !assign_type.has_type) {
- _mark_line_as_unsafe(lv->line);
- }
- }
- } break;
- case Node::TYPE_OPERATOR: {
- OperatorNode *op = static_cast<OperatorNode *>(statement);
-
- switch (op->op) {
- case OperatorNode::OP_ASSIGN:
- case OperatorNode::OP_ASSIGN_ADD:
- case OperatorNode::OP_ASSIGN_SUB:
- case OperatorNode::OP_ASSIGN_MUL:
- case OperatorNode::OP_ASSIGN_DIV:
- case OperatorNode::OP_ASSIGN_MOD:
- case OperatorNode::OP_ASSIGN_SHIFT_LEFT:
- case OperatorNode::OP_ASSIGN_SHIFT_RIGHT:
- case OperatorNode::OP_ASSIGN_BIT_AND:
- case OperatorNode::OP_ASSIGN_BIT_OR:
- case OperatorNode::OP_ASSIGN_BIT_XOR: {
- if (op->arguments.size() < 2) {
- _set_error("Parser bug: operation without enough arguments.", op->line, op->column);
- return;
- }
-
- if (op->arguments[1] == last_var_assign) {
- // Assignment was already checked
- break;
- }
-
- _mark_line_as_safe(op->line);
-
- DataType lh_type = _reduce_node_type(op->arguments[0]);
- if (error_set) {
- return;
- }
-
- if (check_types) {
- if (!lh_type.has_type) {
- if (op->arguments[0]->type == Node::TYPE_OPERATOR) {
- _mark_line_as_unsafe(op->line);
- }
- }
- if (lh_type.is_constant) {
- _set_error("Can't assign a new value to a constant.", op->line);
- return;
- }
- }
-
- DataType rh_type;
- if (op->op != OperatorNode::OP_ASSIGN) {
- // Validate operation
- DataType arg_type = _reduce_node_type(op->arguments[1]);
- if (!arg_type.has_type) {
- _mark_line_as_unsafe(op->line);
- break;
- }
-
- Variant::Operator oper = _get_variant_operation(op->op);
- bool valid = false;
- rh_type = _get_operation_type(oper, lh_type, arg_type, valid);
-
- if (check_types && !valid) {
- _set_error("Invalid operand types (\"" + lh_type.to_string() + "\" and \"" + arg_type.to_string() +
- "\") to assignment operator \"" + Variant::get_operator_name(oper) + "\".",
- op->line);
- return;
- }
- } else {
- rh_type = _reduce_node_type(op->arguments[1]);
- }
-#ifdef DEBUG_ENABLED
- if (rh_type.has_type && rh_type.kind == DataType::BUILTIN && rh_type.builtin_type == Variant::NIL) {
- if (op->arguments[1]->type == Node::TYPE_OPERATOR) {
- OperatorNode *call = static_cast<OperatorNode *>(op->arguments[1]);
- if (call->op == OperatorNode::OP_CALL || call->op == OperatorNode::OP_PARENT_CALL) {
- _add_warning(GDScriptWarning::VOID_ASSIGNMENT, op->line, _find_function_name(call));
- }
- }
- }
- if (lh_type.has_type && rh_type.may_yield && op->arguments[1]->type == Node::TYPE_OPERATOR) {
- _add_warning(GDScriptWarning::FUNCTION_MAY_YIELD, op->line, _find_function_name(static_cast<OperatorNode *>(op->arguments[1])));
- }
-
-#endif // DEBUG_ENABLED
- bool type_match = lh_type.has_type && rh_type.has_type;
- if (check_types && !_is_type_compatible(lh_type, rh_type)) {
- type_match = false;
-
- // Try supertype test
- if (_is_type_compatible(rh_type, lh_type)) {
- _mark_line_as_unsafe(op->line);
- } else {
- // Try implicit conversion
- if (lh_type.kind != DataType::BUILTIN || !_is_type_compatible(lh_type, rh_type, true)) {
- _set_error("The assigned value's type (" + rh_type.to_string() + ") doesn't match the variable's type (" +
- lh_type.to_string() + ").",
- op->line);
- return;
- }
- if (op->op == OperatorNode::OP_ASSIGN) {
- // Replace assignment with implicit conversion
- BuiltInFunctionNode *convert = alloc_node<BuiltInFunctionNode>();
- convert->line = op->line;
- convert->function = GDScriptFunctions::TYPE_CONVERT;
-
- ConstantNode *tgt_type = alloc_node<ConstantNode>();
- tgt_type->line = op->line;
- tgt_type->value = (int)lh_type.builtin_type;
- tgt_type->datatype = _type_from_variant(tgt_type->value);
-
- OperatorNode *convert_call = alloc_node<OperatorNode>();
- convert_call->line = op->line;
- convert_call->op = OperatorNode::OP_CALL;
- convert_call->arguments.push_back(convert);
- convert_call->arguments.push_back(op->arguments[1]);
- convert_call->arguments.push_back(tgt_type);
-
- op->arguments.write[1] = convert_call;
-
- type_match = true; // Since we are converting, the type is matching
- }
-#ifdef DEBUG_ENABLED
- if (lh_type.builtin_type == Variant::INT && rh_type.builtin_type == Variant::FLOAT) {
- _add_warning(GDScriptWarning::NARROWING_CONVERSION, op->line);
- }
-#endif // DEBUG_ENABLED
- }
- }
-#ifdef DEBUG_ENABLED
- if (!rh_type.has_type && (op->op != OperatorNode::OP_ASSIGN || lh_type.has_type || op->arguments[0]->type == Node::TYPE_OPERATOR)) {
- _mark_line_as_unsafe(op->line);
- }
-#endif // DEBUG_ENABLED
- op->datatype.has_type = type_match;
- } break;
- case OperatorNode::OP_CALL:
- case OperatorNode::OP_PARENT_CALL: {
- _mark_line_as_safe(op->line);
- DataType func_type = _reduce_function_call_type(op);
-#ifdef DEBUG_ENABLED
- if (func_type.has_type && (func_type.kind != DataType::BUILTIN || func_type.builtin_type != Variant::NIL)) {
- // Figure out function name for warning
- String func_name = _find_function_name(op);
- if (func_name.empty()) {
- func_name = "<undetected name>";
- }
- _add_warning(GDScriptWarning::RETURN_VALUE_DISCARDED, op->line, func_name);
- }
-#endif // DEBUG_ENABLED
- if (error_set) return;
- } break;
- case OperatorNode::OP_YIELD: {
- _mark_line_as_safe(op->line);
- _reduce_node_type(op);
- } break;
- default: {
- _mark_line_as_safe(op->line);
- _reduce_node_type(op); // Test for safety anyway
-#ifdef DEBUG_ENABLED
- if (op->op == OperatorNode::OP_TERNARY_IF) {
- _add_warning(GDScriptWarning::STANDALONE_TERNARY, statement->line);
- } else {
- _add_warning(GDScriptWarning::STANDALONE_EXPRESSION, statement->line);
- }
-#endif // DEBUG_ENABLED
- }
- }
- } break;
- case Node::TYPE_CONTROL_FLOW: {
- ControlFlowNode *cf = static_cast<ControlFlowNode *>(statement);
- _mark_line_as_safe(cf->line);
-
- switch (cf->cf_type) {
- case ControlFlowNode::CF_RETURN: {
- DataType function_type = current_function->get_datatype();
-
- DataType ret_type;
- if (cf->arguments.size() > 0) {
- ret_type = _reduce_node_type(cf->arguments[0]);
- if (error_set) {
- return;
- }
- }
-
- if (!function_type.has_type) break;
-
- if (function_type.kind == DataType::BUILTIN && function_type.builtin_type == Variant::NIL) {
- // Return void, should not have arguments
- if (cf->arguments.size() > 0) {
- _set_error("A void function cannot return a value.", cf->line, cf->column);
- return;
- }
- } else {
- // Return something, cannot be empty
- if (cf->arguments.size() == 0) {
- _set_error("A non-void function must return a value.", cf->line, cf->column);
- return;
- }
+void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
+ push_text("Class ");
+ if (p_class->identifier == nullptr) {
+ push_text("<unnamed>");
+ } else {
+ print_identifier(p_class->identifier);
+ }
- if (!_is_type_compatible(function_type, ret_type)) {
- _set_error("The returned value type (" + ret_type.to_string() + ") doesn't match the function return type (" +
- function_type.to_string() + ").",
- cf->line, cf->column);
- return;
- }
- }
- } break;
- case ControlFlowNode::CF_MATCH: {
- MatchNode *match_node = cf->match;
- _transform_match_statment(match_node);
- } break;
- default: {
- if (cf->body_else) {
- _mark_line_as_safe(cf->body_else->line);
- }
- for (int i = 0; i < cf->arguments.size(); i++) {
- _reduce_node_type(cf->arguments[i]);
- }
- } break;
- }
- } break;
- case Node::TYPE_CONSTANT: {
- ConstantNode *cn = static_cast<ConstantNode *>(statement);
- // Strings are fine since they can be multiline comments
- if (cn->value.get_type() == Variant::STRING) {
- break;
- }
- [[fallthrough]];
- }
- default: {
- _mark_line_as_safe(statement->line);
- _reduce_node_type(statement); // Test for safety anyway
-#ifdef DEBUG_ENABLED
- _add_warning(GDScriptWarning::STANDALONE_EXPRESSION, statement->line);
-#endif // DEBUG_ENABLED
+ if (p_class->extends_used) {
+ bool first = true;
+ push_text(" Extends ");
+ if (!p_class->extends_path.is_empty()) {
+ push_text(vformat(R"("%s")", p_class->extends_path));
+ first = false;
+ }
+ for (int i = 0; i < p_class->extends.size(); i++) {
+ if (!first) {
+ push_text(".");
+ } else {
+ first = false;
}
+ push_text(p_class->extends[i]);
}
}
- // Parse sub blocks
- for (int i = 0; i < p_block->sub_blocks.size(); i++) {
- current_block = p_block->sub_blocks[i];
- _check_block_types(current_block);
- current_block = p_block;
- if (error_set) return;
- }
+ push_line(" :");
-#ifdef DEBUG_ENABLED
- // Warnings check
- for (Map<StringName, LocalVarNode *>::Element *E = p_block->variables.front(); E; E = E->next()) {
- LocalVarNode *lv = E->get();
- if (!lv->name.operator String().begins_with("_")) {
- if (lv->usages == 0) {
- _add_warning(GDScriptWarning::UNUSED_VARIABLE, lv->line, lv->name);
- } else if (lv->assignments == 0) {
- _add_warning(GDScriptWarning::UNASSIGNED_VARIABLE, lv->line, lv->name);
- }
+ increase_indent();
+
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const ClassNode::Member &m = p_class->members[i];
+
+ switch (m.type) {
+ case ClassNode::Member::CLASS:
+ print_class(m.m_class);
+ break;
+ case ClassNode::Member::VARIABLE:
+ print_variable(m.variable);
+ break;
+ case ClassNode::Member::CONSTANT:
+ print_constant(m.constant);
+ break;
+ case ClassNode::Member::SIGNAL:
+ print_signal(m.signal);
+ break;
+ case ClassNode::Member::FUNCTION:
+ print_function(m.function);
+ break;
+ case ClassNode::Member::ENUM:
+ print_enum(m.m_enum);
+ break;
+ case ClassNode::Member::ENUM_VALUE:
+ break; // Nothing. Will be printed by enum.
+ case ClassNode::Member::UNDEFINED:
+ push_line("<unknown member>");
+ break;
}
}
-#endif // DEBUG_ENABLED
-}
-void GDScriptParser::_set_error(const String &p_error, int p_line, int p_column) {
+ decrease_indent();
+}
- if (error_set)
- return; //allow no further errors
+void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
+ push_text("Constant ");
+ print_identifier(p_constant->identifier);
- error = p_error;
- error_line = p_line < 0 ? tokenizer->get_token_line() : p_line;
- error_column = p_column < 0 ? tokenizer->get_token_column() : p_column;
- error_set = true;
-}
+ increase_indent();
-#ifdef DEBUG_ENABLED
-void GDScriptParser::_add_warning(int p_code, int p_line, const String &p_symbol1, const String &p_symbol2, const String &p_symbol3, const String &p_symbol4) {
- Vector<String> symbols;
- if (!p_symbol1.empty()) {
- symbols.push_back(p_symbol1);
- }
- if (!p_symbol2.empty()) {
- symbols.push_back(p_symbol2);
- }
- if (!p_symbol3.empty()) {
- symbols.push_back(p_symbol3);
- }
- if (!p_symbol4.empty()) {
- symbols.push_back(p_symbol4);
+ push_line();
+ push_text("= ");
+ if (p_constant->initializer == nullptr) {
+ push_text("<missing value>");
+ } else {
+ print_expression(p_constant->initializer);
}
- _add_warning(p_code, p_line, symbols);
+ decrease_indent();
+ push_line();
}
-void GDScriptParser::_add_warning(int p_code, int p_line, const Vector<String> &p_symbols) {
- if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && base_path.begins_with("res://addons/")) {
- return;
- }
- if (tokenizer->is_ignoring_warnings() || !GLOBAL_GET("debug/gdscript/warnings/enable").booleanize()) {
- return;
- }
- String warn_name = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)p_code).to_lower();
- if (tokenizer->get_warning_global_skips().has(warn_name)) {
- return;
- }
- if (!GLOBAL_GET("debug/gdscript/warnings/" + warn_name)) {
- return;
+void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
+ push_line("{");
+ increase_indent();
+ for (int i = 0; i < p_dictionary->elements.size(); i++) {
+ print_expression(p_dictionary->elements[i].key);
+ if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
+ push_text(" : ");
+ } else {
+ push_text(" = ");
+ }
+ print_expression(p_dictionary->elements[i].value);
+ push_line(" ,");
}
+ decrease_indent();
+ push_text("}");
+}
- GDScriptWarning warn;
- warn.code = (GDScriptWarning::Code)p_code;
- warn.symbols = p_symbols;
- warn.line = p_line == -1 ? tokenizer->get_token_line() : p_line;
-
- List<GDScriptWarning>::Element *before = nullptr;
- for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
- if (E->get().line > warn.line) {
+void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
+ switch (p_expression->type) {
+ case Node::ARRAY:
+ print_array(static_cast<ArrayNode *>(p_expression));
+ break;
+ case Node::ASSIGNMENT:
+ print_assignment(static_cast<AssignmentNode *>(p_expression));
+ break;
+ case Node::AWAIT:
+ print_await(static_cast<AwaitNode *>(p_expression));
+ break;
+ case Node::BINARY_OPERATOR:
+ print_binary_op(static_cast<BinaryOpNode *>(p_expression));
+ break;
+ case Node::CALL:
+ print_call(static_cast<CallNode *>(p_expression));
+ break;
+ case Node::CAST:
+ print_cast(static_cast<CastNode *>(p_expression));
+ break;
+ case Node::DICTIONARY:
+ print_dictionary(static_cast<DictionaryNode *>(p_expression));
+ break;
+ case Node::GET_NODE:
+ print_get_node(static_cast<GetNodeNode *>(p_expression));
+ break;
+ case Node::IDENTIFIER:
+ print_identifier(static_cast<IdentifierNode *>(p_expression));
+ break;
+ case Node::LITERAL:
+ print_literal(static_cast<LiteralNode *>(p_expression));
+ break;
+ case Node::PRELOAD:
+ print_preload(static_cast<PreloadNode *>(p_expression));
+ break;
+ case Node::SELF:
+ print_self(static_cast<SelfNode *>(p_expression));
+ break;
+ case Node::SUBSCRIPT:
+ print_subscript(static_cast<SubscriptNode *>(p_expression));
+ break;
+ case Node::TERNARY_OPERATOR:
+ print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
+ break;
+ case Node::UNARY_OPERATOR:
+ print_unary_op(static_cast<UnaryOpNode *>(p_expression));
+ break;
+ default:
+ push_text(vformat("<unknown expression %d>", p_expression->type));
break;
- }
- before = E;
}
- if (before) {
- warnings.insert_after(before, warn);
+}
+
+void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
+ push_text("Enum ");
+ if (p_enum->identifier != nullptr) {
+ print_identifier(p_enum->identifier);
} else {
- warnings.push_front(warn);
+ push_text("<unnamed>");
}
+
+ push_line(" {");
+ increase_indent();
+ for (int i = 0; i < p_enum->values.size(); i++) {
+ const EnumNode::Value &item = p_enum->values[i];
+ print_identifier(item.identifier);
+ push_text(" = ");
+ push_text(itos(item.value));
+ push_line(" ,");
+ }
+ decrease_indent();
+ push_line("}");
}
-#endif // DEBUG_ENABLED
-String GDScriptParser::get_error() const {
+void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
+ push_text("For ");
+ print_identifier(p_for->variable);
+ push_text(" IN ");
+ print_expression(p_for->list);
+ push_line(" :");
- return error;
-}
+ increase_indent();
-int GDScriptParser::get_error_line() const {
+ print_suite(p_for->loop);
- return error_line;
+ decrease_indent();
}
-int GDScriptParser::get_error_column() const {
- return error_column;
+void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function) {
+ for (const List<AnnotationNode *>::Element *E = p_function->annotations.front(); E != nullptr; E = E->next()) {
+ print_annotation(E->get());
+ }
+ push_text("Function ");
+ print_identifier(p_function->identifier);
+ push_text("( ");
+ for (int i = 0; i < p_function->parameters.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
+ }
+ print_parameter(p_function->parameters[i]);
+ }
+ push_line(" ) :");
+ increase_indent();
+ print_suite(p_function->body);
+ decrease_indent();
}
-bool GDScriptParser::has_error() const {
- return error_set;
+void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
+ push_text("$");
+ if (p_get_node->string != nullptr) {
+ print_literal(p_get_node->string);
+ } else {
+ for (int i = 0; i < p_get_node->chain.size(); i++) {
+ if (i > 0) {
+ push_text("/");
+ }
+ print_identifier(p_get_node->chain[i]);
+ }
+ }
}
-Error GDScriptParser::_parse(const String &p_base_path) {
-
- base_path = p_base_path;
-
- //assume class
- ClassNode *main_class = alloc_node<ClassNode>();
- main_class->initializer = alloc_node<BlockNode>();
- main_class->initializer->parent_class = main_class;
- main_class->ready = alloc_node<BlockNode>();
- main_class->ready->parent_class = main_class;
- current_class = main_class;
-
- _parse_class(main_class);
+void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
+ push_text(p_identifier->name);
+}
- if (tokenizer->get_token() == GDScriptTokenizer::TK_ERROR) {
- error_set = false;
- _set_error("Parse error: " + tokenizer->get_token_error());
+void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
+ if (p_is_elif) {
+ push_text("Elif ");
+ } else {
+ push_text("If ");
}
+ print_expression(p_if->condition);
+ push_line(" :");
- bool for_completion_error_set = false;
- if (error_set && for_completion) {
- for_completion_error_set = true;
- error_set = false;
- }
+ increase_indent();
+ print_suite(p_if->true_block);
+ decrease_indent();
- if (error_set) {
- return ERR_PARSE_ERROR;
+ // FIXME: Properly detect "elif" blocks.
+ if (p_if->false_block != nullptr) {
+ push_line("Else :");
+ increase_indent();
+ print_suite(p_if->false_block);
+ decrease_indent();
}
+}
- if (dependencies_only) {
- return OK;
+void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
+ // Prefix for string types.
+ switch (p_literal->value.get_type()) {
+ case Variant::NODE_PATH:
+ push_text("^\"");
+ break;
+ case Variant::STRING:
+ push_text("\"");
+ break;
+ case Variant::STRING_NAME:
+ push_text("&\"");
+ break;
+ default:
+ break;
}
-
- _determine_inheritance(main_class);
-
- if (error_set) {
- return ERR_PARSE_ERROR;
+ push_text(p_literal->value);
+ // Suffix for string types.
+ switch (p_literal->value.get_type()) {
+ case Variant::NODE_PATH:
+ case Variant::STRING:
+ case Variant::STRING_NAME:
+ push_text("\"");
+ break;
+ default:
+ break;
}
+}
- current_class = main_class;
- current_function = nullptr;
- current_block = nullptr;
-
- if (for_completion) check_types = false;
-
- // Resolve all class-level stuff before getting into function blocks
- _check_class_level_types(main_class);
+void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
+ push_text("Match ");
+ print_expression(p_match->test);
+ push_line(" :");
- if (error_set) {
- return ERR_PARSE_ERROR;
+ increase_indent();
+ for (int i = 0; i < p_match->branches.size(); i++) {
+ print_match_branch(p_match->branches[i]);
}
+ decrease_indent();
+}
- // Resolve the function blocks
- _check_class_blocks_types(main_class);
-
- if (for_completion_error_set) {
- error_set = true;
+void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
+ for (int i = 0; i < p_match_branch->patterns.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
+ }
+ print_match_pattern(p_match_branch->patterns[i]);
}
- if (error_set) {
- return ERR_PARSE_ERROR;
- }
+ push_line(" :");
-#ifdef DEBUG_ENABLED
+ increase_indent();
+ print_suite(p_match_branch->block);
+ decrease_indent();
+}
- // Resolve warning ignores
- Vector<Pair<int, String>> warning_skips = tokenizer->get_warning_skips();
- bool warning_is_error = GLOBAL_GET("debug/gdscript/warnings/treat_warnings_as_errors").booleanize();
- for (List<GDScriptWarning>::Element *E = warnings.front(); E;) {
- GDScriptWarning &w = E->get();
- int skip_index = -1;
- for (int i = 0; i < warning_skips.size(); i++) {
- if (warning_skips[i].first >= w.line) {
- break;
+void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
+ switch (p_match_pattern->pattern_type) {
+ case PatternNode::PT_LITERAL:
+ print_literal(p_match_pattern->literal);
+ break;
+ case PatternNode::PT_WILDCARD:
+ push_text("_");
+ break;
+ case PatternNode::PT_REST:
+ push_text("..");
+ break;
+ case PatternNode::PT_BIND:
+ push_text("Var ");
+ print_identifier(p_match_pattern->bind);
+ break;
+ case PatternNode::PT_EXPRESSION:
+ print_expression(p_match_pattern->expression);
+ break;
+ case PatternNode::PT_ARRAY:
+ push_text("[ ");
+ for (int i = 0; i < p_match_pattern->array.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
+ }
+ print_match_pattern(p_match_pattern->array[i]);
}
- skip_index = i;
- }
- List<GDScriptWarning>::Element *next = E->next();
- bool erase = false;
- if (skip_index != -1) {
- if (warning_skips[skip_index].second == GDScriptWarning::get_name_from_code(w.code).to_lower()) {
- erase = true;
+ push_text(" ]");
+ break;
+ case PatternNode::PT_DICTIONARY:
+ push_text("{ ");
+ for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
+ if (i > 0) {
+ push_text(" , ");
+ }
+ if (p_match_pattern->dictionary[i].key != nullptr) {
+ // Key can be null for rest pattern.
+ print_expression(p_match_pattern->dictionary[i].key);
+ push_text(" : ");
+ }
+ print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
}
- warning_skips.remove(skip_index);
- }
- if (erase) {
- warnings.erase(E);
- } else if (warning_is_error) {
- _set_error(w.get_message() + " (warning treated as error)", w.line);
- return ERR_PARSE_ERROR;
- }
- E = next;
+ push_text(" }");
+ break;
}
-#endif // DEBUG_ENABLED
-
- return OK;
}
-Error GDScriptParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path, const String &p_self_path) {
-
- clear();
-
- self_path = p_self_path;
- GDScriptTokenizerBuffer *tb = memnew(GDScriptTokenizerBuffer);
- tb->set_code_buffer(p_bytecode);
- tokenizer = tb;
- Error ret = _parse(p_base_path);
- memdelete(tb);
- tokenizer = nullptr;
- return ret;
+void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
+ print_identifier(p_parameter->identifier);
+ if (p_parameter->datatype_specifier != nullptr) {
+ push_text(" : ");
+ print_type(p_parameter->datatype_specifier);
+ }
+ if (p_parameter->default_value != nullptr) {
+ push_text(" = ");
+ print_expression(p_parameter->default_value);
+ }
}
-Error GDScriptParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion, Set<int> *r_safe_lines, bool p_dependencies_only) {
-
- clear();
-
- self_path = p_self_path;
- GDScriptTokenizerText *tt = memnew(GDScriptTokenizerText);
- tt->set_code(p_code);
-
- validating = p_just_validate;
- for_completion = p_for_completion;
- dependencies_only = p_dependencies_only;
-#ifdef DEBUG_ENABLED
- safe_lines = r_safe_lines;
-#endif // DEBUG_ENABLED
- tokenizer = tt;
- Error ret = _parse(p_base_path);
- memdelete(tt);
- tokenizer = nullptr;
- return ret;
+void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
+ push_text(R"(Preload ( ")");
+ push_text(p_preload->resolved_path);
+ push_text(R"(" )");
}
-bool GDScriptParser::is_tool_script() const {
-
- return (head && head->type == Node::TYPE_CLASS && static_cast<const ClassNode *>(head)->tool);
+void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
+ push_text("Return");
+ if (p_return->return_value != nullptr) {
+ push_text(" ");
+ print_expression(p_return->return_value);
+ }
+ push_line();
}
-const GDScriptParser::Node *GDScriptParser::get_parse_tree() const {
-
- return head;
+void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
+ push_text("Self(");
+ if (p_self->current_class->identifier != nullptr) {
+ print_identifier(p_self->current_class->identifier);
+ } else {
+ push_text("<main class>");
+ }
+ push_text(")");
}
-void GDScriptParser::clear() {
-
- while (list) {
-
- Node *l = list;
- list = list->next;
- memdelete(l);
+void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
+ push_text("Signal ");
+ print_identifier(p_signal->identifier);
+ push_text("( ");
+ for (int i = 0; i < p_signal->parameters.size(); i++) {
+ print_parameter(p_signal->parameters[i]);
}
-
- head = nullptr;
- list = nullptr;
-
- completion_type = COMPLETION_NONE;
- completion_node = nullptr;
- completion_class = nullptr;
- completion_function = nullptr;
- completion_block = nullptr;
- current_block = nullptr;
- current_class = nullptr;
-
- completion_found = false;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
-
- current_function = nullptr;
-
- validating = false;
- for_completion = false;
- error_set = false;
- indent_level.clear();
- indent_level.push_back(IndentLevel(0, 0));
- error_line = 0;
- error_column = 0;
- pending_newline = -1;
- parenthesis = 0;
- current_export.type = Variant::NIL;
- check_types = true;
- dependencies_only = false;
- dependencies.clear();
- error = "";
-#ifdef DEBUG_ENABLED
- safe_lines = nullptr;
-#endif // DEBUG_ENABLED
+ push_line(" )");
}
-GDScriptParser::CompletionType GDScriptParser::get_completion_type() {
-
- return completion_type;
+void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
+ print_expression(p_subscript->base);
+ if (p_subscript->is_attribute) {
+ push_text(".");
+ print_identifier(p_subscript->attribute);
+ } else {
+ push_text("[ ");
+ print_expression(p_subscript->index);
+ push_text(" ]");
+ }
}
-StringName GDScriptParser::get_completion_cursor() {
-
- return completion_cursor;
+void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
+ switch (p_statement->type) {
+ case Node::ASSERT:
+ print_assert(static_cast<AssertNode *>(p_statement));
+ break;
+ case Node::VARIABLE:
+ print_variable(static_cast<VariableNode *>(p_statement));
+ break;
+ case Node::CONSTANT:
+ print_constant(static_cast<ConstantNode *>(p_statement));
+ break;
+ case Node::IF:
+ print_if(static_cast<IfNode *>(p_statement));
+ break;
+ case Node::FOR:
+ print_for(static_cast<ForNode *>(p_statement));
+ break;
+ case Node::WHILE:
+ print_while(static_cast<WhileNode *>(p_statement));
+ break;
+ case Node::MATCH:
+ print_match(static_cast<MatchNode *>(p_statement));
+ break;
+ case Node::RETURN:
+ print_return(static_cast<ReturnNode *>(p_statement));
+ break;
+ case Node::BREAK:
+ push_line("Break");
+ break;
+ case Node::CONTINUE:
+ push_line("Continue");
+ break;
+ case Node::PASS:
+ push_line("Pass");
+ break;
+ case Node::BREAKPOINT:
+ push_line("Breakpoint");
+ break;
+ case Node::ASSIGNMENT:
+ print_assignment(static_cast<AssignmentNode *>(p_statement));
+ break;
+ default:
+ if (p_statement->is_expression()) {
+ print_expression(static_cast<ExpressionNode *>(p_statement));
+ push_line();
+ } else {
+ push_line(vformat("<unknown statement %d>", p_statement->type));
+ }
+ break;
+ }
}
-int GDScriptParser::get_completion_line() {
-
- return completion_line;
+void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
+ for (int i = 0; i < p_suite->statements.size(); i++) {
+ print_statement(p_suite->statements[i]);
+ }
}
-Variant::Type GDScriptParser::get_completion_built_in_constant() {
-
- return completion_built_in_constant;
+void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
+ // Surround in parenthesis for disambiguation.
+ push_text("(");
+ print_expression(p_ternary_op->true_expr);
+ push_text(") IF (");
+ print_expression(p_ternary_op->condition);
+ push_text(") ELSE (");
+ print_expression(p_ternary_op->false_expr);
+ push_text(")");
}
-GDScriptParser::Node *GDScriptParser::get_completion_node() {
-
- return completion_node;
+void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
+ if (p_type->type_chain.is_empty()) {
+ push_text("Void");
+ } else {
+ for (int i = 0; i < p_type->type_chain.size(); i++) {
+ if (i > 0) {
+ push_text(".");
+ }
+ print_identifier(p_type->type_chain[i]);
+ }
+ }
}
-GDScriptParser::BlockNode *GDScriptParser::get_completion_block() {
-
- return completion_block;
+void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
+ // Surround in parenthesis for disambiguation.
+ push_text("(");
+ switch (p_unary_op->operation) {
+ case UnaryOpNode::OP_POSITIVE:
+ push_text("+");
+ break;
+ case UnaryOpNode::OP_NEGATIVE:
+ push_text("-");
+ break;
+ case UnaryOpNode::OP_LOGIC_NOT:
+ push_text("NOT");
+ break;
+ case UnaryOpNode::OP_COMPLEMENT:
+ push_text("~");
+ break;
+ }
+ print_expression(p_unary_op->operand);
+ // Surround in parenthesis for disambiguation.
+ push_text(")");
}
-GDScriptParser::ClassNode *GDScriptParser::get_completion_class() {
+void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
+ for (const List<AnnotationNode *>::Element *E = p_variable->annotations.front(); E != nullptr; E = E->next()) {
+ print_annotation(E->get());
+ }
- return completion_class;
-}
+ push_text("Variable ");
+ print_identifier(p_variable->identifier);
-GDScriptParser::FunctionNode *GDScriptParser::get_completion_function() {
+ push_text(" : ");
+ if (p_variable->datatype_specifier != nullptr) {
+ print_type(p_variable->datatype_specifier);
+ } else if (p_variable->infer_datatype) {
+ push_text("<inferred type>");
+ } else {
+ push_text("Variant");
+ }
- return completion_function;
-}
+ increase_indent();
-int GDScriptParser::get_completion_argument_index() {
+ push_line();
+ push_text("= ");
+ if (p_variable->initializer == nullptr) {
+ push_text("<default value>");
+ } else {
+ print_expression(p_variable->initializer);
+ }
+ push_line();
+
+ if (p_variable->property != VariableNode::PROP_NONE) {
+ if (p_variable->getter != nullptr) {
+ push_text("Get");
+ if (p_variable->property == VariableNode::PROP_INLINE) {
+ push_line(":");
+ increase_indent();
+ print_suite(p_variable->getter);
+ decrease_indent();
+ } else {
+ push_line(" =");
+ increase_indent();
+ print_identifier(p_variable->getter_pointer);
+ push_line();
+ decrease_indent();
+ }
+ }
+ if (p_variable->setter != nullptr) {
+ push_text("Set (");
+ if (p_variable->property == VariableNode::PROP_INLINE) {
+ if (p_variable->setter_parameter != nullptr) {
+ print_identifier(p_variable->setter_parameter);
+ } else {
+ push_text("<missing>");
+ }
+ push_line("):");
+ increase_indent();
+ print_suite(p_variable->setter);
+ decrease_indent();
+ } else {
+ push_line(" =");
+ increase_indent();
+ print_identifier(p_variable->setter_pointer);
+ push_line();
+ decrease_indent();
+ }
+ }
+ }
- return completion_argument;
+ decrease_indent();
+ push_line();
}
-int GDScriptParser::get_completion_identifier_is_function() {
+void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
+ push_text("While ");
+ print_expression(p_while->condition);
+ push_line(" :");
- return completion_ident_is_call;
+ increase_indent();
+ print_suite(p_while->loop);
+ decrease_indent();
}
-GDScriptParser::GDScriptParser() {
-
- head = nullptr;
- list = nullptr;
- tokenizer = nullptr;
- pending_newline = -1;
- clear();
-}
+void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
+ ERR_FAIL_COND_MSG(p_parser.get_tree() == nullptr, "Parse the code before printing the parse tree.");
-GDScriptParser::~GDScriptParser() {
+ if (p_parser.is_tool()) {
+ push_line("@tool");
+ }
+ if (!p_parser.get_tree()->icon_path.is_empty()) {
+ push_text(R"(@icon (")");
+ push_text(p_parser.get_tree()->icon_path);
+ push_line("\")");
+ }
+ print_class(p_parser.get_tree());
- clear();
+ print_line(printed);
}
+
+#endif // DEBUG_ENABLED
diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h
index f254352423..f43708b81f 100644
--- a/modules/gdscript/gdscript_parser.h
+++ b/modules/gdscript/gdscript_parser.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,665 +31,1359 @@
#ifndef GDSCRIPT_PARSER_H
#define GDSCRIPT_PARSER_H
-#include "core/map.h"
-#include "core/object.h"
-#include "core/script_language.h"
-#include "gdscript_functions.h"
+#include "core/io/multiplayer_api.h"
+#include "core/io/resource.h"
+#include "core/object/reference.h"
+#include "core/object/script_language.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
+#include "core/templates/hash_map.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
+#include "gdscript_cache.h"
#include "gdscript_tokenizer.h"
-struct GDScriptDataType;
-struct GDScriptWarning;
+#ifdef DEBUG_ENABLED
+#include "core/string/string_builder.h"
+#include "gdscript_warning.h"
+#endif // DEBUG_ENABLED
class GDScriptParser {
+ struct AnnotationInfo;
+
public:
+ // Forward-declare all parser nodes, to avoid ordering issues.
+ struct AnnotationNode;
+ struct ArrayNode;
+ struct AssertNode;
+ struct AssignmentNode;
+ struct AwaitNode;
+ struct BinaryOpNode;
+ struct BreakNode;
+ struct BreakpointNode;
+ struct CallNode;
+ struct CastNode;
struct ClassNode;
+ struct ConstantNode;
+ struct ContinueNode;
+ struct DictionaryNode;
+ struct EnumNode;
+ struct ExpressionNode;
+ struct ForNode;
+ struct FunctionNode;
+ struct GetNodeNode;
+ struct IdentifierNode;
+ struct IfNode;
+ struct LiteralNode;
+ struct MatchNode;
+ struct MatchBranchNode;
+ struct ParameterNode;
+ struct PassNode;
+ struct PatternNode;
+ struct PreloadNode;
+ struct ReturnNode;
+ struct SelfNode;
+ struct SignalNode;
+ struct SubscriptNode;
+ struct SuiteNode;
+ struct TernaryOpNode;
+ struct TypeNode;
+ struct UnaryOpNode;
+ struct VariableNode;
+ struct WhileNode;
struct DataType {
- enum {
+ enum Kind {
BUILTIN,
NATIVE,
SCRIPT,
- GDSCRIPT,
- CLASS,
- UNRESOLVED
- } kind;
+ CLASS, // GDScript.
+ ENUM, // Full enumeration.
+ ENUM_VALUE, // Value from enumeration.
+ VARIANT, // Can be any type.
+ UNRESOLVED,
+ // TODO: Enum
+ };
+ Kind kind = UNRESOLVED;
- bool has_type;
- bool is_constant;
- bool is_meta_type; // Whether the value can be used as a type
- bool infer_type;
- bool may_yield; // For function calls
+ enum TypeSource {
+ UNDETECTED, // Can be any type.
+ INFERRED, // Has inferred type, but still dynamic.
+ ANNOTATED_EXPLICIT, // Has a specific type annotated.
+ ANNOTATED_INFERRED, // Has a static type but comes from the assigned value.
+ };
+ TypeSource type_source = UNDETECTED;
- Variant::Type builtin_type;
+ bool is_constant = false;
+ bool is_meta_type = false;
+ bool is_coroutine = false; // For function calls.
+
+ Variant::Type builtin_type = Variant::NIL;
StringName native_type;
+ StringName enum_type; // Enum name or the value name in an enum.
Ref<Script> script_type;
- ClassNode *class_type;
+ String script_path;
+ ClassNode *class_type = nullptr;
+
+ MethodInfo method_info; // For callable/signals.
+ HashMap<StringName, int> enum_values; // For enums.
+ _FORCE_INLINE_ bool is_set() const { return kind != UNRESOLVED; }
+ _FORCE_INLINE_ bool has_no_type() const { return type_source == UNDETECTED; }
+ _FORCE_INLINE_ bool is_variant() const { return kind == VARIANT || kind == UNRESOLVED; }
+ _FORCE_INLINE_ bool is_hard_type() const { return type_source > INFERRED; }
String to_string() const;
- bool operator==(const DataType &other) const {
- if (!has_type || !other.has_type) {
- return true; // Can be considered equal for parsing purpose
+ bool operator==(const DataType &p_other) const {
+ if (type_source == UNDETECTED || p_other.type_source == UNDETECTED) {
+ return true; // Can be consireded equal for parsing purposes.
}
- if (kind != other.kind) {
+
+ if (type_source == INFERRED || p_other.type_source == INFERRED) {
+ return true; // Can be consireded equal for parsing purposes.
+ }
+
+ if (kind != p_other.kind) {
return false;
}
+
switch (kind) {
- case BUILTIN: {
- return builtin_type == other.builtin_type;
- } break;
- case NATIVE: {
- return native_type == other.native_type;
- } break;
- case GDSCRIPT:
- case SCRIPT: {
- return script_type == other.script_type;
- } break;
- case CLASS: {
- return class_type == other.class_type;
- } break;
- case UNRESOLVED: {
- } break;
+ case VARIANT:
+ return true; // All variants are the same.
+ case BUILTIN:
+ return builtin_type == p_other.builtin_type;
+ case NATIVE:
+ case ENUM:
+ return native_type == p_other.native_type;
+ case ENUM_VALUE:
+ return native_type == p_other.native_type && enum_type == p_other.enum_type;
+ case SCRIPT:
+ return script_type == p_other.script_type;
+ case CLASS:
+ return class_type == p_other.class_type;
+ case UNRESOLVED:
+ break;
}
+
return false;
}
- DataType() :
- kind(UNRESOLVED),
- has_type(false),
- is_constant(false),
- is_meta_type(false),
- infer_type(false),
- may_yield(false),
- builtin_type(Variant::NIL),
- class_type(nullptr) {}
+ bool operator!=(const DataType &p_other) const {
+ return !(this->operator==(p_other));
+ }
};
- struct Node {
+ struct ParserError {
+ // TODO: Do I really need a "type"?
+ // enum Type {
+ // NO_ERROR,
+ // EMPTY_FILE,
+ // CLASS_NAME_USED_TWICE,
+ // EXTENDS_USED_TWICE,
+ // EXPECTED_END_STATEMENT,
+ // };
+ // Type type = NO_ERROR;
+ String message;
+ int line = 0, column = 0;
+ };
+ struct Node {
enum Type {
- TYPE_CLASS,
- TYPE_FUNCTION,
- TYPE_BUILT_IN_FUNCTION,
- TYPE_BLOCK,
- TYPE_IDENTIFIER,
- TYPE_TYPE,
- TYPE_CONSTANT,
- TYPE_ARRAY,
- TYPE_DICTIONARY,
- TYPE_SELF,
- TYPE_OPERATOR,
- TYPE_CONTROL_FLOW,
- TYPE_LOCAL_VAR,
- TYPE_CAST,
- TYPE_ASSERT,
- TYPE_BREAKPOINT,
- TYPE_NEWLINE,
+ NONE,
+ ANNOTATION,
+ ARRAY,
+ ASSERT,
+ ASSIGNMENT,
+ AWAIT,
+ BINARY_OPERATOR,
+ BREAK,
+ BREAKPOINT,
+ CALL,
+ CAST,
+ CLASS,
+ CONSTANT,
+ CONTINUE,
+ DICTIONARY,
+ ENUM,
+ FOR,
+ FUNCTION,
+ GET_NODE,
+ IDENTIFIER,
+ IF,
+ LITERAL,
+ MATCH,
+ MATCH_BRANCH,
+ PARAMETER,
+ PASS,
+ PATTERN,
+ PRELOAD,
+ RETURN,
+ SELF,
+ SIGNAL,
+ SUBSCRIPT,
+ SUITE,
+ TERNARY_OPERATOR,
+ TYPE,
+ UNARY_OPERATOR,
+ VARIABLE,
+ WHILE,
};
- Node *next;
- int line;
- int column;
- Type type;
+ Type type = NONE;
+ int start_line = 0, end_line = 0;
+ int start_column = 0, end_column = 0;
+ int leftmost_column = 0, rightmost_column = 0;
+ Node *next = nullptr;
+ List<AnnotationNode *> annotations;
+
+ DataType datatype;
- virtual DataType get_datatype() const { return DataType(); }
- virtual void set_datatype(const DataType &p_datatype) {}
+ virtual DataType get_datatype() const { return datatype; }
+ virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
+
+ virtual bool is_expression() const { return false; }
virtual ~Node() {}
};
- struct FunctionNode;
- struct BlockNode;
- struct ConstantNode;
- struct LocalVarNode;
- struct OperatorNode;
+ struct ExpressionNode : public Node {
+ // Base type for all expression kinds.
+ bool reduced = false;
+ bool is_constant = false;
+ Variant reduced_value;
- struct ClassNode : public Node {
+ virtual bool is_expression() const { return true; }
+ virtual ~ExpressionNode() {}
- bool tool;
+ protected:
+ ExpressionNode() {}
+ };
+
+ struct AnnotationNode : public Node {
StringName name;
- bool extends_used;
- bool classname_used;
- StringName extends_file;
- Vector<StringName> extends_class;
- DataType base_type;
- String icon_path;
+ Vector<ExpressionNode *> arguments;
+ Vector<Variant> resolved_arguments;
- struct Member {
- PropertyInfo _export;
-#ifdef TOOLS_ENABLED
- Variant default_value;
-#endif
- StringName identifier;
- DataType data_type;
- StringName setter;
- StringName getter;
- int line;
- Node *expression;
- OperatorNode *initial_assignment;
- MultiplayerAPI::RPCMode rpc_mode;
- int usages;
- };
+ AnnotationInfo *info = nullptr;
- struct Constant {
- Node *expression;
- DataType type;
- };
+ bool apply(GDScriptParser *p_this, Node *p_target) const;
+ bool applies_to(uint32_t p_target_kinds) const;
- struct Signal {
- StringName name;
- Vector<StringName> arguments;
- int emissions;
- int line;
- };
+ AnnotationNode() {
+ type = ANNOTATION;
+ }
+ };
- Vector<ClassNode *> subclasses;
- Vector<Member> variables;
- Map<StringName, Constant> constant_expressions;
- Vector<FunctionNode *> functions;
- Vector<FunctionNode *> static_functions;
- Vector<Signal> _signals;
- BlockNode *initializer;
- BlockNode *ready;
- ClassNode *owner;
- //Vector<Node*> initializers;
- int end_line;
+ struct ArrayNode : public ExpressionNode {
+ Vector<ExpressionNode *> elements;
- ClassNode() {
- tool = false;
- type = TYPE_CLASS;
- extends_used = false;
- classname_used = false;
- end_line = -1;
- owner = nullptr;
+ ArrayNode() {
+ type = ARRAY;
}
};
- struct FunctionNode : public Node {
+ struct AssertNode : public Node {
+ ExpressionNode *condition = nullptr;
+ ExpressionNode *message = nullptr;
- bool _static;
- MultiplayerAPI::RPCMode rpc_mode;
- bool has_yield;
- bool has_unreachable_code;
- StringName name;
- DataType return_type;
- Vector<StringName> arguments;
- Vector<DataType> argument_types;
- Vector<Node *> default_values;
- BlockNode *body;
-#ifdef DEBUG_ENABLED
- Vector<int> arguments_usage;
-#endif // DEBUG_ENABLED
+ AssertNode() {
+ type = ASSERT;
+ }
+ };
- virtual DataType get_datatype() const { return return_type; }
- virtual void set_datatype(const DataType &p_datatype) { return_type = p_datatype; }
- int get_required_argument_count() { return arguments.size() - default_values.size(); }
+ struct AssignmentNode : public ExpressionNode {
+ // Assignment is not really an expression but it's easier to parse as if it were.
+ enum Operation {
+ OP_NONE,
+ OP_ADDITION,
+ OP_SUBTRACTION,
+ OP_MULTIPLICATION,
+ OP_DIVISION,
+ OP_MODULO,
+ OP_BIT_SHIFT_LEFT,
+ OP_BIT_SHIFT_RIGHT,
+ OP_BIT_AND,
+ OP_BIT_OR,
+ OP_BIT_XOR,
+ };
- FunctionNode() {
- type = TYPE_FUNCTION;
- _static = false;
- rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
- has_yield = false;
- has_unreachable_code = false;
+ Operation operation = OP_NONE;
+ Variant::Operator variant_op = Variant::OP_MAX;
+ ExpressionNode *assignee = nullptr;
+ ExpressionNode *assigned_value = nullptr;
+
+ AssignmentNode() {
+ type = ASSIGNMENT;
}
};
- struct BlockNode : public Node {
+ struct AwaitNode : public ExpressionNode {
+ ExpressionNode *to_await = nullptr;
- ClassNode *parent_class;
- BlockNode *parent_block;
- List<Node *> statements;
- Map<StringName, LocalVarNode *> variables;
- bool has_return;
+ AwaitNode() {
+ type = AWAIT;
+ }
+ };
- Node *if_condition; //tiny hack to improve code completion on if () blocks
+ struct BinaryOpNode : public ExpressionNode {
+ enum OpType {
+ OP_ADDITION,
+ OP_SUBTRACTION,
+ OP_MULTIPLICATION,
+ OP_DIVISION,
+ OP_MODULO,
+ OP_BIT_LEFT_SHIFT,
+ OP_BIT_RIGHT_SHIFT,
+ OP_BIT_AND,
+ OP_BIT_OR,
+ OP_BIT_XOR,
+ OP_LOGIC_AND,
+ OP_LOGIC_OR,
+ OP_TYPE_TEST,
+ OP_CONTENT_TEST,
+ OP_COMP_EQUAL,
+ OP_COMP_NOT_EQUAL,
+ OP_COMP_LESS,
+ OP_COMP_LESS_EQUAL,
+ OP_COMP_GREATER,
+ OP_COMP_GREATER_EQUAL,
+ };
+
+ OpType operation;
+ Variant::Operator variant_op = Variant::OP_MAX;
+ ExpressionNode *left_operand = nullptr;
+ ExpressionNode *right_operand = nullptr;
- //the following is useful for code completion
- List<BlockNode *> sub_blocks;
- int end_line;
- BlockNode() {
- if_condition = nullptr;
- type = TYPE_BLOCK;
- end_line = -1;
- parent_block = nullptr;
- parent_class = nullptr;
- has_return = false;
+ BinaryOpNode() {
+ type = BINARY_OPERATOR;
}
};
- struct TypeNode : public Node {
+ struct BreakNode : public Node {
+ BreakNode() {
+ type = BREAK;
+ }
+ };
- Variant::Type vtype;
- TypeNode() { type = TYPE_TYPE; }
+ struct BreakpointNode : public Node {
+ BreakpointNode() {
+ type = BREAKPOINT;
+ }
};
- struct BuiltInFunctionNode : public Node {
- GDScriptFunctions::Function function;
- BuiltInFunctionNode() { type = TYPE_BUILT_IN_FUNCTION; }
+
+ struct CallNode : public ExpressionNode {
+ ExpressionNode *callee = nullptr;
+ Vector<ExpressionNode *> arguments;
+ StringName function_name;
+ bool is_super = false;
+
+ CallNode() {
+ type = CALL;
+ }
+
+ Type get_callee_type() const {
+ if (callee == nullptr) {
+ return Type::NONE;
+ } else {
+ return callee->type;
+ }
+ }
};
- struct IdentifierNode : public Node {
+ struct CastNode : public ExpressionNode {
+ ExpressionNode *operand = nullptr;
+ TypeNode *cast_type = nullptr;
- StringName name;
- BlockNode *declared_block; // Simplify lookup by checking if it is declared locally
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
- IdentifierNode() {
- type = TYPE_IDENTIFIER;
- declared_block = nullptr;
+ CastNode() {
+ type = CAST;
}
};
- struct LocalVarNode : public Node {
+ struct EnumNode : public Node {
+ struct Value {
+ IdentifierNode *identifier = nullptr;
+ ExpressionNode *custom_value = nullptr;
+ EnumNode *parent_enum = nullptr;
+ int index = -1;
+ bool resolved = false;
+ int value = 0;
+ int line = 0;
+ int leftmost_column = 0;
+ int rightmost_column = 0;
+#ifdef TOOLS_ENABLED
+ String doc_description;
+#endif // TOOLS_ENABLED
+ };
- StringName name;
- Node *assign;
- OperatorNode *assign_op;
- int assignments;
- int usages;
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
- LocalVarNode() {
- type = TYPE_LOCAL_VAR;
- assign = nullptr;
- assign_op = nullptr;
- assignments = 0;
- usages = 0;
+ IdentifierNode *identifier = nullptr;
+ Vector<Value> values;
+#ifdef TOOLS_ENABLED
+ String doc_description;
+#endif // TOOLS_ENABLED
+
+ EnumNode() {
+ type = ENUM;
}
};
- struct ConstantNode : public Node {
- Variant value;
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
- ConstantNode() { type = TYPE_CONSTANT; }
+ struct ClassNode : public Node {
+ struct Member {
+ enum Type {
+ UNDEFINED,
+ CLASS,
+ CONSTANT,
+ FUNCTION,
+ SIGNAL,
+ VARIABLE,
+ ENUM,
+ ENUM_VALUE, // For unnamed enums.
+ };
+
+ Type type = UNDEFINED;
+
+ union {
+ ClassNode *m_class = nullptr;
+ ConstantNode *constant;
+ FunctionNode *function;
+ SignalNode *signal;
+ VariableNode *variable;
+ EnumNode *m_enum;
+ };
+ EnumNode::Value enum_value;
+
+ String get_type_name() const {
+ switch (type) {
+ case UNDEFINED:
+ return "???";
+ case CLASS:
+ return "class";
+ case CONSTANT:
+ return "constant";
+ case FUNCTION:
+ return "function";
+ case SIGNAL:
+ return "signal";
+ case VARIABLE:
+ return "variable";
+ case ENUM:
+ return "enum";
+ case ENUM_VALUE:
+ return "enum value";
+ }
+ return "";
+ }
+
+ int get_line() const {
+ switch (type) {
+ case CLASS:
+ return m_class->start_line;
+ case CONSTANT:
+ return constant->start_line;
+ case FUNCTION:
+ return function->start_line;
+ case VARIABLE:
+ return variable->start_line;
+ case ENUM_VALUE:
+ return enum_value.line;
+ case ENUM:
+ return m_enum->start_line;
+ case SIGNAL:
+ return signal->start_line;
+ case UNDEFINED:
+ ERR_FAIL_V_MSG(-1, "Reaching undefined member type.");
+ }
+ ERR_FAIL_V_MSG(-1, "Reaching unhandled type.");
+ }
+
+ DataType get_datatype() const {
+ switch (type) {
+ case CLASS:
+ return m_class->get_datatype();
+ case CONSTANT:
+ return constant->get_datatype();
+ case FUNCTION:
+ return function->get_datatype();
+ case VARIABLE:
+ return variable->get_datatype();
+ case ENUM:
+ return m_enum->get_datatype();
+ case ENUM_VALUE: {
+ // Always integer.
+ DataType type;
+ type.type_source = DataType::ANNOTATED_EXPLICIT;
+ type.kind = DataType::BUILTIN;
+ type.builtin_type = Variant::INT;
+ return type;
+ }
+ case SIGNAL: {
+ DataType type;
+ type.type_source = DataType::ANNOTATED_EXPLICIT;
+ type.kind = DataType::BUILTIN;
+ type.builtin_type = Variant::SIGNAL;
+ // TODO: Add parameter info.
+ return type;
+ }
+ case UNDEFINED:
+ return DataType();
+ }
+ ERR_FAIL_V_MSG(DataType(), "Reaching unhandled type.");
+ }
+
+ Member() {}
+
+ Member(ClassNode *p_class) {
+ type = CLASS;
+ m_class = p_class;
+ }
+ Member(ConstantNode *p_constant) {
+ type = CONSTANT;
+ constant = p_constant;
+ }
+ Member(VariableNode *p_variable) {
+ type = VARIABLE;
+ variable = p_variable;
+ }
+ Member(SignalNode *p_signal) {
+ type = SIGNAL;
+ signal = p_signal;
+ }
+ Member(FunctionNode *p_function) {
+ type = FUNCTION;
+ function = p_function;
+ }
+ Member(EnumNode *p_enum) {
+ type = ENUM;
+ m_enum = p_enum;
+ }
+ Member(const EnumNode::Value &p_enum_value) {
+ type = ENUM_VALUE;
+ enum_value = p_enum_value;
+ }
+ };
+
+ IdentifierNode *identifier = nullptr;
+ String icon_path;
+ Vector<Member> members;
+ HashMap<StringName, int> members_indices;
+ ClassNode *outer = nullptr;
+ bool extends_used = false;
+ bool onready_used = false;
+ String extends_path;
+ Vector<StringName> extends; // List for indexing: extends A.B.C
+ DataType base_type;
+ String fqcn; // Fully-qualified class name. Identifies uniquely any class in the project.
+#ifdef TOOLS_ENABLED
+ String doc_description;
+ String doc_brief_description;
+ Vector<Pair<String, String>> doc_tutorials;
+
+ // EnumValue docs are parsed after itself, so we need a method to add/modify the doc property later.
+ void set_enum_value_doc(const StringName &p_name, const String &p_doc_description) {
+ ERR_FAIL_INDEX(members_indices[p_name], members.size());
+ members.write[members_indices[p_name]].enum_value.doc_description = p_doc_description;
+ }
+#endif // TOOLS_ENABLED
+
+ bool resolved_interface = false;
+ bool resolved_body = false;
+
+ Member get_member(const StringName &p_name) const {
+ return members[members_indices[p_name]];
+ }
+ bool has_member(const StringName &p_name) const {
+ return members_indices.has(p_name);
+ }
+ bool has_function(const StringName &p_name) const {
+ return has_member(p_name) && members[members_indices[p_name]].type == Member::FUNCTION;
+ }
+ template <class T>
+ void add_member(T *p_member_node) {
+ members_indices[p_member_node->identifier->name] = members.size();
+ members.push_back(Member(p_member_node));
+ }
+ void add_member(const EnumNode::Value &p_enum_value) {
+ members_indices[p_enum_value.identifier->name] = members.size();
+ members.push_back(Member(p_enum_value));
+ }
+
+ ClassNode() {
+ type = CLASS;
+ }
};
- struct ArrayNode : public Node {
+ struct ConstantNode : public Node {
+ IdentifierNode *identifier = nullptr;
+ ExpressionNode *initializer = nullptr;
+ TypeNode *datatype_specifier = nullptr;
+ bool infer_datatype = false;
+ int usages = 0;
+#ifdef TOOLS_ENABLED
+ String doc_description;
+#endif // TOOLS_ENABLED
- Vector<Node *> elements;
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
- ArrayNode() {
- type = TYPE_ARRAY;
- datatype.has_type = true;
- datatype.kind = DataType::BUILTIN;
- datatype.builtin_type = Variant::ARRAY;
+ ConstantNode() {
+ type = CONSTANT;
}
};
- struct DictionaryNode : public Node {
+ struct ContinueNode : public Node {
+ bool is_for_match = false;
+ ContinueNode() {
+ type = CONTINUE;
+ }
+ };
+ struct DictionaryNode : public ExpressionNode {
struct Pair {
+ ExpressionNode *key = nullptr;
+ ExpressionNode *value = nullptr;
+ };
+ Vector<Pair> elements;
- Node *key;
- Node *value;
+ enum Style {
+ LUA_TABLE,
+ PYTHON_DICT,
};
+ Style style = PYTHON_DICT;
- Vector<Pair> elements;
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
DictionaryNode() {
- type = TYPE_DICTIONARY;
- datatype.has_type = true;
- datatype.kind = DataType::BUILTIN;
- datatype.builtin_type = Variant::DICTIONARY;
- }
- };
-
- struct SelfNode : public Node {
- SelfNode() { type = TYPE_SELF; }
- };
-
- struct OperatorNode : public Node {
- enum Operator {
- //call/constructor operator
- OP_CALL,
- OP_PARENT_CALL,
- OP_YIELD,
- OP_IS,
- OP_IS_BUILTIN,
- //indexing operator
- OP_INDEX,
- OP_INDEX_NAMED,
- //unary operators
- OP_NEG,
- OP_POS,
- OP_NOT,
- OP_BIT_INVERT,
- //binary operators (in precedence order)
- OP_IN,
- OP_EQUAL,
- OP_NOT_EQUAL,
- OP_LESS,
- OP_LESS_EQUAL,
- OP_GREATER,
- OP_GREATER_EQUAL,
- OP_AND,
- OP_OR,
- OP_ADD,
- OP_SUB,
- OP_MUL,
- OP_DIV,
- OP_MOD,
- OP_SHIFT_LEFT,
- OP_SHIFT_RIGHT,
- OP_INIT_ASSIGN,
- OP_ASSIGN,
- OP_ASSIGN_ADD,
- OP_ASSIGN_SUB,
- OP_ASSIGN_MUL,
- OP_ASSIGN_DIV,
- OP_ASSIGN_MOD,
- OP_ASSIGN_SHIFT_LEFT,
- OP_ASSIGN_SHIFT_RIGHT,
- OP_ASSIGN_BIT_AND,
- OP_ASSIGN_BIT_OR,
- OP_ASSIGN_BIT_XOR,
- OP_BIT_AND,
- OP_BIT_OR,
- OP_BIT_XOR,
- //ternary operators
- OP_TERNARY_IF,
- OP_TERNARY_ELSE,
- };
+ type = DICTIONARY;
+ }
+ };
- Operator op;
+ struct ForNode : public Node {
+ IdentifierNode *variable = nullptr;
+ ExpressionNode *list = nullptr;
+ SuiteNode *loop = nullptr;
- Vector<Node *> arguments;
- DataType datatype;
- virtual DataType get_datatype() const { return datatype; }
- virtual void set_datatype(const DataType &p_datatype) { datatype = p_datatype; }
- OperatorNode() { type = TYPE_OPERATOR; }
+ ForNode() {
+ type = FOR;
+ }
};
- struct PatternNode : public Node {
+ struct FunctionNode : public Node {
+ IdentifierNode *identifier = nullptr;
+ Vector<ParameterNode *> parameters;
+ HashMap<StringName, int> parameters_indices;
+ TypeNode *return_type = nullptr;
+ SuiteNode *body = nullptr;
+ bool is_static = false;
+ bool is_coroutine = false;
+ MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+ MethodInfo info;
+#ifdef TOOLS_ENABLED
+ Vector<Variant> default_arg_values;
+ String doc_description;
+#endif // TOOLS_ENABLED
- enum PatternType {
- PT_CONSTANT,
- PT_BIND,
- PT_DICTIONARY,
- PT_ARRAY,
- PT_IGNORE_REST,
- PT_WILDCARD
+ bool resolved_signature = false;
+ bool resolved_body = false;
+
+ FunctionNode() {
+ type = FUNCTION;
+ }
+ };
+
+ struct GetNodeNode : public ExpressionNode {
+ LiteralNode *string = nullptr;
+ Vector<IdentifierNode *> chain;
+
+ GetNodeNode() {
+ type = GET_NODE;
+ }
+ };
+
+ struct IdentifierNode : public ExpressionNode {
+ StringName name;
+
+ enum Source {
+ UNDEFINED_SOURCE,
+ FUNCTION_PARAMETER,
+ LOCAL_CONSTANT,
+ LOCAL_VARIABLE,
+ LOCAL_ITERATOR, // `for` loop iterator.
+ LOCAL_BIND, // Pattern bind.
+ MEMBER_VARIABLE,
+ MEMBER_CONSTANT,
};
+ Source source = UNDEFINED_SOURCE;
- PatternType pt_type;
+ union {
+ ParameterNode *parameter_source = nullptr;
+ ConstantNode *constant_source;
+ VariableNode *variable_source;
+ IdentifierNode *bind_source;
+ };
- Node *constant;
- StringName bind;
- Map<ConstantNode *, PatternNode *> dictionary;
- Vector<PatternNode *> array;
+ int usages = 0; // Useful for binds/iterator variable.
+
+ IdentifierNode() {
+ type = IDENTIFIER;
+ }
};
- struct PatternBranchNode : public Node {
- Vector<PatternNode *> patterns;
- BlockNode *body;
+ struct IfNode : public Node {
+ ExpressionNode *condition = nullptr;
+ SuiteNode *true_block = nullptr;
+ SuiteNode *false_block = nullptr;
+
+ IfNode() {
+ type = IF;
+ }
+ };
+
+ struct LiteralNode : public ExpressionNode {
+ Variant value;
+
+ LiteralNode() {
+ type = LITERAL;
+ }
};
struct MatchNode : public Node {
- Node *val_to_match;
- Vector<PatternBranchNode *> branches;
+ ExpressionNode *test = nullptr;
+ Vector<MatchBranchNode *> branches;
- struct CompiledPatternBranch {
- Node *compiled_pattern;
- BlockNode *body;
- };
+ MatchNode() {
+ type = MATCH;
+ }
+ };
+
+ struct MatchBranchNode : public Node {
+ Vector<PatternNode *> patterns;
+ SuiteNode *block;
+ bool has_wildcard = false;
+
+ MatchBranchNode() {
+ type = MATCH_BRANCH;
+ }
+ };
+
+ struct ParameterNode : public Node {
+ IdentifierNode *identifier = nullptr;
+ ExpressionNode *default_value = nullptr;
+ TypeNode *datatype_specifier = nullptr;
+ bool infer_datatype = false;
+ int usages = 0;
+
+ ParameterNode() {
+ type = PARAMETER;
+ }
+ };
- Vector<CompiledPatternBranch> compiled_pattern_branches;
+ struct PassNode : public Node {
+ PassNode() {
+ type = PASS;
+ }
};
- struct ControlFlowNode : public Node {
- enum CFType {
- CF_IF,
- CF_FOR,
- CF_WHILE,
- CF_BREAK,
- CF_CONTINUE,
- CF_RETURN,
- CF_MATCH
+ struct PatternNode : public Node {
+ enum Type {
+ PT_LITERAL,
+ PT_EXPRESSION,
+ PT_BIND,
+ PT_ARRAY,
+ PT_DICTIONARY,
+ PT_REST,
+ PT_WILDCARD,
+ };
+ Type pattern_type = PT_LITERAL;
+
+ union {
+ LiteralNode *literal = nullptr;
+ IdentifierNode *bind;
+ ExpressionNode *expression;
+ };
+ Vector<PatternNode *> array;
+ bool rest_used = false; // For array/dict patterns.
+
+ struct Pair {
+ ExpressionNode *key = nullptr;
+ PatternNode *value_pattern = nullptr;
};
+ Vector<Pair> dictionary;
- CFType cf_type;
- Vector<Node *> arguments;
- BlockNode *body;
- BlockNode *body_else;
+ HashMap<StringName, IdentifierNode *> binds;
- MatchNode *match;
+ bool has_bind(const StringName &p_name);
+ IdentifierNode *get_bind(const StringName &p_name);
- ControlFlowNode *_else; //used for if
- ControlFlowNode() {
- type = TYPE_CONTROL_FLOW;
- cf_type = CF_IF;
- body = nullptr;
- body_else = nullptr;
+ PatternNode() {
+ type = PATTERN;
}
};
+ struct PreloadNode : public ExpressionNode {
+ ExpressionNode *path = nullptr;
+ String resolved_path;
+ Ref<Resource> resource;
- struct CastNode : public Node {
- Node *source_node;
- DataType cast_type;
- DataType return_type;
- virtual DataType get_datatype() const { return return_type; }
- virtual void set_datatype(const DataType &p_datatype) { return_type = p_datatype; }
- CastNode() { type = TYPE_CAST; }
+ PreloadNode() {
+ type = PRELOAD;
+ }
};
- struct AssertNode : public Node {
- Node *condition;
- Node *message;
- AssertNode() :
- condition(0),
- message(0) {
- type = TYPE_ASSERT;
+ struct ReturnNode : public Node {
+ ExpressionNode *return_value = nullptr;
+
+ ReturnNode() {
+ type = RETURN;
}
};
- struct BreakpointNode : public Node {
- BreakpointNode() { type = TYPE_BREAKPOINT; }
- };
+ struct SelfNode : public ExpressionNode {
+ ClassNode *current_class = nullptr;
- struct NewLineNode : public Node {
- NewLineNode() { type = TYPE_NEWLINE; }
+ SelfNode() {
+ type = SELF;
+ }
};
- struct Expression {
+ struct SignalNode : public Node {
+ IdentifierNode *identifier = nullptr;
+ Vector<ParameterNode *> parameters;
+ HashMap<StringName, int> parameters_indices;
+#ifdef TOOLS_ENABLED
+ String doc_description;
+#endif // TOOLS_ENABLED
+
+ SignalNode() {
+ type = SIGNAL;
+ }
+ };
- bool is_op;
+ struct SubscriptNode : public ExpressionNode {
+ ExpressionNode *base = nullptr;
union {
- OperatorNode::Operator op;
- Node *node;
+ ExpressionNode *index = nullptr;
+ IdentifierNode *attribute;
};
- };
- enum CompletionType {
- COMPLETION_NONE,
- COMPLETION_BUILT_IN_TYPE_CONSTANT,
- COMPLETION_GET_NODE,
- COMPLETION_FUNCTION,
- COMPLETION_IDENTIFIER,
- COMPLETION_PARENT_FUNCTION,
- COMPLETION_METHOD,
- COMPLETION_CALL_ARGUMENTS,
- COMPLETION_RESOURCE_PATH,
- COMPLETION_INDEX,
- COMPLETION_VIRTUAL_FUNC,
- COMPLETION_YIELD,
- COMPLETION_ASSIGN,
- COMPLETION_TYPE_HINT,
- COMPLETION_TYPE_HINT_INDEX,
+ bool is_attribute = false;
+
+ SubscriptNode() {
+ type = SUBSCRIPT;
+ }
};
-private:
- GDScriptTokenizer *tokenizer;
+ struct SuiteNode : public Node {
+ SuiteNode *parent_block = nullptr;
+ Vector<Node *> statements;
+ struct Local {
+ enum Type {
+ UNDEFINED,
+ CONSTANT,
+ VARIABLE,
+ PARAMETER,
+ FOR_VARIABLE,
+ PATTERN_BIND,
+ };
+ Type type = UNDEFINED;
+ union {
+ ConstantNode *constant = nullptr;
+ VariableNode *variable;
+ ParameterNode *parameter;
+ IdentifierNode *bind;
+ };
+ StringName name;
- Node *head;
- Node *list;
- template <class T>
- T *alloc_node();
-
- bool validating;
- bool for_completion;
- int parenthesis;
- bool error_set;
- String error;
- int error_line;
- int error_column;
- bool check_types;
- bool dependencies_only;
- List<String> dependencies;
-#ifdef DEBUG_ENABLED
- Set<int> *safe_lines;
-#endif // DEBUG_ENABLED
+ int start_line = 0, end_line = 0;
+ int start_column = 0, end_column = 0;
+ int leftmost_column = 0, rightmost_column = 0;
+
+ DataType get_datatype() const;
+ String get_name() const;
+
+ Local() {}
+ Local(ConstantNode *p_constant) {
+ type = CONSTANT;
+ constant = p_constant;
+ name = p_constant->identifier->name;
+
+ start_line = p_constant->start_line;
+ end_line = p_constant->end_line;
+ start_column = p_constant->start_column;
+ end_column = p_constant->end_column;
+ leftmost_column = p_constant->leftmost_column;
+ rightmost_column = p_constant->rightmost_column;
+ }
+ Local(VariableNode *p_variable) {
+ type = VARIABLE;
+ variable = p_variable;
+ name = p_variable->identifier->name;
+
+ start_line = p_variable->start_line;
+ end_line = p_variable->end_line;
+ start_column = p_variable->start_column;
+ end_column = p_variable->end_column;
+ leftmost_column = p_variable->leftmost_column;
+ rightmost_column = p_variable->rightmost_column;
+ }
+ Local(ParameterNode *p_parameter) {
+ type = PARAMETER;
+ parameter = p_parameter;
+ name = p_parameter->identifier->name;
+
+ start_line = p_parameter->start_line;
+ end_line = p_parameter->end_line;
+ start_column = p_parameter->start_column;
+ end_column = p_parameter->end_column;
+ leftmost_column = p_parameter->leftmost_column;
+ rightmost_column = p_parameter->rightmost_column;
+ }
+ Local(IdentifierNode *p_identifier) {
+ type = FOR_VARIABLE;
+ bind = p_identifier;
+ name = p_identifier->name;
+
+ start_line = p_identifier->start_line;
+ end_line = p_identifier->end_line;
+ start_column = p_identifier->start_column;
+ end_column = p_identifier->end_column;
+ leftmost_column = p_identifier->leftmost_column;
+ rightmost_column = p_identifier->rightmost_column;
+ }
+ };
+ Local empty;
+ Vector<Local> locals;
+ HashMap<StringName, int> locals_indices;
+
+ FunctionNode *parent_function = nullptr;
+ ForNode *parent_for = nullptr;
+ IfNode *parent_if = nullptr;
+
+ bool has_return = false;
+ bool has_continue = false;
+ bool has_unreachable_code = false; // Just so warnings aren't given more than once per block.
+
+ bool has_local(const StringName &p_name) const;
+ const Local &get_local(const StringName &p_name) const;
+ template <class T>
+ void add_local(T *p_local) {
+ locals_indices[p_local->identifier->name] = locals.size();
+ locals.push_back(Local(p_local));
+ }
+ void add_local(const Local &p_local) {
+ locals_indices[p_local.name] = locals.size();
+ locals.push_back(p_local);
+ }
-#ifdef DEBUG_ENABLED
- List<GDScriptWarning> warnings;
-#endif // DEBUG_ENABLED
+ SuiteNode() {
+ type = SUITE;
+ }
+ };
- int pending_newline;
+ struct TernaryOpNode : public ExpressionNode {
+ // Only one ternary operation exists, so no abstraction here.
+ ExpressionNode *condition = nullptr;
+ ExpressionNode *true_expr = nullptr;
+ ExpressionNode *false_expr = nullptr;
- struct IndentLevel {
- int indent;
- int tabs;
+ TernaryOpNode() {
+ type = TERNARY_OPERATOR;
+ }
+ };
+
+ struct TypeNode : public Node {
+ Vector<IdentifierNode *> type_chain;
- bool is_mixed(IndentLevel other) {
- return (
- (indent == other.indent && tabs != other.tabs) ||
- (indent > other.indent && tabs < other.tabs) ||
- (indent < other.indent && tabs > other.tabs));
+ TypeNode() {
+ type = TYPE;
}
+ };
- IndentLevel() :
- indent(0),
- tabs(0) {}
+ struct UnaryOpNode : public ExpressionNode {
+ enum OpType {
+ OP_POSITIVE,
+ OP_NEGATIVE,
+ OP_COMPLEMENT,
+ OP_LOGIC_NOT,
+ };
+
+ OpType operation;
+ Variant::Operator variant_op = Variant::OP_MAX;
+ ExpressionNode *operand = nullptr;
- IndentLevel(int p_indent, int p_tabs) :
- indent(p_indent),
- tabs(p_tabs) {}
+ UnaryOpNode() {
+ type = UNARY_OPERATOR;
+ }
};
- List<IndentLevel> indent_level;
+ struct VariableNode : public Node {
+ enum PropertyStyle {
+ PROP_NONE,
+ PROP_INLINE,
+ PROP_SETGET,
+ };
- String base_path;
- String self_path;
+ IdentifierNode *identifier = nullptr;
+ ExpressionNode *initializer = nullptr;
+ TypeNode *datatype_specifier = nullptr;
+ bool infer_datatype = false;
- ClassNode *current_class;
- FunctionNode *current_function;
- BlockNode *current_block;
+ PropertyStyle property = PROP_NONE;
+ union {
+ SuiteNode *setter = nullptr;
+ IdentifierNode *setter_pointer;
+ };
+ IdentifierNode *setter_parameter = nullptr;
+ union {
+ SuiteNode *getter = nullptr;
+ IdentifierNode *getter_pointer;
+ };
- bool _get_completable_identifier(CompletionType p_type, StringName &identifier);
- void _make_completable_call(int p_arg);
+ bool exported = false;
+ bool onready = false;
+ PropertyInfo export_info;
+ MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
+ int assignments = 0;
+ int usages = 0;
+#ifdef TOOLS_ENABLED
+ String doc_description;
+#endif // TOOLS_ENABLED
- CompletionType completion_type;
- StringName completion_cursor;
- Variant::Type completion_built_in_constant;
- Node *completion_node;
- ClassNode *completion_class;
- FunctionNode *completion_function;
- BlockNode *completion_block;
- int completion_line;
- int completion_argument;
- bool completion_found;
- bool completion_ident_is_call;
+ VariableNode() {
+ type = VARIABLE;
+ }
+ };
- PropertyInfo current_export;
+ struct WhileNode : public Node {
+ ExpressionNode *condition = nullptr;
+ SuiteNode *loop = nullptr;
- MultiplayerAPI::RPCMode rpc_mode;
+ WhileNode() {
+ type = WHILE;
+ }
+ };
- void _set_error(const String &p_error, int p_line = -1, int p_column = -1);
-#ifdef DEBUG_ENABLED
- void _add_warning(int p_code, int p_line = -1, const String &p_symbol1 = String(), const String &p_symbol2 = String(), const String &p_symbol3 = String(), const String &p_symbol4 = String());
- void _add_warning(int p_code, int p_line, const Vector<String> &p_symbols);
-#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 p_parsing_constant = false);
- bool _enter_indent_block(BlockNode *p_block = nullptr);
- bool _parse_newline();
- Node *_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign = false, bool p_parsing_constant = false);
- Node *_reduce_expression(Node *p_node, bool p_to_const = false);
- Node *_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const = false, bool p_allow_assign = false);
- bool _reduce_export_var_type(Variant &p_value, int p_line = 0);
-
- PatternNode *_parse_pattern(bool p_static);
- void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static);
- void _transform_match_statment(MatchNode *p_match_statement);
- void _generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings);
-
- void _parse_block(BlockNode *p_block, bool p_static);
- void _parse_extends(ClassNode *p_class);
- void _parse_class(ClassNode *p_class);
- bool _end_statement();
-
- 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;
- DataType _type_from_property(const PropertyInfo &p_property, bool p_nil_is_variant = true) const;
- DataType _type_from_gdtype(const GDScriptDataType &p_gdtype) const;
- DataType _get_operation_type(const Variant::Operator p_op, const DataType &p_a, const DataType &p_b, bool &r_valid) const;
- Variant::Operator _get_variant_operation(const OperatorNode::Operator &p_op) const;
- bool _get_function_signature(DataType &p_base_type, const StringName &p_function, DataType &r_return_type, List<DataType> &r_arg_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) const;
- bool _get_member_type(const DataType &p_base_type, const StringName &p_member, DataType &r_member_type) const;
- bool _is_type_compatible(const DataType &p_container, const DataType &p_expression, bool p_allow_implicit_conversion = false) const;
- Node *_get_default_value_for_type(const DataType &p_type, int p_line = -1);
-
- DataType _reduce_node_type(Node *p_node);
- DataType _reduce_function_call_type(const OperatorNode *p_call);
- DataType _reduce_identifier_type(const DataType *p_base_type, const StringName &p_identifier, int p_line, bool p_is_indexing);
- void _check_class_level_types(ClassNode *p_class);
- void _check_class_blocks_types(ClassNode *p_class);
- void _check_function_types(FunctionNode *p_function);
- void _check_block_types(BlockNode *p_block);
- _FORCE_INLINE_ void _mark_line_as_safe(int p_line) const {
-#ifdef DEBUG_ENABLED
- if (safe_lines) safe_lines->insert(p_line);
-#endif // DEBUG_ENABLED
- }
- _FORCE_INLINE_ void _mark_line_as_unsafe(int p_line) const {
-#ifdef DEBUG_ENABLED
- if (safe_lines) safe_lines->erase(p_line);
-#endif // DEBUG_ENABLED
- }
+ enum CompletionType {
+ COMPLETION_NONE,
+ COMPLETION_ANNOTATION, // Annotation (following @).
+ COMPLETION_ANNOTATION_ARGUMENTS, // Annotation arguments hint.
+ COMPLETION_ASSIGN, // Assignment based on type (e.g. enum values).
+ COMPLETION_ATTRIBUTE, // After id.| to look for members.
+ COMPLETION_ATTRIBUTE_METHOD, // After id.| to look for methods.
+ COMPLETION_BUILT_IN_TYPE_CONSTANT, // Constants inside a built-in type (e.g. Color.blue).
+ COMPLETION_CALL_ARGUMENTS, // Complete with nodes, input actions, enum values (or usual expressions).
+ // TODO: COMPLETION_DECLARATION, // Potential declaration (var, const, func).
+ COMPLETION_GET_NODE, // Get node with $ notation.
+ COMPLETION_IDENTIFIER, // List available identifiers in scope.
+ COMPLETION_INHERIT_TYPE, // Type after extends. Exclude non-viable types (built-ins, enums, void). Includes subtypes using the argument index.
+ COMPLETION_METHOD, // List available methods in scope.
+ COMPLETION_OVERRIDE_METHOD, // Override implementation, also for native virtuals.
+ COMPLETION_PROPERTY_DECLARATION, // Property declaration (get, set).
+ COMPLETION_PROPERTY_DECLARATION_OR_TYPE, // Property declaration (get, set) or a type hint.
+ COMPLETION_PROPERTY_METHOD, // Property setter or getter (list available methods).
+ COMPLETION_RESOURCE_PATH, // For load/preload.
+ COMPLETION_SUBSCRIPT, // Inside id[|].
+ COMPLETION_SUPER_METHOD, // After super.
+ COMPLETION_TYPE_ATTRIBUTE, // Attribute in type name (Type.|).
+ COMPLETION_TYPE_NAME, // Name of type (after :).
+ COMPLETION_TYPE_NAME_OR_VOID, // Same as TYPE_NAME, but allows void (in function return type).
+ };
- Error _parse(const String &p_base_path);
+ struct CompletionContext {
+ CompletionType type = COMPLETION_NONE;
+ ClassNode *current_class = nullptr;
+ FunctionNode *current_function = nullptr;
+ SuiteNode *current_suite = nullptr;
+ int current_line = -1;
+ int current_argument = -1;
+ Variant::Type builtin_type = Variant::VARIANT_MAX;
+ Node *node = nullptr;
+ Object *base = nullptr;
+ List<Ref<GDScriptParserRef>> dependent_parsers;
+ };
-public:
- bool has_error() const;
- String get_error() const;
- int get_error_line() const;
- int get_error_column() const;
+ struct CompletionCall {
+ Node *call = nullptr;
+ int argument = -1;
+ };
+
+private:
+ friend class GDScriptAnalyzer;
+
+ bool _is_tool = false;
+ String script_path;
+ bool for_completion = false;
+ bool panic_mode = false;
+ bool can_break = false;
+ bool can_continue = false;
+ bool is_continue_match = false; // Whether a `continue` will act on a `match`.
+ bool is_ignoring_warnings = false;
+ List<bool> multiline_stack;
+
+ ClassNode *head = nullptr;
+ Node *list = nullptr;
+ List<ParserError> errors;
#ifdef DEBUG_ENABLED
- const List<GDScriptWarning> &get_warnings() const { return warnings; }
-#endif // DEBUG_ENABLED
- Error parse(const String &p_code, const String &p_base_path = "", bool p_just_validate = false, const String &p_self_path = "", bool p_for_completion = false, Set<int> *r_safe_lines = nullptr, bool p_dependencies_only = false);
- Error parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path = "", const String &p_self_path = "");
+ List<GDScriptWarning> warnings;
+ Set<String> ignored_warnings;
+ Set<int> unsafe_lines;
+#endif
- bool is_tool_script() const;
- const Node *get_parse_tree() const;
+ GDScriptTokenizer tokenizer;
+ GDScriptTokenizer::Token previous;
+ GDScriptTokenizer::Token current;
+
+ ClassNode *current_class = nullptr;
+ FunctionNode *current_function = nullptr;
+ SuiteNode *current_suite = nullptr;
+
+ CompletionContext completion_context;
+ CompletionCall completion_call;
+ List<CompletionCall> completion_call_stack;
+ bool passed_cursor = false;
+
+ typedef bool (GDScriptParser::*AnnotationAction)(const AnnotationNode *p_annotation, Node *p_target);
+ struct AnnotationInfo {
+ enum TargetKind {
+ NONE = 0,
+ SCRIPT = 1 << 0,
+ CLASS = 1 << 1,
+ VARIABLE = 1 << 2,
+ CONSTANT = 1 << 3,
+ SIGNAL = 1 << 4,
+ FUNCTION = 1 << 5,
+ STATEMENT = 1 << 6,
+ CLASS_LEVEL = CLASS | VARIABLE | FUNCTION,
+ };
+ uint32_t target_kind = 0; // Flags.
+ AnnotationAction apply = nullptr;
+ MethodInfo info;
+ };
+ HashMap<StringName, AnnotationInfo> valid_annotations;
+ List<AnnotationNode *> annotation_stack;
+
+ typedef ExpressionNode *(GDScriptParser::*ParseFunction)(ExpressionNode *p_previous_operand, bool p_can_assign);
+ // Higher value means higher precedence (i.e. is evaluated first).
+ enum Precedence {
+ PREC_NONE,
+ PREC_ASSIGNMENT,
+ PREC_CAST,
+ PREC_TERNARY,
+ PREC_LOGIC_OR,
+ PREC_LOGIC_AND,
+ PREC_LOGIC_NOT,
+ PREC_CONTENT_TEST,
+ PREC_COMPARISON,
+ PREC_BIT_OR,
+ PREC_BIT_XOR,
+ PREC_BIT_AND,
+ PREC_BIT_SHIFT,
+ PREC_ADDITION_SUBTRACTION,
+ PREC_FACTOR,
+ PREC_SIGN,
+ PREC_BIT_NOT,
+ PREC_TYPE_TEST,
+ PREC_AWAIT,
+ PREC_CALL,
+ PREC_ATTRIBUTE,
+ PREC_SUBSCRIPT,
+ PREC_PRIMARY,
+ };
+ struct ParseRule {
+ ParseFunction prefix = nullptr;
+ ParseFunction infix = nullptr;
+ Precedence precedence = PREC_NONE;
+ };
+ static ParseRule *get_rule(GDScriptTokenizer::Token::Type p_token_type);
- //completion info
+ template <class T>
+ T *alloc_node() {
+ T *node = memnew(T);
- CompletionType get_completion_type();
- StringName get_completion_cursor();
- int get_completion_line();
- Variant::Type get_completion_built_in_constant();
- Node *get_completion_node();
- ClassNode *get_completion_class();
- BlockNode *get_completion_block();
- FunctionNode *get_completion_function();
- int get_completion_argument_index();
- int get_completion_identifier_is_function();
+ node->next = list;
+ list = node;
- const List<String> &get_dependencies() const { return dependencies; }
+ // TODO: Properly set positions for all nodes.
+ node->start_line = previous.start_line;
+ node->end_line = previous.end_line;
+ node->start_column = previous.start_column;
+ node->end_column = previous.end_column;
+ node->leftmost_column = previous.leftmost_column;
+ node->rightmost_column = previous.rightmost_column;
+ return node;
+ }
void clear();
+ void push_error(const String &p_message, const Node *p_origin = nullptr);
+#ifdef DEBUG_ENABLED
+ void push_warning(const Node *p_source, GDScriptWarning::Code p_code, const String &p_symbol1 = String(), const String &p_symbol2 = String(), const String &p_symbol3 = String(), const String &p_symbol4 = String());
+ void push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols);
+#endif
+
+ void make_completion_context(CompletionType p_type, Node *p_node, int p_argument = -1, bool p_force = false);
+ void make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force = false);
+ void push_completion_call(Node *p_call);
+ void pop_completion_call();
+ void set_last_completion_call_arg(int p_argument);
+
+ GDScriptTokenizer::Token advance();
+ bool match(GDScriptTokenizer::Token::Type p_token_type);
+ bool check(GDScriptTokenizer::Token::Type p_token_type);
+ bool consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message);
+ bool is_at_end();
+ bool is_statement_end();
+ void end_statement(const String &p_context);
+ void synchronize();
+ void push_multiline(bool p_state);
+ void pop_multiline();
+
+ // Main blocks.
+ void parse_program();
+ ClassNode *parse_class();
+ void parse_class_name();
+ void parse_extends();
+ void parse_class_body();
+ template <class T>
+ void parse_class_member(T *(GDScriptParser::*p_parse_function)(), AnnotationInfo::TargetKind p_target, const String &p_member_kind);
+ SignalNode *parse_signal();
+ EnumNode *parse_enum();
+ ParameterNode *parse_parameter();
+ FunctionNode *parse_function();
+ SuiteNode *parse_suite(const String &p_context, SuiteNode *p_suite = nullptr);
+ // Annotations
+ AnnotationNode *parse_annotation(uint32_t p_valid_targets);
+ bool register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, int p_optional_arguments = 0, bool p_is_vararg = false);
+ bool validate_annotation_arguments(AnnotationNode *p_annotation);
+ void clear_unused_annotations();
+ bool tool_annotation(const AnnotationNode *p_annotation, Node *p_target);
+ bool icon_annotation(const AnnotationNode *p_annotation, Node *p_target);
+ bool onready_annotation(const AnnotationNode *p_annotation, Node *p_target);
+ template <PropertyHint t_hint, Variant::Type t_type>
+ bool export_annotations(const AnnotationNode *p_annotation, Node *p_target);
+ bool warning_annotations(const AnnotationNode *p_annotation, Node *p_target);
+ template <MultiplayerAPI::RPCMode t_mode>
+ bool network_annotations(const AnnotationNode *p_annotation, Node *p_target);
+ // Statements.
+ Node *parse_statement();
+ VariableNode *parse_variable();
+ VariableNode *parse_variable(bool p_allow_property);
+ VariableNode *parse_property(VariableNode *p_variable, bool p_need_indent);
+ void parse_property_getter(VariableNode *p_variable);
+ void parse_property_setter(VariableNode *p_variable);
+ ConstantNode *parse_constant();
+ AssertNode *parse_assert();
+ BreakNode *parse_break();
+ ContinueNode *parse_continue();
+ ForNode *parse_for();
+ IfNode *parse_if(const String &p_token = "if");
+ MatchNode *parse_match();
+ MatchBranchNode *parse_match_branch();
+ PatternNode *parse_match_pattern(PatternNode *p_root_pattern = nullptr);
+ WhileNode *parse_while();
+ // Expressions.
+ ExpressionNode *parse_expression(bool p_can_assign, bool p_stop_on_assign = false);
+ ExpressionNode *parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign = false);
+ ExpressionNode *parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign);
+ LiteralNode *parse_literal();
+ ExpressionNode *parse_self(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign);
+ IdentifierNode *parse_identifier();
+ ExpressionNode *parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_array(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_call(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_await(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign);
+ ExpressionNode *parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign);
+ TypeNode *parse_type(bool p_allow_void = false);
+#ifdef TOOLS_ENABLED
+ // Doc comments.
+ int class_doc_line = 0x7FFFFFFF;
+ bool has_comment(int p_line);
+ String get_doc_comment(int p_line, bool p_single_line = false);
+ void get_class_doc_comment(int p_line, String &p_brief, String &p_desc, Vector<Pair<String, String>> &p_tutorials, bool p_inner_class);
+#endif // TOOLS_ENABLED
+
+public:
+ Error parse(const String &p_source_code, const String &p_script_path, bool p_for_completion);
+ ClassNode *get_tree() const { return head; }
+ bool is_tool() const { return _is_tool; }
+ static Variant::Type get_builtin_type(const StringName &p_type);
+
+ CompletionContext get_completion_context() const { return completion_context; }
+ CompletionCall get_completion_call() const { return completion_call; }
+ void get_annotation_list(List<MethodInfo> *r_annotations) const;
+
+ const List<ParserError> &get_errors() const { return errors; }
+ const List<String> get_dependencies() const {
+ // TODO: Keep track of deps.
+ return List<String>();
+ }
+#ifdef DEBUG_ENABLED
+ const List<GDScriptWarning> &get_warnings() const { return warnings; }
+ const Set<int> &get_unsafe_lines() const { return unsafe_lines; }
+ int get_last_line_number() const { return current.end_line; }
+#endif
+
GDScriptParser();
~GDScriptParser();
+
+#ifdef DEBUG_ENABLED
+ class TreePrinter {
+ int indent_level = 0;
+ String indent;
+ StringBuilder printed;
+ bool pending_indent = false;
+
+ void increase_indent();
+ void decrease_indent();
+ void push_line(const String &p_line = String());
+ void push_text(const String &p_text);
+
+ void print_annotation(AnnotationNode *p_annotation);
+ void print_array(ArrayNode *p_array);
+ void print_assert(AssertNode *p_assert);
+ void print_assignment(AssignmentNode *p_assignment);
+ void print_await(AwaitNode *p_await);
+ void print_binary_op(BinaryOpNode *p_binary_op);
+ void print_call(CallNode *p_call);
+ void print_cast(CastNode *p_cast);
+ void print_class(ClassNode *p_class);
+ void print_constant(ConstantNode *p_constant);
+ void print_dictionary(DictionaryNode *p_dictionary);
+ void print_expression(ExpressionNode *p_expression);
+ void print_enum(EnumNode *p_enum);
+ void print_for(ForNode *p_for);
+ void print_function(FunctionNode *p_function);
+ void print_get_node(GetNodeNode *p_get_node);
+ void print_if(IfNode *p_if, bool p_is_elif = false);
+ void print_identifier(IdentifierNode *p_identifier);
+ void print_literal(LiteralNode *p_literal);
+ void print_match(MatchNode *p_match);
+ void print_match_branch(MatchBranchNode *p_match_branch);
+ void print_match_pattern(PatternNode *p_match_pattern);
+ void print_parameter(ParameterNode *p_parameter);
+ void print_preload(PreloadNode *p_preload);
+ void print_return(ReturnNode *p_return);
+ void print_self(SelfNode *p_self);
+ void print_signal(SignalNode *p_signal);
+ void print_statement(Node *p_statement);
+ void print_subscript(SubscriptNode *p_subscript);
+ void print_suite(SuiteNode *p_suite);
+ void print_type(TypeNode *p_type);
+ void print_ternary_op(TernaryOpNode *p_ternary_op);
+ void print_unary_op(UnaryOpNode *p_unary_op);
+ void print_variable(VariableNode *p_variable);
+ void print_while(WhileNode *p_while);
+
+ public:
+ void print_tree(const GDScriptParser &p_parser);
+ };
+#endif // DEBUG_ENABLED
+ static void cleanup();
};
#endif // GDSCRIPT_PARSER_H
diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp
index d42ca52731..315b8ee3b4 100644
--- a/modules/gdscript/gdscript_tokenizer.cpp
+++ b/modules/gdscript/gdscript_tokenizer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,1503 +30,1400 @@
#include "gdscript_tokenizer.h"
-#include "core/io/marshalls.h"
-#include "core/map.h"
-#include "core/print_string.h"
-#include "gdscript_functions.h"
-
-const char *GDScriptTokenizer::token_names[TK_MAX] = {
- "Empty",
- "Identifier",
- "Constant",
- "Self",
- "Built-In Type",
- "Built-In Func",
- "In",
- "'=='",
- "'!='",
- "'<'",
- "'<='",
- "'>'",
- "'>='",
- "'and'",
- "'or'",
- "'not'",
- "'+'",
- "'-'",
- "'*'",
- "'/'",
- "'%'",
- "'<<'",
- "'>>'",
- "'='",
- "'+='",
- "'-='",
- "'*='",
- "'/='",
- "'%='",
- "'<<='",
- "'>>='",
- "'&='",
- "'|='",
- "'^='",
- "'&'",
- "'|'",
- "'^'",
- "'~'",
- //"Plus Plus",
- //"Minus Minus",
- "if",
- "elif",
- "else",
- "for",
- "while",
- "break",
- "continue",
- "pass",
- "return",
- "match",
- "func",
- "class",
- "class_name",
- "extends",
- "is",
- "onready",
- "tool",
- "static",
- "export",
- "setget",
- "const",
- "var",
- "as",
- "void",
- "enum",
- "preload",
- "assert",
- "yield",
- "signal",
- "breakpoint",
- "remote",
- "master",
- "puppet",
- "remotesync",
- "mastersync",
- "puppetsync",
- "'['",
- "']'",
- "'{'",
- "'}'",
- "'('",
- "')'",
- "','",
- "';'",
- "'.'",
- "'?'",
- "':'",
- "'$'",
- "'->'",
- "'\\n'",
- "PI",
- "TAU",
- "_",
- "INF",
- "NAN",
- "Error",
- "EOF",
- "Cursor"
+#include "core/error/error_macros.h"
+
+#ifdef TOOLS_ENABLED
+#include "editor/editor_settings.h"
+#endif
+
+static const char *token_names[] = {
+ "Empty", // EMPTY,
+ // Basic
+ "Annotation", // ANNOTATION
+ "Identifier", // IDENTIFIER,
+ "Literal", // LITERAL,
+ // Comparison
+ "<", // LESS,
+ "<=", // LESS_EQUAL,
+ ">", // GREATER,
+ ">=", // GREATER_EQUAL,
+ "==", // EQUAL_EQUAL,
+ "!=", // BANG_EQUAL,
+ // Logical
+ "and", // AND,
+ "or", // OR,
+ "not", // NOT,
+ "&&", // AMPERSAND_AMPERSAND,
+ "||", // PIPE_PIPE,
+ "!", // BANG,
+ // Bitwise
+ "&", // AMPERSAND,
+ "|", // PIPE,
+ "~", // TILDE,
+ "^", // CARET,
+ "<<", // LESS_LESS,
+ ">>", // GREATER_GREATER,
+ // Math
+ "+", // PLUS,
+ "-", // MINUS,
+ "*", // STAR,
+ "/", // SLASH,
+ "%", // PERCENT,
+ // Assignment
+ "=", // EQUAL,
+ "+=", // PLUS_EQUAL,
+ "-=", // MINUS_EQUAL,
+ "*=", // STAR_EQUAL,
+ "/=", // SLASH_EQUAL,
+ "%=", // PERCENT_EQUAL,
+ "<<=", // LESS_LESS_EQUAL,
+ ">>=", // GREATER_GREATER_EQUAL,
+ "&=", // AMPERSAND_EQUAL,
+ "|=", // PIPE_EQUAL,
+ "^=", // CARET_EQUAL,
+ // Control flow
+ "if", // IF,
+ "elif", // ELIF,
+ "else", // ELSE,
+ "for", // FOR,
+ "while", // WHILE,
+ "break", // BREAK,
+ "continue", // CONTINUE,
+ "pass", // PASS,
+ "return", // RETURN,
+ "match", // MATCH,
+ // Keywords
+ "as", // AS,
+ "assert", // ASSERT,
+ "await", // AWAIT,
+ "breakpoint", // BREAKPOINT,
+ "class", // CLASS,
+ "class_name", // CLASS_NAME,
+ "const", // CONST,
+ "enum", // ENUM,
+ "extends", // EXTENDS,
+ "func", // FUNC,
+ "in", // IN,
+ "is", // IS,
+ "namespace", // NAMESPACE
+ "preload", // PRELOAD,
+ "self", // SELF,
+ "signal", // SIGNAL,
+ "static", // STATIC,
+ "super", // SUPER,
+ "trait", // TRAIT,
+ "var", // VAR,
+ "void", // VOID,
+ "yield", // YIELD,
+ // Punctuation
+ "[", // BRACKET_OPEN,
+ "]", // BRACKET_CLOSE,
+ "{", // BRACE_OPEN,
+ "}", // BRACE_CLOSE,
+ "(", // PARENTHESIS_OPEN,
+ ")", // PARENTHESIS_CLOSE,
+ ",", // COMMA,
+ ";", // SEMICOLON,
+ ".", // PERIOD,
+ "..", // PERIOD_PERIOD,
+ ":", // COLON,
+ "$", // DOLLAR,
+ "->", // FORWARD_ARROW,
+ "_", // UNDERSCORE,
+ // Whitespace
+ "Newline", // NEWLINE,
+ "Indent", // INDENT,
+ "Dedent", // DEDENT,
+ // Constants
+ "PI", // CONST_PI,
+ "TAU", // CONST_TAU,
+ "INF", // CONST_INF,
+ "NaN", // CONST_NAN,
+ // Error message improvement
+ "VCS conflict marker", // VCS_CONFLICT_MARKER,
+ "`", // BACKTICK,
+ "?", // QUESTION_MARK,
+ // Special
+ "Error", // ERROR,
+ "End of file", // EOF,
};
-struct _bit {
- Variant::Type type;
- const char *text;
-};
-//built in types
-
-static const _bit _type_list[] = {
- //types
- { Variant::BOOL, "bool" },
- { Variant::INT, "int" },
- { Variant::FLOAT, "float" },
- { Variant::STRING, "String" },
- { Variant::VECTOR2, "Vector2" },
- { Variant::VECTOR2I, "Vector2i" },
- { Variant::RECT2, "Rect2" },
- { Variant::RECT2I, "Rect2i" },
- { Variant::TRANSFORM2D, "Transform2D" },
- { Variant::VECTOR3, "Vector3" },
- { Variant::VECTOR3I, "Vector3i" },
- { Variant::AABB, "AABB" },
- { Variant::PLANE, "Plane" },
- { Variant::QUAT, "Quat" },
- { Variant::BASIS, "Basis" },
- { Variant::TRANSFORM, "Transform" },
- { Variant::COLOR, "Color" },
- { Variant::_RID, "RID" },
- { Variant::OBJECT, "Object" },
- { Variant::STRING_NAME, "StringName" },
- { Variant::NODE_PATH, "NodePath" },
- { Variant::DICTIONARY, "Dictionary" },
- { Variant::CALLABLE, "Callable" },
- { Variant::SIGNAL, "Signal" },
- { Variant::ARRAY, "Array" },
- { Variant::PACKED_BYTE_ARRAY, "PackedByteArray" },
- { Variant::PACKED_INT32_ARRAY, "PackedInt32Array" },
- { Variant::PACKED_INT64_ARRAY, "PackedInt64Array" },
- { Variant::PACKED_FLOAT32_ARRAY, "PackedFloat32Array" },
- { Variant::PACKED_FLOAT64_ARRAY, "PackedFloat64Array" },
- { Variant::PACKED_STRING_ARRAY, "PackedStringArray" },
- { Variant::PACKED_VECTOR2_ARRAY, "PackedVector2Array" },
- { Variant::PACKED_VECTOR3_ARRAY, "PackedVector3Array" },
- { Variant::PACKED_COLOR_ARRAY, "PackedColorArray" },
- { Variant::VARIANT_MAX, nullptr },
-};
-
-struct _kws {
- GDScriptTokenizer::Token token;
- const char *text;
-};
-
-static const _kws _keyword_list[] = {
- //ops
- { GDScriptTokenizer::TK_OP_IN, "in" },
- { GDScriptTokenizer::TK_OP_NOT, "not" },
- { GDScriptTokenizer::TK_OP_OR, "or" },
- { GDScriptTokenizer::TK_OP_AND, "and" },
- //func
- { GDScriptTokenizer::TK_PR_FUNCTION, "func" },
- { GDScriptTokenizer::TK_PR_CLASS, "class" },
- { GDScriptTokenizer::TK_PR_CLASS_NAME, "class_name" },
- { GDScriptTokenizer::TK_PR_EXTENDS, "extends" },
- { GDScriptTokenizer::TK_PR_IS, "is" },
- { GDScriptTokenizer::TK_PR_ONREADY, "onready" },
- { GDScriptTokenizer::TK_PR_TOOL, "tool" },
- { GDScriptTokenizer::TK_PR_STATIC, "static" },
- { GDScriptTokenizer::TK_PR_EXPORT, "export" },
- { GDScriptTokenizer::TK_PR_SETGET, "setget" },
- { GDScriptTokenizer::TK_PR_VAR, "var" },
- { GDScriptTokenizer::TK_PR_AS, "as" },
- { GDScriptTokenizer::TK_PR_VOID, "void" },
- { GDScriptTokenizer::TK_PR_PRELOAD, "preload" },
- { GDScriptTokenizer::TK_PR_ASSERT, "assert" },
- { GDScriptTokenizer::TK_PR_YIELD, "yield" },
- { GDScriptTokenizer::TK_PR_SIGNAL, "signal" },
- { GDScriptTokenizer::TK_PR_BREAKPOINT, "breakpoint" },
- { GDScriptTokenizer::TK_PR_REMOTE, "remote" },
- { GDScriptTokenizer::TK_PR_MASTER, "master" },
- { GDScriptTokenizer::TK_PR_PUPPET, "puppet" },
- { GDScriptTokenizer::TK_PR_REMOTESYNC, "remotesync" },
- { GDScriptTokenizer::TK_PR_MASTERSYNC, "mastersync" },
- { GDScriptTokenizer::TK_PR_PUPPETSYNC, "puppetsync" },
- { GDScriptTokenizer::TK_PR_CONST, "const" },
- { GDScriptTokenizer::TK_PR_ENUM, "enum" },
- //controlflow
- { GDScriptTokenizer::TK_CF_IF, "if" },
- { GDScriptTokenizer::TK_CF_ELIF, "elif" },
- { GDScriptTokenizer::TK_CF_ELSE, "else" },
- { GDScriptTokenizer::TK_CF_FOR, "for" },
- { GDScriptTokenizer::TK_CF_WHILE, "while" },
- { GDScriptTokenizer::TK_CF_BREAK, "break" },
- { GDScriptTokenizer::TK_CF_CONTINUE, "continue" },
- { GDScriptTokenizer::TK_CF_RETURN, "return" },
- { GDScriptTokenizer::TK_CF_MATCH, "match" },
- { GDScriptTokenizer::TK_CF_PASS, "pass" },
- { GDScriptTokenizer::TK_SELF, "self" },
- { GDScriptTokenizer::TK_CONST_PI, "PI" },
- { GDScriptTokenizer::TK_CONST_TAU, "TAU" },
- { GDScriptTokenizer::TK_WILDCARD, "_" },
- { GDScriptTokenizer::TK_CONST_INF, "INF" },
- { GDScriptTokenizer::TK_CONST_NAN, "NAN" },
- { GDScriptTokenizer::TK_ERROR, nullptr }
-};
-
-const char *GDScriptTokenizer::get_token_name(Token p_token) {
+// Avoid desync.
+static_assert(sizeof(token_names) / sizeof(token_names[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of token names don't match the amount of token types.");
- ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>");
- return token_names[p_token];
+const char *GDScriptTokenizer::Token::get_name() const {
+ ERR_FAIL_INDEX_V_MSG(type, TK_MAX, "<error>", "Using token type out of the enum.");
+ return token_names[type];
}
-bool GDScriptTokenizer::is_token_literal(int p_offset, bool variable_safe) const {
- switch (get_token(p_offset)) {
- // Can always be literal:
- case TK_IDENTIFIER:
-
- case TK_PR_ONREADY:
- case TK_PR_TOOL:
- case TK_PR_STATIC:
- case TK_PR_EXPORT:
- case TK_PR_SETGET:
- case TK_PR_SIGNAL:
- case TK_PR_REMOTE:
- case TK_PR_MASTER:
- case TK_PR_PUPPET:
- case TK_PR_REMOTESYNC:
- case TK_PR_MASTERSYNC:
- case TK_PR_PUPPETSYNC:
+bool GDScriptTokenizer::Token::is_identifier() const {
+ // Note: Most keywords should not be recognized as identifiers.
+ // These are only exceptions for stuff that already is on the engine's API.
+ switch (type) {
+ case IDENTIFIER:
+ case MATCH: // Used in String.match().
return true;
-
- // Literal for non-variables only:
- case TK_BUILT_IN_TYPE:
- case TK_BUILT_IN_FUNC:
-
- case TK_OP_IN:
- //case TK_OP_NOT:
- //case TK_OP_OR:
- //case TK_OP_AND:
-
- case TK_PR_CLASS:
- case TK_PR_CONST:
- case TK_PR_ENUM:
- case TK_PR_PRELOAD:
- case TK_PR_FUNCTION:
- case TK_PR_EXTENDS:
- case TK_PR_ASSERT:
- case TK_PR_YIELD:
- case TK_PR_VAR:
-
- case TK_CF_IF:
- case TK_CF_ELIF:
- case TK_CF_ELSE:
- case TK_CF_FOR:
- case TK_CF_WHILE:
- case TK_CF_BREAK:
- case TK_CF_CONTINUE:
- case TK_CF_RETURN:
- case TK_CF_MATCH:
- case TK_CF_PASS:
- case TK_SELF:
- case TK_CONST_PI:
- case TK_CONST_TAU:
- case TK_WILDCARD:
- case TK_CONST_INF:
- case TK_CONST_NAN:
- case TK_ERROR:
- return !variable_safe;
-
- case TK_CONSTANT: {
- switch (get_token_constant(p_offset).get_type()) {
- case Variant::NIL:
- case Variant::BOOL:
- return true;
- default:
- return false;
- }
- }
default:
return false;
}
}
-StringName GDScriptTokenizer::get_token_literal(int p_offset) const {
- Token token = get_token(p_offset);
- switch (token) {
- case TK_IDENTIFIER:
- return get_token_identifier(p_offset);
- case TK_BUILT_IN_TYPE: {
- Variant::Type type = get_token_type(p_offset);
- int idx = 0;
-
- while (_type_list[idx].text) {
- if (type == _type_list[idx].type) {
- return _type_list[idx].text;
- }
- idx++;
- }
- } break; // Shouldn't get here, stuff happens
- case TK_BUILT_IN_FUNC:
- return GDScriptFunctions::get_func_name(get_token_built_in_func(p_offset));
- case TK_CONSTANT: {
- const Variant value = get_token_constant(p_offset);
-
- switch (value.get_type()) {
- case Variant::NIL:
- return "null";
- case Variant::BOOL:
- return value ? "true" : "false";
- default: {
- }
- }
- } break;
- case TK_OP_AND:
- case TK_OP_OR:
- break; // Don't get into default, since they can be non-literal
- default: {
- int idx = 0;
-
- while (_keyword_list[idx].text) {
- if (token == _keyword_list[idx].token) {
- return _keyword_list[idx].text;
- }
- idx++;
- }
- }
+bool GDScriptTokenizer::Token::is_node_name() const {
+ // This is meant to allow keywords with the $ notation, but not as general identifiers.
+ switch (type) {
+ case IDENTIFIER:
+ case AND:
+ case AS:
+ case ASSERT:
+ case AWAIT:
+ case BREAK:
+ case BREAKPOINT:
+ case CLASS_NAME:
+ case CLASS:
+ case CONST:
+ case CONTINUE:
+ case ELIF:
+ case ELSE:
+ case ENUM:
+ case EXTENDS:
+ case FOR:
+ case FUNC:
+ case IF:
+ case IN:
+ case IS:
+ case MATCH:
+ case NAMESPACE:
+ case NOT:
+ case OR:
+ case PASS:
+ case PRELOAD:
+ case RETURN:
+ case SELF:
+ case SIGNAL:
+ case STATIC:
+ case SUPER:
+ case TRAIT:
+ case UNDERSCORE:
+ case VAR:
+ case VOID:
+ case WHILE:
+ case YIELD:
+ return true;
+ default:
+ return false;
}
- ERR_FAIL_V_MSG("", "Failed to get token literal.");
}
-static bool _is_text_char(CharType c) {
-
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
+String GDScriptTokenizer::get_token_name(Token::Type p_token_type) {
+ ERR_FAIL_INDEX_V_MSG(p_token_type, Token::TK_MAX, "<error>", "Using token type out of the enum.");
+ return token_names[p_token_type];
}
-static bool _is_number(CharType c) {
-
- return (c >= '0' && c <= '9');
+void GDScriptTokenizer::set_source_code(const String &p_source_code) {
+ source = p_source_code;
+ if (source.is_empty()) {
+ _source = U"";
+ } else {
+ _source = source.ptr();
+ }
+ _current = _source;
+ line = 1;
+ column = 1;
+ length = p_source_code.length();
+ position = 0;
}
-static bool _is_hex(CharType c) {
-
- return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
+void GDScriptTokenizer::set_cursor_position(int p_line, int p_column) {
+ cursor_line = p_line;
+ cursor_column = p_column;
}
-static bool _is_bin(CharType c) {
-
- return (c == '0' || c == '1');
+void GDScriptTokenizer::set_multiline_mode(bool p_state) {
+ multiline_mode = p_state;
}
-void GDScriptTokenizerText::_make_token(Token p_type) {
-
- TokenData &tk = tk_rb[tk_rb_pos];
-
- tk.type = p_type;
- tk.line = line;
- tk.col = column;
-
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+int GDScriptTokenizer::get_cursor_line() const {
+ return cursor_line;
}
-void GDScriptTokenizerText::_make_identifier(const StringName &p_identifier) {
-
- TokenData &tk = tk_rb[tk_rb_pos];
- tk.type = TK_IDENTIFIER;
- tk.identifier = p_identifier;
- tk.line = line;
- tk.col = column;
-
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+int GDScriptTokenizer::get_cursor_column() const {
+ return cursor_column;
}
-void GDScriptTokenizerText::_make_built_in_func(GDScriptFunctions::Function p_func) {
-
- TokenData &tk = tk_rb[tk_rb_pos];
-
- tk.type = TK_BUILT_IN_FUNC;
- tk.func = p_func;
- tk.line = line;
- tk.col = column;
-
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+bool GDScriptTokenizer::is_past_cursor() const {
+ if (line < cursor_line) {
+ return false;
+ }
+ if (line > cursor_line) {
+ return true;
+ }
+ if (column < cursor_column) {
+ return false;
+ }
+ return true;
}
-void GDScriptTokenizerText::_make_constant(const Variant &p_constant) {
- TokenData &tk = tk_rb[tk_rb_pos];
-
- tk.type = TK_CONSTANT;
- tk.constant = p_constant;
- tk.line = line;
- tk.col = column;
-
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+char32_t GDScriptTokenizer::_advance() {
+ if (unlikely(_is_at_end())) {
+ return '\0';
+ }
+ _current++;
+ column++;
+ position++;
+ if (column > rightmost_column) {
+ rightmost_column = column;
+ }
+ if (unlikely(_is_at_end())) {
+ // Add extra newline even if it's not there, to satisfy the parser.
+ newline(true);
+ // Also add needed unindent.
+ check_indent();
+ }
+ return _peek(-1);
}
-void GDScriptTokenizerText::_make_type(const Variant::Type &p_type) {
-
- TokenData &tk = tk_rb[tk_rb_pos];
-
- tk.type = TK_BUILT_IN_TYPE;
- tk.vtype = p_type;
- tk.line = line;
- tk.col = column;
-
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+void GDScriptTokenizer::push_paren(char32_t p_char) {
+ paren_stack.push_back(p_char);
}
-void GDScriptTokenizerText::_make_error(const String &p_error) {
-
- error_flag = true;
- last_error = p_error;
+bool GDScriptTokenizer::pop_paren(char32_t p_expected) {
+ if (paren_stack.is_empty()) {
+ return false;
+ }
+ char32_t actual = paren_stack.back()->get();
+ paren_stack.pop_back();
- TokenData &tk = tk_rb[tk_rb_pos];
- tk.type = TK_ERROR;
- tk.constant = p_error;
- tk.line = line;
- tk.col = column;
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+ return actual == p_expected;
}
-void GDScriptTokenizerText::_make_newline(int p_indentation, int p_tabs) {
-
- TokenData &tk = tk_rb[tk_rb_pos];
- tk.type = TK_NEWLINE;
- tk.constant = Vector2(p_indentation, p_tabs);
- tk.line = line;
- tk.col = column;
- tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
+GDScriptTokenizer::Token GDScriptTokenizer::pop_error() {
+ Token error = error_stack.back()->get();
+ error_stack.pop_back();
+ return error;
}
-void GDScriptTokenizerText::_advance() {
-
- if (error_flag) {
- //parser broke
- _make_error(last_error);
- return;
- }
-
- if (code_pos >= len) {
- _make_token(TK_EOF);
- return;
- }
-#define GETCHAR(m_ofs) ((m_ofs + code_pos) >= len ? 0 : _code[m_ofs + code_pos])
-#define INCPOS(m_amount) \
- { \
- code_pos += m_amount; \
- column += m_amount; \
- }
- while (true) {
-
- bool is_string_name = false;
- StringMode string_mode = STRING_DOUBLE_QUOTE;
-
- switch (GETCHAR(0)) {
- case 0:
- _make_token(TK_EOF);
- break;
- case '\\':
- INCPOS(1);
- if (GETCHAR(0) == '\r') {
- INCPOS(1);
- }
-
- if (GETCHAR(0) != '\n') {
- _make_error("Expected newline after '\\'.");
- return;
- }
-
- INCPOS(1);
- line++;
-
- while (GETCHAR(0) == ' ' || GETCHAR(0) == '\t') {
- INCPOS(1);
- }
-
- continue;
- case '\t':
- case '\r':
- case ' ':
- INCPOS(1);
- continue;
- case '#': { // line comment skip
-#ifdef DEBUG_ENABLED
- String comment;
-#endif // DEBUG_ENABLED
- while (GETCHAR(0) != '\n') {
-#ifdef DEBUG_ENABLED
- comment += GETCHAR(0);
-#endif // DEBUG_ENABLED
- code_pos++;
- if (GETCHAR(0) == 0) { //end of file
- //_make_error("Unterminated Comment");
- _make_token(TK_EOF);
- return;
- }
- }
-#ifdef DEBUG_ENABLED
- String comment_content = comment.trim_prefix("#").trim_prefix(" ");
- if (comment_content.begins_with("warning-ignore:")) {
- String code = comment_content.get_slice(":", 1);
- warning_skips.push_back(Pair<int, String>(line, code.strip_edges().to_lower()));
- } else if (comment_content.begins_with("warning-ignore-all:")) {
- String code = comment_content.get_slice(":", 1);
- warning_global_skips.insert(code.strip_edges().to_lower());
- } else if (comment_content.strip_edges() == "warnings-disable") {
- ignore_warnings = true;
- }
-#endif // DEBUG_ENABLED
- [[fallthrough]];
- }
- case '\n': {
- line++;
- INCPOS(1);
- bool used_spaces = false;
- int tabs = 0;
- column = 1;
- int i = 0;
- while (true) {
- if (GETCHAR(i) == ' ') {
- i++;
- used_spaces = true;
- } else if (GETCHAR(i) == '\t') {
- if (used_spaces) {
- _make_error("Spaces used before tabs on a line");
- return;
- }
- i++;
- tabs++;
- } else {
- break; // not indentation anymore
- }
- }
-
- _make_newline(i, tabs);
- return;
- }
- case '/': {
-
- switch (GETCHAR(1)) {
- case '=': { // diveq
-
- _make_token(TK_OP_ASSIGN_DIV);
- INCPOS(1);
-
- } break;
- default:
- _make_token(TK_OP_DIV);
- }
- } break;
- case '=': {
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_EQUAL);
- INCPOS(1);
-
- } else
- _make_token(TK_OP_ASSIGN);
-
- } break;
- case '<': {
- if (GETCHAR(1) == '=') {
-
- _make_token(TK_OP_LESS_EQUAL);
- INCPOS(1);
- } else if (GETCHAR(1) == '<') {
- if (GETCHAR(2) == '=') {
- _make_token(TK_OP_ASSIGN_SHIFT_LEFT);
- INCPOS(1);
- } else {
- _make_token(TK_OP_SHIFT_LEFT);
- }
- INCPOS(1);
- } else
- _make_token(TK_OP_LESS);
-
- } break;
- case '>': {
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_GREATER_EQUAL);
- INCPOS(1);
- } else if (GETCHAR(1) == '>') {
- if (GETCHAR(2) == '=') {
- _make_token(TK_OP_ASSIGN_SHIFT_RIGHT);
- INCPOS(1);
-
- } else {
- _make_token(TK_OP_SHIFT_RIGHT);
- }
- INCPOS(1);
- } else {
- _make_token(TK_OP_GREATER);
- }
-
- } break;
- case '!': {
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_NOT_EQUAL);
- INCPOS(1);
- } else {
- _make_token(TK_OP_NOT);
- }
+static bool _is_alphanumeric(char32_t c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
+}
- } break;
- //case '"' //string - no strings in shader
- //case '\'' //string - no strings in shader
- case '{':
- _make_token(TK_CURLY_BRACKET_OPEN);
- break;
- case '}':
- _make_token(TK_CURLY_BRACKET_CLOSE);
- break;
- case '[':
- _make_token(TK_BRACKET_OPEN);
- break;
- case ']':
- _make_token(TK_BRACKET_CLOSE);
- break;
- case '(':
- _make_token(TK_PARENTHESIS_OPEN);
- break;
- case ')':
- _make_token(TK_PARENTHESIS_CLOSE);
- break;
- case ',':
- _make_token(TK_COMMA);
- break;
- case ';':
- _make_token(TK_SEMICOLON);
- break;
- case '?':
- _make_token(TK_QUESTION_MARK);
- break;
- case ':':
- _make_token(TK_COLON); //for methods maybe but now useless.
- break;
- case '$':
- _make_token(TK_DOLLAR); //for the get_node() shortener
- break;
- case '^': {
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_BIT_XOR);
- INCPOS(1);
- } else {
- _make_token(TK_OP_BIT_XOR);
- }
+static bool _is_digit(char32_t c) {
+ return (c >= '0' && c <= '9');
+}
- } break;
- case '~':
- _make_token(TK_OP_BIT_INVERT);
- break;
- case '&': {
- if (GETCHAR(1) == '&') {
-
- _make_token(TK_OP_AND);
- INCPOS(1);
- } else if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_BIT_AND);
- INCPOS(1);
- } else {
- _make_token(TK_OP_BIT_AND);
- }
- } break;
- case '|': {
- if (GETCHAR(1) == '|') {
-
- _make_token(TK_OP_OR);
- INCPOS(1);
- } else if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_BIT_OR);
- INCPOS(1);
- } else {
- _make_token(TK_OP_BIT_OR);
- }
- } break;
- case '*': {
+static bool _is_hex_digit(char32_t c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
+}
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_MUL);
- INCPOS(1);
- } else {
- _make_token(TK_OP_MUL);
- }
- } break;
- case '+': {
-
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_ADD);
- INCPOS(1);
- /*
- } else if (GETCHAR(1)=='+') {
- _make_token(TK_OP_PLUS_PLUS);
- INCPOS(1);
- */
- } else {
- _make_token(TK_OP_ADD);
- }
+static bool _is_binary_digit(char32_t c) {
+ return (c == '0' || c == '1');
+}
- } break;
- case '-': {
-
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_SUB);
- INCPOS(1);
- } else if (GETCHAR(1) == '>') {
- _make_token(TK_FORWARD_ARROW);
- INCPOS(1);
+GDScriptTokenizer::Token GDScriptTokenizer::make_token(Token::Type p_type) {
+ Token token(p_type);
+ token.start_line = start_line;
+ token.end_line = line;
+ token.start_column = start_column;
+ token.end_column = column;
+ token.leftmost_column = leftmost_column;
+ token.rightmost_column = rightmost_column;
+ token.source = String(_start, _current - _start);
+
+ if (p_type != Token::ERROR && cursor_line > -1) {
+ // Also count whitespace after token.
+ int offset = 0;
+ while (_peek(offset) == ' ' || _peek(offset) == '\t') {
+ offset++;
+ }
+ int last_column = column + offset;
+ // Check cursor position in token.
+ if (start_line == line) {
+ // Single line token.
+ if (cursor_line == start_line && cursor_column >= start_column && cursor_column <= last_column) {
+ token.cursor_position = cursor_column - start_column;
+ if (cursor_column == start_column) {
+ token.cursor_place = CURSOR_BEGINNING;
+ } else if (cursor_column < column) {
+ token.cursor_place = CURSOR_MIDDLE;
} else {
- _make_token(TK_OP_SUB);
+ token.cursor_place = CURSOR_END;
}
- } break;
- case '%': {
-
- if (GETCHAR(1) == '=') {
- _make_token(TK_OP_ASSIGN_MOD);
- INCPOS(1);
+ }
+ } else {
+ // Multi line token.
+ if (cursor_line == start_line && cursor_column >= start_column) {
+ // Is in first line.
+ token.cursor_position = cursor_column - start_column;
+ if (cursor_column == start_column) {
+ token.cursor_place = CURSOR_BEGINNING;
} else {
- _make_token(TK_OP_MOD);
- }
- } break;
- case '@':
- if (CharType(GETCHAR(1)) != '"' && CharType(GETCHAR(1)) != '\'') {
- _make_error("Unexpected '@'");
- return;
+ token.cursor_place = CURSOR_MIDDLE;
}
- INCPOS(1);
- is_string_name = true;
- [[fallthrough]];
- case '\'':
- case '"': {
-
- if (GETCHAR(0) == '\'')
- string_mode = STRING_SINGLE_QUOTE;
-
- int i = 1;
- if (string_mode == STRING_DOUBLE_QUOTE && GETCHAR(i) == '"' && GETCHAR(i + 1) == '"') {
- i += 2;
- string_mode = STRING_MULTILINE;
- }
-
- String str;
- while (true) {
- if (CharType(GETCHAR(i)) == 0) {
-
- _make_error("Unterminated String");
- return;
- } else if (string_mode == STRING_DOUBLE_QUOTE && CharType(GETCHAR(i)) == '"') {
- break;
- } else if (string_mode == STRING_SINGLE_QUOTE && CharType(GETCHAR(i)) == '\'') {
- break;
- } else if (string_mode == STRING_MULTILINE && CharType(GETCHAR(i)) == '\"' && CharType(GETCHAR(i + 1)) == '\"' && CharType(GETCHAR(i + 2)) == '\"') {
- i += 2;
- break;
- } else if (string_mode != STRING_MULTILINE && CharType(GETCHAR(i)) == '\n') {
- _make_error("Unexpected EOL at String.");
- return;
- } else if (CharType(GETCHAR(i)) == 0xFFFF) {
- //string ends here, next will be TK
- i--;
- break;
- } else if (CharType(GETCHAR(i)) == '\\') {
- //escaped characters...
- i++;
- CharType next = GETCHAR(i);
- if (next == 0) {
- _make_error("Unterminated String");
- return;
- }
- CharType res = 0;
-
- switch (next) {
-
- case 'a': res = 7; break;
- case 'b': res = 8; break;
- case 't': res = 9; break;
- case 'n': res = 10; break;
- case 'v': res = 11; break;
- case 'f': res = 12; break;
- case 'r': res = 13; break;
- case '\'': res = '\''; break;
- case '\"': res = '\"'; break;
- case '\\': res = '\\'; break;
- case '/':
- res = '/';
- break; //wtf
-
- case 'u': {
- // hex number
- i += 1;
- for (int j = 0; j < 4; j++) {
- CharType c = GETCHAR(i + j);
- if (c == 0) {
- _make_error("Unterminated String");
- return;
- }
-
- CharType v = 0;
- if (c >= '0' && c <= '9') {
- v = c - '0';
- } else if (c >= 'a' && c <= 'f') {
- v = c - 'a';
- v += 10;
- } else if (c >= 'A' && c <= 'F') {
- v = c - 'A';
- v += 10;
- } else {
- _make_error("Malformed hex constant in string");
- return;
- }
-
- res <<= 4;
- res |= v;
- }
- i += 3;
-
- } break;
- default: {
-
- _make_error("Invalid escape sequence");
- return;
- } break;
- }
-
- str += res;
-
- } else {
- if (CharType(GETCHAR(i)) == '\n') {
- line++;
- column = 1;
- }
-
- str += CharType(GETCHAR(i));
- }
- i++;
- }
- INCPOS(i);
-
- if (is_string_name) {
- _make_constant(StringName(str));
+ } else if (cursor_line == line && cursor_column <= last_column) {
+ // Is in last line.
+ token.cursor_position = cursor_column - start_column;
+ if (cursor_column < column) {
+ token.cursor_place = CURSOR_MIDDLE;
} else {
- _make_constant(str);
- }
-
- } break;
- case 0xFFFF: {
- _make_token(TK_CURSOR);
- } break;
- default: {
-
- if (_is_number(GETCHAR(0)) || (GETCHAR(0) == '.' && _is_number(GETCHAR(1)))) {
- // parse number
- bool period_found = false;
- bool exponent_found = false;
- bool hexa_found = false;
- bool bin_found = false;
- bool sign_found = false;
-
- String str;
- int i = 0;
-
- while (true) {
- if (GETCHAR(i) == '.') {
- 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 || 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 (hexa_found && _is_hex(GETCHAR(i))) {
-
- } else if (!hexa_found && GETCHAR(i) == 'b') {
- if (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 || bin_found) {
- _make_error("Invalid numeric constant at 'e'");
- return;
- }
- exponent_found = true;
- } else if (_is_number(GETCHAR(i))) {
- //all ok
-
- } 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 '-'");
- return;
- }
- sign_found = true;
- } else if (GETCHAR(i) == '_') {
- i++;
- continue; // Included for readability, shouldn't be a part of the string
- } else
- break;
-
- str += CharType(GETCHAR(i));
- i++;
- }
-
- if (!(_is_number(str[str.length() - 1]) || (hexa_found && _is_hex(str[str.length() - 1])))) {
- _make_error("Invalid numeric constant: " + str);
- return;
- }
-
- INCPOS(i);
- 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);
- } else {
- int64_t val = str.to_int64();
- _make_constant(val);
- }
-
- return;
- }
-
- if (GETCHAR(0) == '.') {
- //parse period
- _make_token(TK_PERIOD);
- break;
+ token.cursor_place = CURSOR_END;
}
-
- if (_is_text_char(GETCHAR(0))) {
- // parse identifier
- String str;
- str += CharType(GETCHAR(0));
-
- int i = 1;
- while (_is_text_char(GETCHAR(i))) {
- str += CharType(GETCHAR(i));
- i++;
- }
-
- bool identifier = false;
-
- if (str == "null") {
- _make_constant(Variant());
-
- } else if (str == "true") {
- _make_constant(true);
-
- } else if (str == "false") {
- _make_constant(false);
- } else {
-
- bool found = false;
-
- {
-
- int idx = 0;
-
- while (_type_list[idx].text) {
-
- if (str == _type_list[idx].text) {
- _make_type(_type_list[idx].type);
- found = true;
- break;
- }
- idx++;
- }
- }
-
- if (!found) {
-
- //built in func?
-
- for (int j = 0; j < GDScriptFunctions::FUNC_MAX; j++) {
-
- if (str == GDScriptFunctions::get_func_name(GDScriptFunctions::Function(j))) {
-
- _make_built_in_func(GDScriptFunctions::Function(j));
- found = true;
- break;
- }
- }
- }
-
- if (!found) {
- //keyword
-
- int idx = 0;
- found = false;
-
- while (_keyword_list[idx].text) {
-
- if (str == _keyword_list[idx].text) {
- _make_token(_keyword_list[idx].token);
- found = true;
- break;
- }
- idx++;
- }
- }
-
- if (!found)
- identifier = true;
- }
-
- if (identifier) {
- _make_identifier(str);
- }
- INCPOS(str.length());
- return;
- }
-
- _make_error("Unknown character");
- return;
-
- } break;
+ } else if (cursor_line > start_line && cursor_line < line) {
+ // Is in middle line.
+ token.cursor_position = CURSOR_MIDDLE;
+ }
}
-
- INCPOS(1);
- break;
}
-}
-
-void GDScriptTokenizerText::set_code(const String &p_code) {
- code = p_code;
- len = p_code.length();
- if (len) {
- _code = &code[0];
- } else {
- _code = nullptr;
- }
- code_pos = 0;
- line = 1; //it is stand-ar-ized that lines begin in 1 in code..
- column = 1; //the same holds for columns
- tk_rb_pos = 0;
- error_flag = false;
-#ifdef DEBUG_ENABLED
- ignore_warnings = false;
-#endif // DEBUG_ENABLED
- last_error = "";
- for (int i = 0; i < MAX_LOOKAHEAD + 1; i++)
- _advance();
+ return token;
}
-GDScriptTokenizerText::Token GDScriptTokenizerText::get_token(int p_offset) const {
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, TK_ERROR);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, TK_ERROR);
-
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- return tk_rb[ofs].type;
+GDScriptTokenizer::Token GDScriptTokenizer::make_literal(const Variant &p_literal) {
+ Token token = make_token(Token::LITERAL);
+ token.literal = p_literal;
+ return token;
}
-int GDScriptTokenizerText::get_token_line(int p_offset) const {
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1);
-
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- return tk_rb[ofs].line;
+GDScriptTokenizer::Token GDScriptTokenizer::make_identifier(const StringName &p_identifier) {
+ Token identifier = make_token(Token::IDENTIFIER);
+ identifier.literal = p_identifier;
+ return identifier;
}
-int GDScriptTokenizerText::get_token_column(int p_offset) const {
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1);
+GDScriptTokenizer::Token GDScriptTokenizer::make_error(const String &p_message) {
+ Token error = make_token(Token::ERROR);
+ error.literal = p_message;
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- return tk_rb[ofs].col;
+ return error;
}
-const Variant &GDScriptTokenizerText::get_token_constant(int p_offset) const {
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant);
-
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_CONSTANT, tk_rb[0].constant);
- return tk_rb[ofs].constant;
+void GDScriptTokenizer::push_error(const String &p_message) {
+ Token error = make_error(p_message);
+ error_stack.push_back(error);
}
-StringName GDScriptTokenizerText::get_token_identifier(int p_offset) const {
-
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, StringName());
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, StringName());
-
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_IDENTIFIER, StringName());
- return tk_rb[ofs].identifier;
+void GDScriptTokenizer::push_error(const Token &p_error) {
+ error_stack.push_back(p_error);
}
-GDScriptFunctions::Function GDScriptTokenizerText::get_token_built_in_func(int p_offset) const {
-
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, GDScriptFunctions::FUNC_MAX);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, GDScriptFunctions::FUNC_MAX);
-
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_FUNC, GDScriptFunctions::FUNC_MAX);
- return tk_rb[ofs].func;
+GDScriptTokenizer::Token GDScriptTokenizer::make_paren_error(char32_t p_paren) {
+ if (paren_stack.is_empty()) {
+ return make_error(vformat("Closing \"%c\" doesn't have an opening counterpart.", p_paren));
+ }
+ Token error = make_error(vformat("Closing \"%c\" doesn't match the opening \"%c\".", p_paren, paren_stack.back()->get()));
+ paren_stack.pop_back(); // Remove opening one anyway.
+ return error;
}
-Variant::Type GDScriptTokenizerText::get_token_type(int p_offset) const {
+GDScriptTokenizer::Token GDScriptTokenizer::check_vcs_marker(char32_t p_test, Token::Type p_double_type) {
+ const char32_t *next = _current + 1;
+ int chars = 2; // Two already matched.
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, Variant::NIL);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, Variant::NIL);
+ // Test before consuming characters, since we don't want to consume more than needed.
+ while (*next == p_test) {
+ chars++;
+ next++;
+ }
+ if (chars >= 7) {
+ // It is a VCS conflict marker.
+ while (chars > 1) {
+ // Consume all characters (first was already consumed by scan()).
+ _advance();
+ chars--;
+ }
+ return make_token(Token::VCS_CONFLICT_MARKER);
+ } else {
+ // It is only a regular double character token, so we consume the second character.
+ _advance();
+ return make_token(p_double_type);
+ }
+}
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_TYPE, Variant::NIL);
- return tk_rb[ofs].vtype;
+GDScriptTokenizer::Token GDScriptTokenizer::annotation() {
+ if (!_is_alphanumeric(_peek())) {
+ push_error("Expected annotation identifier after \"@\".");
+ }
+ while (_is_alphanumeric(_peek())) {
+ // Consume all identifier characters.
+ _advance();
+ }
+ Token annotation = make_token(Token::ANNOTATION);
+ annotation.literal = StringName(annotation.source);
+ return annotation;
}
-int GDScriptTokenizerText::get_token_line_indent(int p_offset) const {
+GDScriptTokenizer::Token GDScriptTokenizer::potential_identifier() {
+#define KEYWORDS(KEYWORD_GROUP, KEYWORD) \
+ KEYWORD_GROUP('a') \
+ KEYWORD("as", Token::AS) \
+ KEYWORD("and", Token::AND) \
+ KEYWORD("assert", Token::ASSERT) \
+ KEYWORD("await", Token::AWAIT) \
+ KEYWORD_GROUP('b') \
+ KEYWORD("break", Token::BREAK) \
+ KEYWORD("breakpoint", Token::BREAKPOINT) \
+ KEYWORD_GROUP('c') \
+ KEYWORD("class", Token::CLASS) \
+ KEYWORD("class_name", Token::CLASS_NAME) \
+ KEYWORD("const", Token::CONST) \
+ KEYWORD("continue", Token::CONTINUE) \
+ KEYWORD_GROUP('e') \
+ KEYWORD("elif", Token::ELIF) \
+ KEYWORD("else", Token::ELSE) \
+ KEYWORD("enum", Token::ENUM) \
+ KEYWORD("extends", Token::EXTENDS) \
+ KEYWORD_GROUP('f') \
+ KEYWORD("for", Token::FOR) \
+ KEYWORD("func", Token::FUNC) \
+ KEYWORD_GROUP('i') \
+ KEYWORD("if", Token::IF) \
+ KEYWORD("in", Token::IN) \
+ KEYWORD("is", Token::IS) \
+ KEYWORD_GROUP('m') \
+ KEYWORD("match", Token::MATCH) \
+ KEYWORD_GROUP('n') \
+ KEYWORD("namespace", Token::NAMESPACE) \
+ KEYWORD("not", Token::NOT) \
+ KEYWORD_GROUP('o') \
+ KEYWORD("or", Token::OR) \
+ KEYWORD_GROUP('p') \
+ KEYWORD("pass", Token::PASS) \
+ KEYWORD("preload", Token::PRELOAD) \
+ KEYWORD_GROUP('r') \
+ KEYWORD("return", Token::RETURN) \
+ KEYWORD_GROUP('s') \
+ KEYWORD("self", Token::SELF) \
+ KEYWORD("signal", Token::SIGNAL) \
+ KEYWORD("static", Token::STATIC) \
+ KEYWORD("super", Token::SUPER) \
+ KEYWORD_GROUP('t') \
+ KEYWORD("trait", Token::TRAIT) \
+ KEYWORD_GROUP('v') \
+ KEYWORD("var", Token::VAR) \
+ KEYWORD("void", Token::VOID) \
+ KEYWORD_GROUP('w') \
+ KEYWORD("while", Token::WHILE) \
+ KEYWORD_GROUP('y') \
+ KEYWORD("yield", Token::YIELD) \
+ KEYWORD_GROUP('I') \
+ KEYWORD("INF", Token::CONST_INF) \
+ KEYWORD_GROUP('N') \
+ KEYWORD("NAN", Token::CONST_NAN) \
+ KEYWORD_GROUP('P') \
+ KEYWORD("PI", Token::CONST_PI) \
+ KEYWORD_GROUP('T') \
+ KEYWORD("TAU", Token::CONST_TAU)
+
+#define MIN_KEYWORD_LENGTH 2
+#define MAX_KEYWORD_LENGTH 10
+
+ // Consume all alphanumeric characters.
+ while (_is_alphanumeric(_peek())) {
+ _advance();
+ }
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0);
+ int length = _current - _start;
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0);
- return tk_rb[ofs].constant.operator Vector2().x;
-}
+ if (length == 1 && _peek(-1) == '_') {
+ // Lone underscore.
+ return make_token(Token::UNDERSCORE);
+ }
-int GDScriptTokenizerText::get_token_line_tab_indent(int p_offset) const {
+ String name(_start, length);
+ if (length < MIN_KEYWORD_LENGTH || length > MAX_KEYWORD_LENGTH) {
+ // Cannot be a keyword, as the length doesn't match any.
+ return make_identifier(name);
+ }
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0);
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0);
+ // Define some helper macros for the switch case.
+#define KEYWORD_GROUP_CASE(char) \
+ break; \
+ case char:
+#define KEYWORD(keyword, token_type) \
+ { \
+ const int keyword_length = sizeof(keyword) - 1; \
+ static_assert(keyword_length <= MAX_KEYWORD_LENGTH, "There's a keyword longer than the defined maximum length"); \
+ static_assert(keyword_length >= MIN_KEYWORD_LENGTH, "There's a keyword shorter than the defined minimum length"); \
+ if (keyword_length == length && name == keyword) { \
+ return make_token(token_type); \
+ } \
+ }
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0);
- return tk_rb[ofs].constant.operator Vector2().y;
-}
+ // Find if it's a keyword.
+ switch (_start[0]) {
+ default:
+ KEYWORDS(KEYWORD_GROUP_CASE, KEYWORD)
+ break;
+ }
-String GDScriptTokenizerText::get_token_error(int p_offset) const {
+ // Check if it's a special literal
+ if (length == 4) {
+ if (name == "true") {
+ return make_literal(true);
+ } else if (name == "null") {
+ return make_literal(Variant());
+ }
+ } else if (length == 5) {
+ if (name == "false") {
+ return make_literal(false);
+ }
+ }
- ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, String());
- ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, String());
+ // Not a keyword, so must be an identifier.
+ return make_identifier(name);
- int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
- ERR_FAIL_COND_V(tk_rb[ofs].type != TK_ERROR, String());
- return tk_rb[ofs].constant;
+#undef KEYWORDS
+#undef MIN_KEYWORD_LENGTH
+#undef MAX_KEYWORD_LENGTH
+#undef KEYWORD_GROUP_CASE
+#undef KEYWORD
}
-void GDScriptTokenizerText::advance(int p_amount) {
+void GDScriptTokenizer::newline(bool p_make_token) {
+ // Don't overwrite previous newline, nor create if we want a line continuation.
+ if (p_make_token && !pending_newline && !line_continuation) {
+ Token newline(Token::NEWLINE);
+ newline.start_line = line;
+ newline.end_line = line;
+ newline.start_column = column - 1;
+ newline.end_column = column;
+ newline.leftmost_column = newline.start_column;
+ newline.rightmost_column = newline.end_column;
+ pending_newline = true;
+ last_newline = newline;
+ }
- ERR_FAIL_COND(p_amount <= 0);
- for (int i = 0; i < p_amount; i++)
- _advance();
+ // Increment line/column counters.
+ line++;
+ column = 1;
+ leftmost_column = 1;
}
-//////////////////////////////////////////////////////////////////////////////////////////////////////
-
-#define BYTECODE_VERSION 13
-
-Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) {
-
- const uint8_t *buf = p_buffer.ptr();
- int total_len = p_buffer.size();
- ERR_FAIL_COND_V(p_buffer.size() < 24 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA);
-
- int version = decode_uint32(&buf[4]);
- ERR_FAIL_COND_V_MSG(version > BYTECODE_VERSION, ERR_INVALID_DATA, "Bytecode is too recent! Please use a newer engine version.");
-
- int identifier_count = decode_uint32(&buf[8]);
- int constant_count = decode_uint32(&buf[12]);
- int line_count = decode_uint32(&buf[16]);
- int token_count = decode_uint32(&buf[20]);
-
- const uint8_t *b = &buf[24];
- total_len -= 24;
-
- identifiers.resize(identifier_count);
- for (int i = 0; i < identifier_count; i++) {
-
- int len = decode_uint32(b);
- ERR_FAIL_COND_V(len > total_len, ERR_INVALID_DATA);
- b += 4;
- Vector<uint8_t> cs;
- cs.resize(len);
- for (int j = 0; j < len; j++) {
- cs.write[j] = b[j] ^ 0xb6;
+GDScriptTokenizer::Token GDScriptTokenizer::number() {
+ int base = 10;
+ bool has_decimal = false;
+ bool has_exponent = false;
+ bool has_error = false;
+ bool (*digit_check_func)(char32_t) = _is_digit;
+
+ if (_peek(-1) == '.') {
+ has_decimal = true;
+ } else if (_peek(-1) == '0') {
+ if (_peek() == 'x') {
+ // Hexadecimal.
+ base = 16;
+ digit_check_func = _is_hex_digit;
+ _advance();
+ } else if (_peek() == 'b') {
+ // Binary.
+ base = 2;
+ digit_check_func = _is_binary_digit;
+ _advance();
}
-
- cs.write[cs.size() - 1] = 0;
- String s;
- s.parse_utf8((const char *)cs.ptr());
- b += len;
- total_len -= len + 4;
- identifiers.write[i] = s;
}
- constants.resize(constant_count);
- for (int i = 0; i < constant_count; i++) {
-
- Variant v;
- int len;
- // An object cannot be constant, never decode objects
- Error err = decode_variant(v, b, total_len, &len, false);
- if (err)
- return err;
- b += len;
- total_len -= len;
- constants.write[i] = v;
+ // Allow '_' to be used in a number, for readability.
+ bool previous_was_underscore = false;
+ while (digit_check_func(_peek()) || _peek() == '_') {
+ if (_peek() == '_') {
+ if (previous_was_underscore) {
+ Token error = make_error(R"(Only one underscore can be used as a numeric separator.)");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ }
+ previous_was_underscore = true;
+ }
+ _advance();
}
- ERR_FAIL_COND_V(line_count * 8 > total_len, ERR_INVALID_DATA);
-
- for (int i = 0; i < line_count; i++) {
-
- uint32_t token = decode_uint32(b);
- b += 4;
- uint32_t linecol = decode_uint32(b);
- b += 4;
+ // It might be a ".." token (instead of decimal point) so we check if it's not.
+ if (_peek() == '.' && _peek(1) != '.') {
+ if (base == 10 && !has_decimal) {
+ has_decimal = true;
+ } else if (base == 10) {
+ Token error = make_error("Cannot use a decimal point twice in a number.");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ has_error = true;
+ } else if (base == 16) {
+ Token error = make_error("Cannot use a decimal point in a hexadecimal number.");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ has_error = true;
+ } else {
+ Token error = make_error("Cannot use a decimal point in a binary number.");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ has_error = true;
+ }
+ if (!has_error) {
+ _advance();
- lines.insert(token, linecol);
- total_len -= 8;
+ // Consume decimal digits.
+ while (_is_digit(_peek()) || _peek() == '_') {
+ _advance();
+ }
+ }
}
-
- tokens.resize(token_count);
-
- for (int i = 0; i < token_count; i++) {
-
- ERR_FAIL_COND_V(total_len < 1, ERR_INVALID_DATA);
-
- if ((*b) & TOKEN_BYTE_MASK) { //little endian always
- ERR_FAIL_COND_V(total_len < 4, ERR_INVALID_DATA);
-
- tokens.write[i] = decode_uint32(b) & ~TOKEN_BYTE_MASK;
- b += 4;
- } else {
- tokens.write[i] = *b;
- b += 1;
- total_len--;
+ if (base == 10) {
+ if (_peek() == 'e' || _peek() == 'E') {
+ has_exponent = true;
+ _advance();
+ if (_peek() == '+' || _peek() == '-') {
+ // Exponent sign.
+ _advance();
+ }
+ // Consume exponent digits.
+ if (!_is_digit(_peek())) {
+ Token error = make_error(R"(Expected exponent value after "e".)");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ }
+ previous_was_underscore = false;
+ while (_is_digit(_peek()) || _peek() == '_') {
+ if (_peek() == '_') {
+ if (previous_was_underscore) {
+ Token error = make_error(R"(Only one underscore can be used as a numeric separator.)");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ }
+ previous_was_underscore = true;
+ }
+ _advance();
+ }
}
}
- token = 0;
+ // Detect extra decimal point.
+ if (!has_error && has_decimal && _peek() == '.' && _peek(1) != '.') {
+ Token error = make_error("Cannot use a decimal point twice in a number.");
+ error.start_column = column;
+ error.leftmost_column = column;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ has_error = true;
+ } else if (_is_alphanumeric(_peek())) {
+ // Letter at the end of the number.
+ push_error("Invalid numeric notation.");
+ }
- return OK;
+ // Create a string with the whole number.
+ int length = _current - _start;
+ String number = String(_start, length).replace("_", "");
+
+ // Convert to the appropriate literal type.
+ if (base == 16) {
+ int64_t value = number.hex_to_int();
+ return make_literal(value);
+ } else if (base == 2) {
+ int64_t value = number.bin_to_int();
+ return make_literal(value);
+ } else if (has_decimal || has_exponent) {
+ double value = number.to_float();
+ return make_literal(value);
+ } else {
+ int64_t value = number.to_int();
+ return make_literal(value);
+ }
}
-Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code) {
+GDScriptTokenizer::Token GDScriptTokenizer::string() {
+ enum StringType {
+ STRING_REGULAR,
+ STRING_NAME,
+ STRING_NODEPATH,
+ };
- Vector<uint8_t> buf;
+ bool is_multiline = false;
+ StringType type = STRING_REGULAR;
- Map<StringName, int> identifier_map;
- HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
- Map<uint32_t, int> line_map;
- Vector<uint32_t> token_array;
+ if (_peek(-1) == '&') {
+ type = STRING_NAME;
+ _advance();
+ } else if (_peek(-1) == '^') {
+ type = STRING_NODEPATH;
+ _advance();
+ }
- GDScriptTokenizerText tt;
- tt.set_code(p_code);
- int line = -1;
+ char32_t quote_char = _peek(-1);
- while (true) {
+ if (_peek() == quote_char && _peek(1) == quote_char) {
+ is_multiline = true;
+ // Consume all quotes.
+ _advance();
+ _advance();
+ }
- if (tt.get_token_line() != line) {
+ String result;
- line = tt.get_token_line();
- line_map[line] = token_array.size();
+ for (;;) {
+ // Consume actual string.
+ if (_is_at_end()) {
+ return make_error("Unterminated string.");
}
- uint32_t token = tt.get_token();
- switch (tt.get_token()) {
+ char32_t ch = _peek();
- case TK_IDENTIFIER: {
- StringName id = tt.get_token_identifier();
- if (!identifier_map.has(id)) {
- int idx = identifier_map.size();
- identifier_map[id] = idx;
- }
- token |= identifier_map[id] << TOKEN_BITS;
- } break;
- case TK_CONSTANT: {
+ if (ch == '\\') {
+ // Escape pattern.
+ _advance();
+ if (_is_at_end()) {
+ return make_error("Unterminated string.");
+ }
- const Variant &c = tt.get_token_constant();
- if (!constant_map.has(c)) {
- int idx = constant_map.size();
- constant_map[c] = idx;
- }
- token |= constant_map[c] << TOKEN_BITS;
- } break;
- case TK_BUILT_IN_TYPE: {
+ // Grab escape character.
+ char32_t code = _peek();
+ _advance();
+ if (_is_at_end()) {
+ return make_error("Unterminated string.");
+ }
- token |= tt.get_token_type() << TOKEN_BITS;
- } break;
- case TK_BUILT_IN_FUNC: {
+ char32_t escaped = 0;
+ bool valid_escape = true;
- token |= tt.get_token_built_in_func() << TOKEN_BITS;
+ switch (code) {
+ case 'a':
+ escaped = '\a';
+ break;
+ case 'b':
+ escaped = '\b';
+ break;
+ case 'f':
+ escaped = '\f';
+ break;
+ case 'n':
+ escaped = '\n';
+ break;
+ case 'r':
+ escaped = '\r';
+ break;
+ case 't':
+ escaped = '\t';
+ break;
+ case 'v':
+ escaped = '\v';
+ break;
+ case '\'':
+ escaped = '\'';
+ break;
+ case '\"':
+ escaped = '\"';
+ break;
+ case '\\':
+ escaped = '\\';
+ break;
+ case 'u':
+ // Hexadecimal sequence.
+ for (int i = 0; i < 4; i++) {
+ if (_is_at_end()) {
+ return make_error("Unterminated string.");
+ }
- } break;
- case TK_NEWLINE: {
+ char32_t digit = _peek();
+ char32_t value = 0;
+ if (digit >= '0' && digit <= '9') {
+ value = digit - '0';
+ } else if (digit >= 'a' && digit <= 'f') {
+ value = digit - 'a';
+ value += 10;
+ } else if (digit >= 'A' && digit <= 'F') {
+ value = digit - 'A';
+ value += 10;
+ } else {
+ // Make error, but keep parsing the string.
+ Token error = make_error("Invalid hexadecimal digit in unicode escape sequence.");
+ error.start_column = column;
+ error.leftmost_column = error.start_column;
+ error.end_column = column + 1;
+ error.rightmost_column = error.end_column;
+ push_error(error);
+ valid_escape = false;
+ break;
+ }
- token |= tt.get_token_line_indent() << TOKEN_BITS;
- } break;
- case TK_ERROR: {
+ escaped <<= 4;
+ escaped |= value;
- ERR_FAIL_V(Vector<uint8_t>());
- } break;
- default: {
+ _advance();
+ }
+ break;
+ case '\r':
+ if (_peek() != '\n') {
+ // Carriage return without newline in string. (???)
+ // Just add it to the string and keep going.
+ result += ch;
+ _advance();
+ break;
+ }
+ [[fallthrough]];
+ case '\n':
+ // Escaping newline.
+ newline(false);
+ valid_escape = false; // Don't add to the string.
+ break;
+ default:
+ Token error = make_error("Invalid escape in string.");
+ error.start_column = column - 2;
+ error.leftmost_column = error.start_column;
+ push_error(error);
+ valid_escape = false;
+ break;
}
- };
- token_array.push_back(token);
+ if (valid_escape) {
+ result += escaped;
+ }
+ } else if (ch == quote_char) {
+ _advance();
+ if (is_multiline) {
+ if (_peek() == quote_char && _peek(1) == quote_char) {
+ // Ended the multiline string. Consume all quotes.
+ _advance();
+ _advance();
+ break;
+ }
+ } else {
+ // Ended single-line string.
+ break;
+ }
+ } else {
+ result += ch;
+ _advance();
+ if (ch == '\n') {
+ newline(false);
+ }
+ }
+ }
- if (tt.get_token() == TK_EOF)
+ // Make the literal.
+ Variant string;
+ switch (type) {
+ case STRING_NAME:
+ string = StringName(result);
+ break;
+ case STRING_NODEPATH:
+ string = NodePath(result);
+ break;
+ case STRING_REGULAR:
+ string = result;
break;
- tt.advance();
}
- //reverse maps
+ return make_literal(string);
+}
- Map<int, StringName> rev_identifier_map;
- for (Map<StringName, int>::Element *E = identifier_map.front(); E; E = E->next()) {
- rev_identifier_map[E->get()] = E->key();
- }
+void GDScriptTokenizer::check_indent() {
+ ERR_FAIL_COND_MSG(column != 1, "Checking tokenizer indentation in the middle of a line.");
- Map<int, Variant> rev_constant_map;
- const Variant *K = nullptr;
- while ((K = constant_map.next(K))) {
- rev_constant_map[constant_map[*K]] = *K;
+ if (_is_at_end()) {
+ // Send dedents for every indent level.
+ pending_indents -= indent_level();
+ indent_stack.clear();
+ return;
}
- Map<int, uint32_t> rev_line_map;
- for (Map<uint32_t, int>::Element *E = line_map.front(); E; E = E->next()) {
- rev_line_map[E->get()] = E->key();
- }
+ for (;;) {
+ char32_t current_indent_char = _peek();
+ int indent_count = 0;
- //save header
- buf.resize(24);
- buf.write[0] = 'G';
- buf.write[1] = 'D';
- buf.write[2] = 'S';
- buf.write[3] = 'C';
- encode_uint32(BYTECODE_VERSION, &buf.write[4]);
- encode_uint32(identifier_map.size(), &buf.write[8]);
- encode_uint32(constant_map.size(), &buf.write[12]);
- encode_uint32(line_map.size(), &buf.write[16]);
- encode_uint32(token_array.size(), &buf.write[20]);
-
- //save identifiers
-
- for (Map<int, StringName>::Element *E = rev_identifier_map.front(); E; E = E->next()) {
-
- CharString cs = String(E->get()).utf8();
- int len = cs.length() + 1;
- int extra = 4 - (len % 4);
- if (extra == 4)
- extra = 0;
-
- uint8_t ibuf[4];
- encode_uint32(len + extra, ibuf);
- for (int i = 0; i < 4; i++) {
- buf.push_back(ibuf[i]);
+ if (current_indent_char != ' ' && current_indent_char != '\t' && current_indent_char != '\r' && current_indent_char != '\n' && current_indent_char != '#') {
+ // First character of the line is not whitespace, so we clear all indentation levels.
+ // Unless we are in a continuation or in multiline mode (inside expression).
+ if (line_continuation || multiline_mode) {
+ return;
+ }
+ pending_indents -= indent_level();
+ indent_stack.clear();
+ return;
}
- for (int i = 0; i < len; i++) {
- buf.push_back(cs[i] ^ 0xb6);
+
+ if (_peek() == '\r') {
+ _advance();
+ if (_peek() != '\n') {
+ push_error("Stray carriage return character in source code.");
+ }
}
- for (int i = 0; i < extra; i++) {
- buf.push_back(0 ^ 0xb6);
+ if (_peek() == '\n') {
+ // Empty line, keep going.
+ _advance();
+ newline(false);
+ continue;
}
- }
-
- for (Map<int, Variant>::Element *E = rev_constant_map.front(); E; E = E->next()) {
-
- int len;
- // Objects cannot be constant, never encode objects
- Error err = encode_variant(E->get(), nullptr, len, false);
- ERR_FAIL_COND_V_MSG(err != OK, Vector<uint8_t>(), "Error when trying to encode Variant.");
- int pos = buf.size();
- buf.resize(pos + len);
- encode_variant(E->get(), &buf.write[pos], len, false);
- }
-
- for (Map<int, uint32_t>::Element *E = rev_line_map.front(); E; E = E->next()) {
- uint8_t ibuf[8];
- encode_uint32(E->key(), &ibuf[0]);
- encode_uint32(E->get(), &ibuf[4]);
- for (int i = 0; i < 8; i++)
- buf.push_back(ibuf[i]);
- }
+ // Check indent level.
+ bool mixed = false;
+ while (!_is_at_end()) {
+ char32_t space = _peek();
+ if (space == '\t') {
+ // Consider individual tab columns.
+ column += tab_size - 1;
+ indent_count += tab_size;
+ } else if (space == ' ') {
+ indent_count += 1;
+ } else {
+ break;
+ }
+ mixed = mixed || space != current_indent_char;
+ _advance();
+ }
- for (int i = 0; i < token_array.size(); i++) {
+ if (mixed) {
+ Token error = make_error("Mixed use of tabs and spaces for indentation.");
+ error.start_line = line;
+ error.start_column = 1;
+ error.leftmost_column = 1;
+ error.rightmost_column = column;
+ push_error(error);
+ }
- uint32_t token = token_array[i];
+ if (_is_at_end()) {
+ // Reached the end with an empty line, so just dedent as much as needed.
+ pending_indents -= indent_level();
+ indent_stack.clear();
+ return;
+ }
- if (token & ~TOKEN_MASK) {
- uint8_t buf4[4];
- encode_uint32(token_array[i] | TOKEN_BYTE_MASK, &buf4[0]);
- for (int j = 0; j < 4; j++) {
- buf.push_back(buf4[j]);
+ if (_peek() == '\r') {
+ _advance();
+ if (_peek() != '\n') {
+ push_error("Stray carriage return character in source code.");
}
- } else {
- buf.push_back(token);
}
- }
-
- return buf;
-}
+ if (_peek() == '\n') {
+ // Empty line, keep going.
+ _advance();
+ newline(false);
+ continue;
+ }
+ if (_peek() == '#') {
+ // Comment. Advance to the next line.
+#ifdef TOOLS_ENABLED
+ String comment;
+ while (_peek() != '\n' && !_is_at_end()) {
+ comment += _advance();
+ }
+ comments[line] = CommentData(comment, true);
+#else
+ while (_peek() != '\n' && !_is_at_end()) {
+ _advance();
+ }
+#endif // TOOLS_ENABLED
+ if (_is_at_end()) {
+ // Reached the end with an empty line, so just dedent as much as needed.
+ pending_indents -= indent_level();
+ indent_stack.clear();
+ return;
+ }
+ _advance(); // Consume '\n'.
+ newline(false);
+ continue;
+ }
-GDScriptTokenizerBuffer::Token GDScriptTokenizerBuffer::get_token(int p_offset) const {
+ if (line_continuation || multiline_mode) {
+ // We cleared up all the whitespace at the beginning of the line.
+ // But if this is a continuation or multiline mode and we don't want any indentation change.
+ return;
+ }
- int offset = token + p_offset;
+ // Check if indentation character is consistent.
+ if (indent_char == '\0') {
+ // First time indenting, choose character now.
+ indent_char = current_indent_char;
+ } else if (current_indent_char != indent_char) {
+ Token error = make_error(vformat("Used \"%s\" for indentation instead \"%s\" as used before in the file.", String(&current_indent_char, 1).c_escape(), String(&indent_char, 1).c_escape()));
+ error.start_line = line;
+ error.start_column = 1;
+ error.leftmost_column = 1;
+ error.rightmost_column = column;
+ push_error(error);
+ }
- if (offset < 0 || offset >= tokens.size())
- return TK_EOF;
+ // Now we can do actual indentation changes.
- return GDScriptTokenizerBuffer::Token(tokens[offset] & TOKEN_MASK);
+ // Check if indent or dedent.
+ int previous_indent = 0;
+ if (indent_level() > 0) {
+ previous_indent = indent_stack.back()->get();
+ }
+ if (indent_count == previous_indent) {
+ // No change in indentation.
+ return;
+ }
+ if (indent_count > previous_indent) {
+ // Indentation increased.
+ indent_stack.push_back(indent_count);
+ pending_indents++;
+ } else {
+ // Indentation decreased (dedent).
+ if (indent_level() == 0) {
+ push_error("Tokenizer bug: trying to dedent without previous indent.");
+ return;
+ }
+ while (indent_level() > 0 && indent_stack.back()->get() > indent_count) {
+ indent_stack.pop_back();
+ pending_indents--;
+ }
+ if ((indent_level() > 0 && indent_stack.back()->get() != indent_count) || (indent_level() == 0 && indent_count != 0)) {
+ // Mismatched indentation alignment.
+ Token error = make_error("Unindent doesn't match the previous indentation level.");
+ error.start_line = line;
+ error.start_column = 1;
+ error.leftmost_column = 1;
+ error.end_column = column + 1;
+ error.rightmost_column = column + 1;
+ push_error(error);
+ // Still, we'll be lenient and keep going, so keep this level in the stack.
+ indent_stack.push_back(indent_count);
+ }
+ }
+ break; // Get out of the loop in any case.
+ }
}
-StringName GDScriptTokenizerBuffer::get_token_identifier(int p_offset) const {
-
- int offset = token + p_offset;
-
- ERR_FAIL_INDEX_V(offset, tokens.size(), StringName());
- uint32_t identifier = tokens[offset] >> TOKEN_BITS;
- ERR_FAIL_UNSIGNED_INDEX_V(identifier, (uint32_t)identifiers.size(), StringName());
+void GDScriptTokenizer::_skip_whitespace() {
+ if (pending_indents != 0) {
+ // Still have some indent/dedent tokens to give.
+ return;
+ }
- return identifiers[identifier];
-}
+ bool is_bol = column == 1; // Beginning of line.
-GDScriptFunctions::Function GDScriptTokenizerBuffer::get_token_built_in_func(int p_offset) const {
+ if (is_bol) {
+ check_indent();
+ return;
+ }
- int offset = token + p_offset;
- ERR_FAIL_INDEX_V(offset, tokens.size(), GDScriptFunctions::FUNC_MAX);
- return GDScriptFunctions::Function(tokens[offset] >> TOKEN_BITS);
+ for (;;) {
+ char32_t c = _peek();
+ switch (c) {
+ case ' ':
+ _advance();
+ break;
+ case '\t':
+ _advance();
+ // Consider individual tab columns.
+ column += tab_size - 1;
+ break;
+ case '\r':
+ _advance(); // Consume either way.
+ if (_peek() != '\n') {
+ push_error("Stray carriage return character in source code.");
+ return;
+ }
+ break;
+ case '\n':
+ _advance();
+ newline(!is_bol); // Don't create new line token if line is empty.
+ check_indent();
+ break;
+ case '#': {
+ // Comment.
+#ifdef TOOLS_ENABLED
+ String comment;
+ while (_peek() != '\n' && !_is_at_end()) {
+ comment += _advance();
+ }
+ comments[line] = CommentData(comment, is_bol);
+#else
+ while (_peek() != '\n' && !_is_at_end()) {
+ _advance();
+ }
+#endif // TOOLS_ENABLED
+ if (_is_at_end()) {
+ return;
+ }
+ _advance(); // Consume '\n'
+ newline(!is_bol);
+ check_indent();
+ } break;
+ default:
+ return;
+ }
+ }
}
-Variant::Type GDScriptTokenizerBuffer::get_token_type(int p_offset) const {
+GDScriptTokenizer::Token GDScriptTokenizer::scan() {
+ if (has_error()) {
+ return pop_error();
+ }
- int offset = token + p_offset;
- ERR_FAIL_INDEX_V(offset, tokens.size(), Variant::NIL);
+ _skip_whitespace();
- return Variant::Type(tokens[offset] >> TOKEN_BITS);
-}
+ if (pending_newline) {
+ pending_newline = false;
+ if (!multiline_mode) {
+ // Don't return newline tokens on multine mode.
+ return last_newline;
+ }
+ }
-int GDScriptTokenizerBuffer::get_token_line(int p_offset) const {
+ // Check for potential errors after skipping whitespace().
+ if (has_error()) {
+ return pop_error();
+ }
- int offset = token + p_offset;
- int pos = lines.find_nearest(offset);
+ _start = _current;
+ start_line = line;
+ start_column = column;
+ leftmost_column = column;
+ rightmost_column = column;
+
+ if (pending_indents != 0) {
+ // Adjust position for indent.
+ _start -= start_column - 1;
+ start_column = 1;
+ leftmost_column = 1;
+ if (pending_indents > 0) {
+ // Indents.
+ pending_indents--;
+ return make_token(Token::INDENT);
+ } else {
+ // Dedents.
+ pending_indents++;
+ Token dedent = make_token(Token::DEDENT);
+ dedent.end_column += 1;
+ dedent.rightmost_column += 1;
+ return dedent;
+ }
+ }
- if (pos < 0)
- return -1;
- if (pos >= lines.size())
- pos = lines.size() - 1;
+ if (_is_at_end()) {
+ return make_token(Token::TK_EOF);
+ }
- uint32_t l = lines.getv(pos);
- return l & TOKEN_LINE_MASK;
-}
-int GDScriptTokenizerBuffer::get_token_column(int p_offset) const {
+ const char32_t c = _advance();
- int offset = token + p_offset;
- int pos = lines.find_nearest(offset);
- if (pos < 0)
- return -1;
- if (pos >= lines.size())
- pos = lines.size() - 1;
+ if (c == '\\') {
+ // Line continuation with backslash.
+ if (_peek() == '\r') {
+ if (_peek(1) != '\n') {
+ return make_error("Unexpected carriage return character.");
+ }
+ _advance();
+ }
+ if (_peek() != '\n') {
+ return make_error("Expected new line after \"\\\".");
+ }
+ _advance();
+ newline(false);
+ line_continuation = true;
+ return scan(); // Recurse to get next token.
+ }
- uint32_t l = lines.getv(pos);
- return l >> TOKEN_LINE_BITS;
-}
-int GDScriptTokenizerBuffer::get_token_line_indent(int p_offset) const {
+ line_continuation = false;
- int offset = token + p_offset;
- ERR_FAIL_INDEX_V(offset, tokens.size(), 0);
- return tokens[offset] >> TOKEN_BITS;
-}
-const Variant &GDScriptTokenizerBuffer::get_token_constant(int p_offset) const {
-
- int offset = token + p_offset;
- ERR_FAIL_INDEX_V(offset, tokens.size(), nil);
- uint32_t constant = tokens[offset] >> TOKEN_BITS;
- ERR_FAIL_UNSIGNED_INDEX_V(constant, (uint32_t)constants.size(), nil);
- return constants[constant];
-}
-String GDScriptTokenizerBuffer::get_token_error(int p_offset) const {
+ if (_is_digit(c)) {
+ return number();
+ } else if (_is_alphanumeric(c)) {
+ return potential_identifier();
+ }
- ERR_FAIL_V(String());
-}
+ switch (c) {
+ // String literals.
+ case '"':
+ case '\'':
+ return string();
+
+ // Annotation.
+ case '@':
+ return annotation();
+
+ // Single characters.
+ case '~':
+ return make_token(Token::TILDE);
+ case ',':
+ return make_token(Token::COMMA);
+ case ':':
+ return make_token(Token::COLON);
+ case ';':
+ return make_token(Token::SEMICOLON);
+ case '$':
+ return make_token(Token::DOLLAR);
+ case '?':
+ return make_token(Token::QUESTION_MARK);
+ case '`':
+ return make_token(Token::BACKTICK);
+
+ // Parens.
+ case '(':
+ push_paren('(');
+ return make_token(Token::PARENTHESIS_OPEN);
+ case '[':
+ push_paren('[');
+ return make_token(Token::BRACKET_OPEN);
+ case '{':
+ push_paren('{');
+ return make_token(Token::BRACE_OPEN);
+ case ')':
+ if (!pop_paren('(')) {
+ return make_paren_error(c);
+ }
+ return make_token(Token::PARENTHESIS_CLOSE);
+ case ']':
+ if (!pop_paren('[')) {
+ return make_paren_error(c);
+ }
+ return make_token(Token::BRACKET_CLOSE);
+ case '}':
+ if (!pop_paren('{')) {
+ return make_paren_error(c);
+ }
+ return make_token(Token::BRACE_CLOSE);
+
+ // Double characters.
+ case '!':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::BANG_EQUAL);
+ } else {
+ return make_token(Token::BANG);
+ }
+ case '.':
+ if (_peek() == '.') {
+ _advance();
+ return make_token(Token::PERIOD_PERIOD);
+ } else if (_is_digit(_peek())) {
+ // Number starting with '.'.
+ return number();
+ } else {
+ return make_token(Token::PERIOD);
+ }
+ case '+':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::PLUS_EQUAL);
+ } else {
+ return make_token(Token::PLUS);
+ }
+ case '-':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::MINUS_EQUAL);
+ } else if (_peek() == '>') {
+ _advance();
+ return make_token(Token::FORWARD_ARROW);
+ } else {
+ return make_token(Token::MINUS);
+ }
+ case '*':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::STAR_EQUAL);
+ } else {
+ return make_token(Token::STAR);
+ }
+ case '/':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::SLASH_EQUAL);
+ } else {
+ return make_token(Token::SLASH);
+ }
+ case '%':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::PERCENT_EQUAL);
+ } else {
+ return make_token(Token::PERCENT);
+ }
+ case '^':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::CARET_EQUAL);
+ } else if (_peek() == '"' || _peek() == '\'') {
+ // Node path
+ return string();
+ } else {
+ return make_token(Token::CARET);
+ }
+ case '&':
+ if (_peek() == '&') {
+ _advance();
+ return make_token(Token::AMPERSAND_AMPERSAND);
+ } else if (_peek() == '=') {
+ _advance();
+ return make_token(Token::AMPERSAND_EQUAL);
+ } else if (_peek() == '"' || _peek() == '\'') {
+ // String Name
+ return string();
+ } else {
+ return make_token(Token::AMPERSAND);
+ }
+ case '|':
+ if (_peek() == '|') {
+ _advance();
+ return make_token(Token::PIPE_PIPE);
+ } else if (_peek() == '=') {
+ _advance();
+ return make_token(Token::PIPE_EQUAL);
+ } else {
+ return make_token(Token::PIPE);
+ }
-void GDScriptTokenizerBuffer::advance(int p_amount) {
+ // Potential VCS conflict markers.
+ case '=':
+ if (_peek() == '=') {
+ return check_vcs_marker('=', Token::EQUAL_EQUAL);
+ } else {
+ return make_token(Token::EQUAL);
+ }
+ case '<':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::LESS_EQUAL);
+ } else if (_peek() == '<') {
+ if (_peek(1) == '=') {
+ _advance();
+ _advance(); // Advance both '<' and '='
+ return make_token(Token::LESS_LESS_EQUAL);
+ } else {
+ return check_vcs_marker('<', Token::LESS_LESS);
+ }
+ } else {
+ return make_token(Token::LESS);
+ }
+ case '>':
+ if (_peek() == '=') {
+ _advance();
+ return make_token(Token::GREATER_EQUAL);
+ } else if (_peek() == '>') {
+ if (_peek(1) == '=') {
+ _advance();
+ _advance(); // Advance both '>' and '='
+ return make_token(Token::GREATER_GREATER_EQUAL);
+ } else {
+ return check_vcs_marker('>', Token::GREATER_GREATER);
+ }
+ } else {
+ return make_token(Token::GREATER);
+ }
- ERR_FAIL_INDEX(p_amount + token, tokens.size());
- token += p_amount;
+ default:
+ return make_error(vformat(R"(Unknown character "%s".")", String(&c, 1)));
+ }
}
-GDScriptTokenizerBuffer::GDScriptTokenizerBuffer() {
- token = 0;
+GDScriptTokenizer::GDScriptTokenizer() {
+#ifdef TOOLS_ENABLED
+ if (EditorSettings::get_singleton()) {
+ tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
+ }
+#endif // TOOLS_ENABLED
}
diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h
index 180ec3c77e..cdb0072294 100644
--- a/modules/gdscript/gdscript_tokenizer.h
+++ b/modules/gdscript/gdscript_tokenizer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,270 +31,241 @@
#ifndef GDSCRIPT_TOKENIZER_H
#define GDSCRIPT_TOKENIZER_H
-#include "core/pair.h"
-#include "core/set.h"
-#include "core/string_name.h"
-#include "core/ustring.h"
-#include "core/variant.h"
-#include "core/vmap.h"
-#include "gdscript_functions.h"
+#include "core/templates/list.h"
+#include "core/templates/map.h"
+#include "core/templates/set.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
class GDScriptTokenizer {
public:
- enum Token {
-
- TK_EMPTY,
- TK_IDENTIFIER,
- TK_CONSTANT,
- TK_SELF,
- TK_BUILT_IN_TYPE,
- TK_BUILT_IN_FUNC,
- TK_OP_IN,
- TK_OP_EQUAL,
- TK_OP_NOT_EQUAL,
- TK_OP_LESS,
- TK_OP_LESS_EQUAL,
- TK_OP_GREATER,
- TK_OP_GREATER_EQUAL,
- TK_OP_AND,
- TK_OP_OR,
- TK_OP_NOT,
- TK_OP_ADD,
- TK_OP_SUB,
- TK_OP_MUL,
- TK_OP_DIV,
- TK_OP_MOD,
- TK_OP_SHIFT_LEFT,
- TK_OP_SHIFT_RIGHT,
- TK_OP_ASSIGN,
- TK_OP_ASSIGN_ADD,
- TK_OP_ASSIGN_SUB,
- TK_OP_ASSIGN_MUL,
- TK_OP_ASSIGN_DIV,
- TK_OP_ASSIGN_MOD,
- TK_OP_ASSIGN_SHIFT_LEFT,
- TK_OP_ASSIGN_SHIFT_RIGHT,
- TK_OP_ASSIGN_BIT_AND,
- TK_OP_ASSIGN_BIT_OR,
- TK_OP_ASSIGN_BIT_XOR,
- TK_OP_BIT_AND,
- TK_OP_BIT_OR,
- TK_OP_BIT_XOR,
- TK_OP_BIT_INVERT,
- //TK_OP_PLUS_PLUS,
- //TK_OP_MINUS_MINUS,
- TK_CF_IF,
- TK_CF_ELIF,
- TK_CF_ELSE,
- TK_CF_FOR,
- TK_CF_WHILE,
- TK_CF_BREAK,
- TK_CF_CONTINUE,
- TK_CF_PASS,
- TK_CF_RETURN,
- TK_CF_MATCH,
- TK_PR_FUNCTION,
- TK_PR_CLASS,
- TK_PR_CLASS_NAME,
- TK_PR_EXTENDS,
- TK_PR_IS,
- TK_PR_ONREADY,
- TK_PR_TOOL,
- TK_PR_STATIC,
- TK_PR_EXPORT,
- TK_PR_SETGET,
- TK_PR_CONST,
- TK_PR_VAR,
- TK_PR_AS,
- TK_PR_VOID,
- TK_PR_ENUM,
- TK_PR_PRELOAD,
- TK_PR_ASSERT,
- TK_PR_YIELD,
- TK_PR_SIGNAL,
- TK_PR_BREAKPOINT,
- TK_PR_REMOTE,
- TK_PR_MASTER,
- TK_PR_PUPPET,
- TK_PR_REMOTESYNC,
- TK_PR_MASTERSYNC,
- TK_PR_PUPPETSYNC,
- TK_BRACKET_OPEN,
- TK_BRACKET_CLOSE,
- TK_CURLY_BRACKET_OPEN,
- TK_CURLY_BRACKET_CLOSE,
- TK_PARENTHESIS_OPEN,
- TK_PARENTHESIS_CLOSE,
- TK_COMMA,
- TK_SEMICOLON,
- TK_PERIOD,
- TK_QUESTION_MARK,
- TK_COLON,
- TK_DOLLAR,
- TK_FORWARD_ARROW,
- TK_NEWLINE,
- TK_CONST_PI,
- TK_CONST_TAU,
- TK_WILDCARD,
- TK_CONST_INF,
- TK_CONST_NAN,
- TK_ERROR,
- TK_EOF,
- TK_CURSOR, //used for code completion
- TK_MAX
- };
-
-protected:
- enum StringMode {
- STRING_SINGLE_QUOTE,
- STRING_DOUBLE_QUOTE,
- STRING_MULTILINE
+ enum CursorPlace {
+ CURSOR_NONE,
+ CURSOR_BEGINNING,
+ CURSOR_MIDDLE,
+ CURSOR_END,
};
- static const char *token_names[TK_MAX];
-
-public:
- static const char *get_token_name(Token p_token);
-
- bool is_token_literal(int p_offset = 0, bool variable_safe = false) const;
- StringName get_token_literal(int p_offset = 0) const;
-
- virtual const Variant &get_token_constant(int p_offset = 0) const = 0;
- virtual Token get_token(int p_offset = 0) const = 0;
- virtual StringName get_token_identifier(int p_offset = 0) const = 0;
- virtual GDScriptFunctions::Function get_token_built_in_func(int p_offset = 0) const = 0;
- virtual Variant::Type get_token_type(int p_offset = 0) const = 0;
- virtual int get_token_line(int p_offset = 0) const = 0;
- virtual int get_token_column(int p_offset = 0) const = 0;
- virtual int get_token_line_indent(int p_offset = 0) const = 0;
- virtual int get_token_line_tab_indent(int p_offset = 0) const = 0;
- virtual String get_token_error(int p_offset = 0) const = 0;
- virtual void advance(int p_amount = 1) = 0;
-#ifdef DEBUG_ENABLED
- virtual const Vector<Pair<int, String>> &get_warning_skips() const = 0;
- virtual const Set<String> &get_warning_global_skips() const = 0;
- virtual bool is_ignoring_warnings() const = 0;
-#endif // DEBUG_ENABLED
+ struct Token {
+ enum Type {
+ EMPTY,
+ // Basic
+ ANNOTATION,
+ IDENTIFIER,
+ LITERAL,
+ // Comparison
+ LESS,
+ LESS_EQUAL,
+ GREATER,
+ GREATER_EQUAL,
+ EQUAL_EQUAL,
+ BANG_EQUAL,
+ // Logical
+ AND,
+ OR,
+ NOT,
+ AMPERSAND_AMPERSAND,
+ PIPE_PIPE,
+ BANG,
+ // Bitwise
+ AMPERSAND,
+ PIPE,
+ TILDE,
+ CARET,
+ LESS_LESS,
+ GREATER_GREATER,
+ // Math
+ PLUS,
+ MINUS,
+ STAR,
+ SLASH,
+ PERCENT,
+ // Assignment
+ EQUAL,
+ PLUS_EQUAL,
+ MINUS_EQUAL,
+ STAR_EQUAL,
+ SLASH_EQUAL,
+ PERCENT_EQUAL,
+ LESS_LESS_EQUAL,
+ GREATER_GREATER_EQUAL,
+ AMPERSAND_EQUAL,
+ PIPE_EQUAL,
+ CARET_EQUAL,
+ // Control flow
+ IF,
+ ELIF,
+ ELSE,
+ FOR,
+ WHILE,
+ BREAK,
+ CONTINUE,
+ PASS,
+ RETURN,
+ MATCH,
+ // Keywords
+ AS,
+ ASSERT,
+ AWAIT,
+ BREAKPOINT,
+ CLASS,
+ CLASS_NAME,
+ CONST,
+ ENUM,
+ EXTENDS,
+ FUNC,
+ IN,
+ IS,
+ NAMESPACE,
+ PRELOAD,
+ SELF,
+ SIGNAL,
+ STATIC,
+ SUPER,
+ TRAIT,
+ VAR,
+ VOID,
+ YIELD,
+ // Punctuation
+ BRACKET_OPEN,
+ BRACKET_CLOSE,
+ BRACE_OPEN,
+ BRACE_CLOSE,
+ PARENTHESIS_OPEN,
+ PARENTHESIS_CLOSE,
+ COMMA,
+ SEMICOLON,
+ PERIOD,
+ PERIOD_PERIOD,
+ COLON,
+ DOLLAR,
+ FORWARD_ARROW,
+ UNDERSCORE,
+ // Whitespace
+ NEWLINE,
+ INDENT,
+ DEDENT,
+ // Constants
+ CONST_PI,
+ CONST_TAU,
+ CONST_INF,
+ CONST_NAN,
+ // Error message improvement
+ VCS_CONFLICT_MARKER,
+ BACKTICK,
+ QUESTION_MARK,
+ // Special
+ ERROR,
+ TK_EOF, // "EOF" is reserved
+ TK_MAX
+ };
- virtual ~GDScriptTokenizer(){};
-};
+ Type type = EMPTY;
+ Variant literal;
+ int start_line = 0, end_line = 0, start_column = 0, end_column = 0;
+ int leftmost_column = 0, rightmost_column = 0; // Column span for multiline tokens.
+ int cursor_position = -1;
+ CursorPlace cursor_place = CURSOR_NONE;
+ String source;
-class GDScriptTokenizerText : public GDScriptTokenizer {
+ const char *get_name() const;
+ bool is_identifier() const;
+ bool is_node_name() const;
+ StringName get_identifier() const { return source; }
- enum {
- MAX_LOOKAHEAD = 4,
- TK_RB_SIZE = MAX_LOOKAHEAD * 2 + 1
+ Token(Type p_type) {
+ type = p_type;
+ }
+ Token() {
+ type = EMPTY;
+ }
};
- struct TokenData {
- Token type;
- StringName identifier; //for identifier types
- Variant constant; //for constant types
- union {
- Variant::Type vtype; //for type types
- GDScriptFunctions::Function func; //function for built in functions
- int warning_code; //for warning skip
- };
- int line, col;
- TokenData() {
- type = TK_EMPTY;
- line = col = 0;
- vtype = Variant::NIL;
+#ifdef TOOLS_ENABLED
+ struct CommentData {
+ String comment;
+ bool new_line = false;
+ CommentData() {}
+ CommentData(const String &p_comment, bool p_new_line) {
+ comment = p_comment;
+ new_line = p_new_line;
}
};
+ const Map<int, CommentData> &get_comments() const {
+ return comments;
+ }
+#endif // TOOLS_ENABLED
- void _make_token(Token p_type);
- void _make_newline(int p_indentation = 0, int p_tabs = 0);
- void _make_identifier(const StringName &p_identifier);
- void _make_built_in_func(GDScriptFunctions::Function p_func);
- void _make_constant(const Variant &p_constant);
- void _make_type(const Variant::Type &p_type);
- void _make_error(const String &p_error);
+private:
+ String source;
+ const char32_t *_source = nullptr;
+ const char32_t *_current = nullptr;
+ int line = -1, column = -1;
+ int cursor_line = -1, cursor_column = -1;
+ int tab_size = 4;
- String code;
- int len;
- int code_pos;
- const CharType *_code;
- int line;
- int column;
- TokenData tk_rb[TK_RB_SIZE * 2 + 1];
- int tk_rb_pos;
- String last_error;
- bool error_flag;
+ // Keep track of multichar tokens.
+ const char32_t *_start = nullptr;
+ int start_line = 0, start_column = 0;
+ int leftmost_column = 0, rightmost_column = 0;
-#ifdef DEBUG_ENABLED
- Vector<Pair<int, String>> warning_skips;
- Set<String> warning_global_skips;
- bool ignore_warnings;
-#endif // DEBUG_ENABLED
+ // Info cache.
+ bool line_continuation = false; // Whether this line is a continuation of the previous, like when using '\'.
+ bool multiline_mode = false;
+ List<Token> error_stack;
+ bool pending_newline = false;
+ Token last_newline;
+ int pending_indents = 0;
+ List<int> indent_stack;
+ List<char32_t> paren_stack;
+ char32_t indent_char = '\0';
+ int position = 0;
+ int length = 0;
- void _advance();
+#ifdef TOOLS_ENABLED
+ Map<int, CommentData> comments;
+#endif // TOOLS_ENABLED
-public:
- void set_code(const String &p_code);
- virtual Token get_token(int p_offset = 0) const;
- virtual StringName get_token_identifier(int p_offset = 0) const;
- virtual GDScriptFunctions::Function get_token_built_in_func(int p_offset = 0) const;
- virtual Variant::Type get_token_type(int p_offset = 0) const;
- virtual int get_token_line(int p_offset = 0) const;
- virtual int get_token_column(int p_offset = 0) const;
- virtual int get_token_line_indent(int p_offset = 0) const;
- virtual int get_token_line_tab_indent(int p_offset = 0) const;
- virtual const Variant &get_token_constant(int p_offset = 0) const;
- virtual String get_token_error(int p_offset = 0) const;
- virtual void advance(int p_amount = 1);
-#ifdef DEBUG_ENABLED
- virtual const Vector<Pair<int, String>> &get_warning_skips() const { return warning_skips; }
- virtual const Set<String> &get_warning_global_skips() const { return warning_global_skips; }
- virtual bool is_ignoring_warnings() const { return ignore_warnings; }
-#endif // DEBUG_ENABLED
-};
+ _FORCE_INLINE_ bool _is_at_end() { return position >= length; }
+ _FORCE_INLINE_ char32_t _peek(int p_offset = 0) { return position + p_offset >= 0 && position + p_offset < length ? _current[p_offset] : '\0'; }
+ int indent_level() const { return indent_stack.size(); }
+ bool has_error() const { return !error_stack.is_empty(); }
+ Token pop_error();
+ char32_t _advance();
+ void _skip_whitespace();
+ void check_indent();
-class GDScriptTokenizerBuffer : public GDScriptTokenizer {
+ Token make_error(const String &p_message);
+ void push_error(const String &p_message);
+ void push_error(const Token &p_error);
+ Token make_paren_error(char32_t p_paren);
+ Token make_token(Token::Type p_type);
+ Token make_literal(const Variant &p_literal);
+ Token make_identifier(const StringName &p_identifier);
+ Token check_vcs_marker(char32_t p_test, Token::Type p_double_type);
+ void push_paren(char32_t p_char);
+ bool pop_paren(char32_t p_expected);
- enum {
+ void newline(bool p_make_token);
+ Token number();
+ Token potential_identifier();
+ Token string();
+ Token annotation();
- TOKEN_BYTE_MASK = 0x80,
- TOKEN_BITS = 8,
- TOKEN_MASK = (1 << TOKEN_BITS) - 1,
- TOKEN_LINE_BITS = 24,
- TOKEN_LINE_MASK = (1 << TOKEN_LINE_BITS) - 1,
- };
+public:
+ Token scan();
- Vector<StringName> identifiers;
- Vector<Variant> constants;
- VMap<uint32_t, uint32_t> lines;
- Vector<uint32_t> tokens;
- Variant nil;
- int token;
+ void set_source_code(const String &p_source_code);
-public:
- Error set_code_buffer(const Vector<uint8_t> &p_buffer);
- static Vector<uint8_t> parse_code_string(const String &p_code);
- virtual Token get_token(int p_offset = 0) const;
- virtual StringName get_token_identifier(int p_offset = 0) const;
- virtual GDScriptFunctions::Function get_token_built_in_func(int p_offset = 0) const;
- virtual Variant::Type get_token_type(int p_offset = 0) const;
- virtual int get_token_line(int p_offset = 0) const;
- virtual int get_token_column(int p_offset = 0) const;
- virtual int get_token_line_indent(int p_offset = 0) const;
- virtual int get_token_line_tab_indent(int p_offset = 0) const { return 0; }
- virtual const Variant &get_token_constant(int p_offset = 0) const;
- virtual String get_token_error(int p_offset = 0) const;
- virtual void advance(int p_amount = 1);
-#ifdef DEBUG_ENABLED
- virtual const Vector<Pair<int, String>> &get_warning_skips() const {
- static Vector<Pair<int, String>> v;
- return v;
- }
- virtual const Set<String> &get_warning_global_skips() const {
- static Set<String> s;
- return s;
- }
- virtual bool is_ignoring_warnings() const { return true; }
-#endif // DEBUG_ENABLED
- GDScriptTokenizerBuffer();
+ int get_cursor_line() const;
+ int get_cursor_column() const;
+ void set_cursor_position(int p_line, int p_column);
+ void set_multiline_mode(bool p_state);
+ bool is_past_cursor() const;
+ static String get_token_name(Token::Type p_token_type);
+
+ GDScriptTokenizer();
};
-#endif // GDSCRIPT_TOKENIZER_H
+#endif
diff --git a/modules/gdscript/gdscript_utility_functions.cpp b/modules/gdscript/gdscript_utility_functions.cpp
new file mode 100644
index 0000000000..348d221352
--- /dev/null
+++ b/modules/gdscript/gdscript_utility_functions.cpp
@@ -0,0 +1,718 @@
+/*************************************************************************/
+/* gdscript_utility_functions.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_utility_functions.h"
+
+#include "core/io/resource_loader.h"
+#include "core/object/class_db.h"
+#include "core/object/method_bind.h"
+#include "core/object/object.h"
+#include "core/templates/oa_hash_map.h"
+#include "core/templates/vector.h"
+#include "gdscript.h"
+
+#ifdef DEBUG_ENABLED
+
+#define VALIDATE_ARG_COUNT(m_count) \
+ if (p_arg_count < m_count) { \
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; \
+ r_error.argument = m_count; \
+ r_error.expected = m_count; \
+ *r_ret = Variant(); \
+ return; \
+ } \
+ if (p_arg_count > m_count) { \
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; \
+ r_error.argument = m_count; \
+ r_error.expected = m_count; \
+ *r_ret = Variant(); \
+ return; \
+ }
+
+#define VALIDATE_ARG_INT(m_arg) \
+ if (p_args[m_arg]->get_type() != Variant::INT) { \
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
+ r_error.argument = m_arg; \
+ r_error.expected = Variant::INT; \
+ *r_ret = Variant(); \
+ return; \
+ }
+
+#define VALIDATE_ARG_NUM(m_arg) \
+ if (!p_args[m_arg]->is_num()) { \
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; \
+ r_error.argument = m_arg; \
+ r_error.expected = Variant::FLOAT; \
+ *r_ret = Variant(); \
+ return; \
+ }
+
+#else
+
+#define VALIDATE_ARG_COUNT(m_count)
+#define VALIDATE_ARG_INT(m_arg)
+#define VALIDATE_ARG_NUM(m_arg)
+
+#endif
+
+struct GDScriptUtilityFunctionsDefinitions {
+ static inline void convert(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(2);
+ VALIDATE_ARG_INT(1);
+ int type = *p_args[1];
+ if (type < 0 || type >= Variant::VARIANT_MAX) {
+ *r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants.");
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::INT;
+ return;
+
+ } else {
+ Variant::construct(Variant::Type(type), *r_ret, p_args, 1, r_error);
+ }
+ }
+
+ static inline void type_exists(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+ *r_ret = ClassDB::class_exists(*p_args[0]);
+ }
+
+ static inline void _char(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+ VALIDATE_ARG_INT(0);
+ char32_t result[2] = { *p_args[0], 0 };
+ *r_ret = String(result);
+ }
+
+ static inline void str(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ if (p_arg_count < 1) {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
+ *r_ret = Variant();
+ return;
+ }
+
+ String str;
+ for (int i = 0; i < p_arg_count; i++) {
+ String os = p_args[i]->operator String();
+
+ if (i == 0) {
+ str = os;
+ } else {
+ str += os;
+ }
+ }
+ *r_ret = str;
+ }
+
+ static inline void range(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ switch (p_arg_count) {
+ case 0: {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
+ r_error.expected = 1;
+ *r_ret = Variant();
+ } break;
+ case 1: {
+ VALIDATE_ARG_NUM(0);
+ int count = *p_args[0];
+ Array arr;
+ if (count <= 0) {
+ *r_ret = arr;
+ return;
+ }
+ Error err = arr.resize(count);
+ if (err != OK) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ *r_ret = Variant();
+ return;
+ }
+
+ for (int i = 0; i < count; i++) {
+ arr[i] = i;
+ }
+
+ *r_ret = arr;
+ } break;
+ case 2: {
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+
+ int from = *p_args[0];
+ int to = *p_args[1];
+
+ Array arr;
+ if (from >= to) {
+ *r_ret = arr;
+ return;
+ }
+ Error err = arr.resize(to - from);
+ if (err != OK) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ *r_ret = Variant();
+ return;
+ }
+ for (int i = from; i < to; i++) {
+ arr[i - from] = i;
+ }
+ *r_ret = arr;
+ } break;
+ case 3: {
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ VALIDATE_ARG_NUM(2);
+
+ int from = *p_args[0];
+ int to = *p_args[1];
+ int incr = *p_args[2];
+ if (incr == 0) {
+ *r_ret = RTR("Step argument is zero!");
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ return;
+ }
+
+ Array arr;
+ if (from >= to && incr > 0) {
+ *r_ret = arr;
+ return;
+ }
+ if (from <= to && incr < 0) {
+ *r_ret = arr;
+ return;
+ }
+
+ // Calculate how many.
+ int count = 0;
+ if (incr > 0) {
+ count = ((to - from - 1) / incr) + 1;
+ } else {
+ count = ((from - to - 1) / -incr) + 1;
+ }
+
+ Error err = arr.resize(count);
+
+ if (err != OK) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ *r_ret = Variant();
+ return;
+ }
+
+ if (incr > 0) {
+ int idx = 0;
+ for (int i = from; i < to; i += incr) {
+ arr[idx++] = i;
+ }
+ } else {
+ int idx = 0;
+ for (int i = from; i > to; i += incr) {
+ arr[idx++] = i;
+ }
+ }
+
+ *r_ret = arr;
+ } break;
+ default: {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = 3;
+ r_error.expected = 3;
+ *r_ret = Variant();
+
+ } break;
+ }
+ }
+
+ static inline void load(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
+ *r_ret = Variant();
+ } else {
+ *r_ret = ResourceLoader::load(*p_args[0]);
+ }
+ }
+
+ static inline void inst2dict(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+
+ if (p_args[0]->get_type() == Variant::NIL) {
+ *r_ret = Variant();
+ } else if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ *r_ret = Variant();
+ } else {
+ Object *obj = *p_args[0];
+ if (!obj) {
+ *r_ret = Variant();
+
+ } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::DICTIONARY;
+ *r_ret = RTR("Not a script with an instance");
+ return;
+ } else {
+ GDScriptInstance *ins = static_cast<GDScriptInstance *>(obj->get_script_instance());
+ Ref<GDScript> base = ins->get_script();
+ if (base.is_null()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::DICTIONARY;
+ *r_ret = RTR("Not based on a script");
+ return;
+ }
+
+ GDScript *p = base.ptr();
+ Vector<StringName> sname;
+
+ while (p->_owner) {
+ sname.push_back(p->name);
+ p = p->_owner;
+ }
+ sname.invert();
+
+ if (!p->path.is_resource_file()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::DICTIONARY;
+ *r_ret = Variant();
+
+ *r_ret = RTR("Not based on a resource file");
+
+ return;
+ }
+
+ NodePath cp(sname, Vector<StringName>(), false);
+
+ Dictionary d;
+ d["@subpath"] = cp;
+ d["@path"] = p->get_path();
+
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = base->member_indices.front(); E; E = E->next()) {
+ if (!d.has(E->key())) {
+ d[E->key()] = ins->members[E->get().index];
+ }
+ }
+ *r_ret = d;
+ }
+ }
+ }
+
+ static inline void dict2inst(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+
+ if (p_args[0]->get_type() != Variant::DICTIONARY) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::DICTIONARY;
+ *r_ret = Variant();
+
+ return;
+ }
+
+ Dictionary d = *p_args[0];
+
+ if (!d.has("@path")) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ *r_ret = RTR("Invalid instance dictionary format (missing @path)");
+
+ return;
+ }
+
+ Ref<Script> scr = ResourceLoader::load(d["@path"]);
+ if (!scr.is_valid()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ *r_ret = RTR("Invalid instance dictionary format (can't load script at @path)");
+ return;
+ }
+
+ Ref<GDScript> gdscr = scr;
+
+ if (!gdscr.is_valid()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ *r_ret = Variant();
+ *r_ret = RTR("Invalid instance dictionary format (invalid script at @path)");
+ return;
+ }
+
+ NodePath sub;
+ if (d.has("@subpath")) {
+ sub = d["@subpath"];
+ }
+
+ for (int i = 0; i < sub.get_name_count(); i++) {
+ gdscr = gdscr->subclasses[sub.get_name(i)];
+ if (!gdscr.is_valid()) {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ *r_ret = Variant();
+ *r_ret = RTR("Invalid instance dictionary (invalid subclasses)");
+ return;
+ }
+ }
+ *r_ret = gdscr->_new(nullptr, -1 /*skip initializer*/, r_error);
+
+ if (r_error.error != Callable::CallError::CALL_OK) {
+ *r_ret = Variant();
+ return;
+ }
+
+ GDScriptInstance *ins = static_cast<GDScriptInstance *>(static_cast<Object *>(*r_ret)->get_script_instance());
+ Ref<GDScript> gd_ref = ins->get_script();
+
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) {
+ if (d.has(E->key())) {
+ ins->members.write[E->get().index] = d[E->key()];
+ }
+ }
+ }
+
+ static inline void Color8(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ if (p_arg_count < 3) {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 3;
+ *r_ret = Variant();
+ return;
+ }
+ if (p_arg_count > 4) {
+ r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = 4;
+ *r_ret = Variant();
+ return;
+ }
+
+ VALIDATE_ARG_INT(0);
+ VALIDATE_ARG_INT(1);
+ VALIDATE_ARG_INT(2);
+
+ Color color((int64_t)*p_args[0] / 255.0f, (int64_t)*p_args[1] / 255.0f, (int64_t)*p_args[2] / 255.0f);
+
+ if (p_arg_count == 4) {
+ VALIDATE_ARG_INT(3);
+ color.a = (int64_t)*p_args[3] / 255.0f;
+ }
+
+ *r_ret = color;
+ }
+
+ static inline void print_debug(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ String str;
+ for (int i = 0; i < p_arg_count; i++) {
+ str += p_args[i]->operator String();
+ }
+
+ ScriptLanguage *script = GDScriptLanguage::get_singleton();
+ if (script->debug_get_stack_level_count() > 0) {
+ str += "\n At: " + script->debug_get_stack_level_source(0) + ":" + itos(script->debug_get_stack_level_line(0)) + ":" + script->debug_get_stack_level_function(0) + "()";
+ }
+
+ print_line(str);
+ *r_ret = Variant();
+ }
+
+ static inline void print_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(0);
+
+ ScriptLanguage *script = GDScriptLanguage::get_singleton();
+ for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
+ print_line("Frame " + itos(i) + " - " + script->debug_get_stack_level_source(i) + ":" + itos(script->debug_get_stack_level_line(i)) + " in function '" + script->debug_get_stack_level_function(i) + "'");
+ };
+ }
+
+ static inline void get_stack(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(0);
+
+ ScriptLanguage *script = GDScriptLanguage::get_singleton();
+ Array ret;
+ for (int i = 0; i < script->debug_get_stack_level_count(); i++) {
+ Dictionary frame;
+ frame["source"] = script->debug_get_stack_level_source(i);
+ frame["function"] = script->debug_get_stack_level_function(i);
+ frame["line"] = script->debug_get_stack_level_line(i);
+ ret.push_back(frame);
+ };
+ *r_ret = ret;
+ }
+
+ static inline void len(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) {
+ VALIDATE_ARG_COUNT(1);
+ switch (p_args[0]->get_type()) {
+ case Variant::STRING: {
+ String d = *p_args[0];
+ *r_ret = d.length();
+ } break;
+ case Variant::DICTIONARY: {
+ Dictionary d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::ARRAY: {
+ Array d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_BYTE_ARRAY: {
+ Vector<uint8_t> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_INT32_ARRAY: {
+ Vector<int32_t> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_INT64_ARRAY: {
+ Vector<int64_t> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_FLOAT32_ARRAY: {
+ Vector<float> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_FLOAT64_ARRAY: {
+ Vector<double> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_STRING_ARRAY: {
+ Vector<String> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_VECTOR2_ARRAY: {
+ Vector<Vector2> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_VECTOR3_ARRAY: {
+ Vector<Vector3> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ case Variant::PACKED_COLOR_ARRAY: {
+ Vector<Color> d = *p_args[0];
+ *r_ret = d.size();
+ } break;
+ default: {
+ r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::NIL;
+ *r_ret = vformat(RTR("Value of type '%s' can't provide a length."), Variant::get_type_name(p_args[0]->get_type()));
+ }
+ }
+ }
+};
+
+struct GDScriptUtilityFunctionInfo {
+ GDScriptUtilityFunctions::FunctionPtr function;
+ MethodInfo info;
+ bool is_constant = false;
+};
+
+static OAHashMap<StringName, GDScriptUtilityFunctionInfo> utility_function_table;
+static List<StringName> utility_function_name_table;
+
+static void _register_function(const String &p_name, const MethodInfo &p_method_info, GDScriptUtilityFunctions::FunctionPtr p_function, bool p_is_const) {
+ StringName sname(p_name);
+
+ ERR_FAIL_COND(utility_function_table.has(sname));
+
+ GDScriptUtilityFunctionInfo function;
+ function.function = p_function;
+ function.info = p_method_info;
+ function.is_constant = p_is_const;
+
+ utility_function_table.insert(sname, function);
+ utility_function_name_table.push_back(sname);
+}
+
+#define REGISTER_FUNC(m_func, m_is_const, m_return_type, ...) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name, __VA_ARGS__); \
+ info.return_val.type = m_return_type; \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define REGISTER_FUNC_NO_ARGS(m_func, m_is_const, m_return_type) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name); \
+ info.return_val.type = m_return_type; \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define REGISTER_VARARG_FUNC(m_func, m_is_const, m_return_type) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name); \
+ info.return_val.type = m_return_type; \
+ info.flags |= METHOD_FLAG_VARARG; \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define REGISTER_VARIANT_FUNC(m_func, m_is_const, ...) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name, __VA_ARGS__); \
+ info.return_val.type = Variant::NIL; \
+ info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define REGISTER_CLASS_FUNC(m_func, m_is_const, m_return_type, ...) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name, __VA_ARGS__); \
+ info.return_val.type = Variant::OBJECT; \
+ info.return_val.hint = PROPERTY_HINT_RESOURCE_TYPE; \
+ info.return_val.class_name = m_return_type; \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define REGISTER_FUNC_DEF(m_func, m_is_const, m_default, m_return_type, ...) \
+ { \
+ String name(#m_func); \
+ if (name.begins_with("_")) { \
+ name = name.substr(1, name.length() - 1); \
+ } \
+ MethodInfo info = MethodInfo(name, __VA_ARGS__); \
+ info.return_val.type = m_return_type; \
+ info.default_arguments.push_back(m_default); \
+ _register_function(name, info, GDScriptUtilityFunctionsDefinitions::m_func, m_is_const); \
+ }
+
+#define ARG(m_name, m_type) \
+ PropertyInfo(m_type, m_name)
+
+#define VARARG(m_name) \
+ PropertyInfo(Variant::NIL, m_name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT)
+
+void GDScriptUtilityFunctions::register_functions() {
+ REGISTER_VARIANT_FUNC(convert, true, VARARG("what"), ARG("type", Variant::INT));
+ REGISTER_FUNC(type_exists, true, Variant::BOOL, ARG("type", Variant::STRING_NAME));
+ REGISTER_FUNC(_char, true, Variant::STRING, ARG("char", Variant::INT));
+ REGISTER_VARARG_FUNC(str, true, Variant::STRING);
+ REGISTER_VARARG_FUNC(range, false, Variant::ARRAY);
+ REGISTER_CLASS_FUNC(load, false, "Resource", ARG("path", Variant::STRING));
+ REGISTER_FUNC(inst2dict, false, Variant::DICTIONARY, ARG("instance", Variant::OBJECT));
+ REGISTER_FUNC(dict2inst, false, Variant::OBJECT, ARG("dictionary", Variant::DICTIONARY));
+ REGISTER_FUNC_DEF(Color8, true, 255, Variant::COLOR, ARG("r8", Variant::INT), ARG("g8", Variant::INT), ARG("b8", Variant::INT), ARG("a8", Variant::INT));
+ REGISTER_VARARG_FUNC(print_debug, false, Variant::NIL);
+ REGISTER_FUNC_NO_ARGS(print_stack, false, Variant::NIL);
+ REGISTER_FUNC_NO_ARGS(get_stack, false, Variant::ARRAY);
+ REGISTER_FUNC(len, true, Variant::INT, VARARG("var"));
+}
+
+void GDScriptUtilityFunctions::unregister_functions() {
+ utility_function_name_table.clear();
+ utility_function_table.clear();
+}
+
+GDScriptUtilityFunctions::FunctionPtr GDScriptUtilityFunctions::get_function(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, nullptr);
+ return info->function;
+}
+
+bool GDScriptUtilityFunctions::has_function_return_value(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, false);
+ return info->info.return_val.type != Variant::NIL || bool(info->info.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT);
+}
+
+Variant::Type GDScriptUtilityFunctions::get_function_return_type(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, Variant::NIL);
+ return info->info.return_val.type;
+}
+
+StringName GDScriptUtilityFunctions::get_function_return_class(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, StringName());
+ return info->info.return_val.class_name;
+}
+
+Variant::Type GDScriptUtilityFunctions::get_function_argument_type(const StringName &p_function, int p_arg) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, Variant::NIL);
+ ERR_FAIL_COND_V(p_arg >= info->info.arguments.size(), Variant::NIL);
+ return info->info.arguments[p_arg].type;
+}
+
+int GDScriptUtilityFunctions::get_function_argument_count(const StringName &p_function, int p_arg) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, 0);
+ return info->info.arguments.size();
+}
+
+bool GDScriptUtilityFunctions::is_function_vararg(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, false);
+ return (bool)(info->info.flags & METHOD_FLAG_VARARG);
+}
+
+bool GDScriptUtilityFunctions::is_function_constant(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, false);
+ return info->is_constant;
+}
+
+bool GDScriptUtilityFunctions::function_exists(const StringName &p_function) {
+ return utility_function_table.has(p_function);
+}
+
+void GDScriptUtilityFunctions::get_function_list(List<StringName> *r_functions) {
+ for (const List<StringName>::Element *E = utility_function_name_table.front(); E; E = E->next()) {
+ r_functions->push_back(E->get());
+ }
+}
+
+MethodInfo GDScriptUtilityFunctions::get_function_info(const StringName &p_function) {
+ GDScriptUtilityFunctionInfo *info = utility_function_table.lookup_ptr(p_function);
+ ERR_FAIL_COND_V(!info, MethodInfo());
+ return info->info;
+}
diff --git a/modules/gdscript/gdscript_utility_functions.h b/modules/gdscript/gdscript_utility_functions.h
new file mode 100644
index 0000000000..c6d3718844
--- /dev/null
+++ b/modules/gdscript/gdscript_utility_functions.h
@@ -0,0 +1,58 @@
+/*************************************************************************/
+/* gdscript_utility_functions.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_UTILITY_FUNCTIONS_H
+#define GDSCRIPT_UTILITY_FUNCTIONS_H
+
+#include "core/string/string_name.h"
+#include "core/variant/variant.h"
+
+class GDScriptUtilityFunctions {
+public:
+ typedef void (*FunctionPtr)(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error);
+
+ static FunctionPtr get_function(const StringName &p_function);
+ static bool has_function_return_value(const StringName &p_function);
+ static Variant::Type get_function_return_type(const StringName &p_function);
+ static StringName get_function_return_class(const StringName &p_function);
+ static Variant::Type get_function_argument_type(const StringName &p_function, int p_arg);
+ static int get_function_argument_count(const StringName &p_function, int p_arg);
+ static bool is_function_vararg(const StringName &p_function);
+ static bool is_function_constant(const StringName &p_function);
+
+ static bool function_exists(const StringName &p_function);
+ static void get_function_list(List<StringName> *r_functions);
+ static MethodInfo get_function_info(const StringName &p_function);
+
+ static void register_functions();
+ static void unregister_functions();
+};
+
+#endif // GDSCRIPT_UTILITY_FUNCTIONS_H
diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp
new file mode 100644
index 0000000000..4e098d7a6d
--- /dev/null
+++ b/modules/gdscript/gdscript_vm.cpp
@@ -0,0 +1,2918 @@
+/*************************************************************************/
+/* gdscript_vm.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_function.h"
+
+#include "core/core_string_names.h"
+#include "core/os/os.h"
+#include "gdscript.h"
+
+Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_instance, GDScript *p_script, Variant &self, Variant &static_ref, Variant *p_stack, String &r_error) const {
+ int address = p_address & ADDR_MASK;
+
+ //sequential table (jump table generated by compiler)
+ switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) {
+ case ADDR_TYPE_SELF: {
+#ifdef DEBUG_ENABLED
+ if (unlikely(!p_instance)) {
+ r_error = "Cannot access self without instance.";
+ return nullptr;
+ }
+#endif
+ return &self;
+ } break;
+ case ADDR_TYPE_CLASS: {
+ return &static_ref;
+ } break;
+ case ADDR_TYPE_MEMBER: {
+#ifdef DEBUG_ENABLED
+ if (unlikely(!p_instance)) {
+ r_error = "Cannot access member without instance.";
+ return nullptr;
+ }
+#endif
+ //member indexing is O(1)
+ return &p_instance->members.write[address];
+ } break;
+ case ADDR_TYPE_CLASS_CONSTANT: {
+ //todo change to index!
+ GDScript *s = p_script;
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_INDEX_V(address, _global_names_count, nullptr);
+#endif
+ const StringName *sn = &_global_names_ptr[address];
+
+ while (s) {
+ GDScript *o = s;
+ while (o) {
+ Map<StringName, Variant>::Element *E = o->constants.find(*sn);
+ if (E) {
+ return &E->get();
+ }
+ o = o->_owner;
+ }
+ s = s->_base;
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "GDScriptCompiler bug.");
+ } break;
+ case ADDR_TYPE_LOCAL_CONSTANT: {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_INDEX_V(address, _constant_count, nullptr);
+#endif
+ return &_constants_ptr[address];
+ } break;
+ case ADDR_TYPE_STACK:
+ case ADDR_TYPE_STACK_VARIABLE: {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_INDEX_V(address, _stack_size, nullptr);
+#endif
+ return &p_stack[address];
+ } break;
+ case ADDR_TYPE_GLOBAL: {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), nullptr);
+#endif
+ return &GDScriptLanguage::get_singleton()->get_global_array()[address];
+ } break;
+#ifdef TOOLS_ENABLED
+ case ADDR_TYPE_NAMED_GLOBAL: {
+#ifdef DEBUG_ENABLED
+ ERR_FAIL_INDEX_V(address, _global_names_count, nullptr);
+#endif
+ StringName id = _global_names_ptr[address];
+
+ if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(id)) {
+ return (Variant *)&GDScriptLanguage::get_singleton()->get_named_globals_map()[id];
+ } else {
+ r_error = "Autoload singleton '" + String(id) + "' has been removed.";
+ return nullptr;
+ }
+ } break;
+#endif
+ case ADDR_TYPE_NIL: {
+ return &nil;
+ } break;
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Bad code! (unknown addressing mode).");
+ return nullptr;
+}
+
+#ifdef DEBUG_ENABLED
+static String _get_var_type(const Variant *p_var) {
+ String basestr;
+
+ if (p_var->get_type() == Variant::OBJECT) {
+ bool was_freed;
+ Object *bobj = p_var->get_validated_object_with_check(was_freed);
+ if (!bobj) {
+ if (was_freed) {
+ basestr = "null instance";
+ } else {
+ basestr = "previously freed";
+ }
+ } else {
+ if (bobj->get_script_instance()) {
+ basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")";
+ } else {
+ basestr = bobj->get_class();
+ }
+ }
+
+ } else {
+ basestr = Variant::get_type_name(p_var->get_type());
+ }
+
+ return basestr;
+}
+#endif // DEBUG_ENABLED
+
+String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const String &p_where, const Variant **argptrs) const {
+ String err_text;
+
+ if (p_err.error == Callable::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(Variant::Type(p_err.expected)) + ".";
+ }
+ } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
+ err_text = "Invalid call. Nonexistent " + p_where + ".";
+ } else if (p_err.error == Callable::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 \
+ static const void *switch_table_ops[] = { \
+ &&OPCODE_OPERATOR, \
+ &&OPCODE_OPERATOR_VALIDATED, \
+ &&OPCODE_EXTENDS_TEST, \
+ &&OPCODE_IS_BUILTIN, \
+ &&OPCODE_SET_KEYED, \
+ &&OPCODE_SET_KEYED_VALIDATED, \
+ &&OPCODE_SET_INDEXED_VALIDATED, \
+ &&OPCODE_GET_KEYED, \
+ &&OPCODE_GET_KEYED_VALIDATED, \
+ &&OPCODE_GET_INDEXED_VALIDATED, \
+ &&OPCODE_SET_NAMED, \
+ &&OPCODE_SET_NAMED_VALIDATED, \
+ &&OPCODE_GET_NAMED, \
+ &&OPCODE_GET_NAMED_VALIDATED, \
+ &&OPCODE_SET_MEMBER, \
+ &&OPCODE_GET_MEMBER, \
+ &&OPCODE_ASSIGN, \
+ &&OPCODE_ASSIGN_TRUE, \
+ &&OPCODE_ASSIGN_FALSE, \
+ &&OPCODE_ASSIGN_TYPED_BUILTIN, \
+ &&OPCODE_ASSIGN_TYPED_NATIVE, \
+ &&OPCODE_ASSIGN_TYPED_SCRIPT, \
+ &&OPCODE_CAST_TO_BUILTIN, \
+ &&OPCODE_CAST_TO_NATIVE, \
+ &&OPCODE_CAST_TO_SCRIPT, \
+ &&OPCODE_CONSTRUCT, \
+ &&OPCODE_CONSTRUCT_VALIDATED, \
+ &&OPCODE_CONSTRUCT_ARRAY, \
+ &&OPCODE_CONSTRUCT_DICTIONARY, \
+ &&OPCODE_CALL, \
+ &&OPCODE_CALL_RETURN, \
+ &&OPCODE_CALL_ASYNC, \
+ &&OPCODE_CALL_UTILITY, \
+ &&OPCODE_CALL_UTILITY_VALIDATED, \
+ &&OPCODE_CALL_GDSCRIPT_UTILITY, \
+ &&OPCODE_CALL_BUILTIN_TYPE_VALIDATED, \
+ &&OPCODE_CALL_SELF_BASE, \
+ &&OPCODE_CALL_METHOD_BIND, \
+ &&OPCODE_CALL_METHOD_BIND_RET, \
+ &&OPCODE_CALL_PTRCALL_NO_RETURN, \
+ &&OPCODE_CALL_PTRCALL_BOOL, \
+ &&OPCODE_CALL_PTRCALL_INT, \
+ &&OPCODE_CALL_PTRCALL_FLOAT, \
+ &&OPCODE_CALL_PTRCALL_STRING, \
+ &&OPCODE_CALL_PTRCALL_VECTOR2, \
+ &&OPCODE_CALL_PTRCALL_VECTOR2I, \
+ &&OPCODE_CALL_PTRCALL_RECT2, \
+ &&OPCODE_CALL_PTRCALL_RECT2I, \
+ &&OPCODE_CALL_PTRCALL_VECTOR3, \
+ &&OPCODE_CALL_PTRCALL_VECTOR3I, \
+ &&OPCODE_CALL_PTRCALL_TRANSFORM2D, \
+ &&OPCODE_CALL_PTRCALL_PLANE, \
+ &&OPCODE_CALL_PTRCALL_QUAT, \
+ &&OPCODE_CALL_PTRCALL_AABB, \
+ &&OPCODE_CALL_PTRCALL_BASIS, \
+ &&OPCODE_CALL_PTRCALL_TRANSFORM, \
+ &&OPCODE_CALL_PTRCALL_COLOR, \
+ &&OPCODE_CALL_PTRCALL_STRING_NAME, \
+ &&OPCODE_CALL_PTRCALL_NODE_PATH, \
+ &&OPCODE_CALL_PTRCALL_RID, \
+ &&OPCODE_CALL_PTRCALL_OBJECT, \
+ &&OPCODE_CALL_PTRCALL_CALLABLE, \
+ &&OPCODE_CALL_PTRCALL_SIGNAL, \
+ &&OPCODE_CALL_PTRCALL_DICTIONARY, \
+ &&OPCODE_CALL_PTRCALL_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_BYTE_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_INT32_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_INT64_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_FLOAT32_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_FLOAT64_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_STRING_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_VECTOR2_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_VECTOR3_ARRAY, \
+ &&OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY, \
+ &&OPCODE_AWAIT, \
+ &&OPCODE_AWAIT_RESUME, \
+ &&OPCODE_JUMP, \
+ &&OPCODE_JUMP_IF, \
+ &&OPCODE_JUMP_IF_NOT, \
+ &&OPCODE_JUMP_TO_DEF_ARGUMENT, \
+ &&OPCODE_RETURN, \
+ &&OPCODE_ITERATE_BEGIN, \
+ &&OPCODE_ITERATE_BEGIN_INT, \
+ &&OPCODE_ITERATE_BEGIN_FLOAT, \
+ &&OPCODE_ITERATE_BEGIN_VECTOR2, \
+ &&OPCODE_ITERATE_BEGIN_VECTOR2I, \
+ &&OPCODE_ITERATE_BEGIN_VECTOR3, \
+ &&OPCODE_ITERATE_BEGIN_VECTOR3I, \
+ &&OPCODE_ITERATE_BEGIN_STRING, \
+ &&OPCODE_ITERATE_BEGIN_DICTIONARY, \
+ &&OPCODE_ITERATE_BEGIN_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_BYTE_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_INT32_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_INT64_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_FLOAT32_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_FLOAT64_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_STRING_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_VECTOR2_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_VECTOR3_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_PACKED_COLOR_ARRAY, \
+ &&OPCODE_ITERATE_BEGIN_OBJECT, \
+ &&OPCODE_ITERATE, \
+ &&OPCODE_ITERATE_INT, \
+ &&OPCODE_ITERATE_FLOAT, \
+ &&OPCODE_ITERATE_VECTOR2, \
+ &&OPCODE_ITERATE_VECTOR2I, \
+ &&OPCODE_ITERATE_VECTOR3, \
+ &&OPCODE_ITERATE_VECTOR3I, \
+ &&OPCODE_ITERATE_STRING, \
+ &&OPCODE_ITERATE_DICTIONARY, \
+ &&OPCODE_ITERATE_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_BYTE_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_INT32_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_INT64_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_FLOAT32_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_FLOAT64_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_STRING_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_VECTOR2_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_VECTOR3_ARRAY, \
+ &&OPCODE_ITERATE_PACKED_COLOR_ARRAY, \
+ &&OPCODE_ITERATE_OBJECT, \
+ &&OPCODE_ASSERT, \
+ &&OPCODE_BREAKPOINT, \
+ &&OPCODE_LINE, \
+ &&OPCODE_END \
+ }; \
+ static_assert((sizeof(switch_table_ops) / sizeof(switch_table_ops[0]) == (OPCODE_END + 1)), "Opcodes in jump table aren't the same as opcodes in enum.");
+
+#define OPCODE(m_op) \
+ m_op:
+#define OPCODE_WHILE(m_test) \
+ OPSWHILE:
+#define OPCODES_END \
+ OPSEXIT:
+#define OPCODES_OUT \
+ OPSOUT:
+#define DISPATCH_OPCODE goto OPSWHILE
+#define OPCODE_SWITCH(m_test) goto *switch_table_ops[m_test];
+#define OPCODE_BREAK goto OPSEXIT
+#define OPCODE_OUT goto OPSOUT
+#else
+#define OPCODES_TABLE
+#define OPCODE(m_op) case m_op:
+#define OPCODE_WHILE(m_test) while (m_test)
+#define OPCODES_END
+#define OPCODES_OUT
+#define DISPATCH_OPCODE continue
+#define OPCODE_SWITCH(m_test) switch (m_test)
+#define OPCODE_BREAK break
+#define OPCODE_OUT break
+#endif
+
+// Helpers for VariantInternal methods in macros.
+#define OP_GET_BOOL get_bool
+#define OP_GET_INT get_int
+#define OP_GET_FLOAT get_float
+#define OP_GET_VECTOR2 get_vector2
+#define OP_GET_VECTOR2I get_vector2i
+#define OP_GET_VECTOR3 get_vector3
+#define OP_GET_VECTOR3I get_vector3i
+#define OP_GET_RECT2 get_rect2
+#define OP_GET_RECT2I get_rect2i
+#define OP_GET_QUAT get_quat
+#define OP_GET_COLOR get_color
+#define OP_GET_STRING get_string
+#define OP_GET_STRING_NAME get_string_name
+#define OP_GET_NODE_PATH get_node_path
+#define OP_GET_CALLABLE get_callable
+#define OP_GET_SIGNAL get_signal
+#define OP_GET_ARRAY get_array
+#define OP_GET_DICTIONARY get_dictionary
+#define OP_GET_PACKED_BYTE_ARRAY get_byte_array
+#define OP_GET_PACKED_INT32_ARRAY get_int32_array
+#define OP_GET_PACKED_INT64_ARRAY get_int64_array
+#define OP_GET_PACKED_FLOAT32_ARRAY get_float32_array
+#define OP_GET_PACKED_FLOAT64_ARRAY get_float64_array
+#define OP_GET_PACKED_STRING_ARRAY get_string_array
+#define OP_GET_PACKED_VECTOR2_ARRAY get_vector2_array
+#define OP_GET_PACKED_VECTOR3_ARRAY get_vector3_array
+#define OP_GET_PACKED_COLOR_ARRAY get_color_array
+#define OP_GET_TRANSFORM get_transform
+#define OP_GET_TRANSFORM2D get_transform2d
+#define OP_GET_PLANE get_plane
+#define OP_GET_AABB get_aabb
+#define OP_GET_BASIS get_basis
+#define OP_GET_RID get_rid
+
+Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_args, int p_argcount, Callable::CallError &r_err, CallState *p_state) {
+ OPCODES_TABLE;
+
+ if (!_code_ptr) {
+ return Variant();
+ }
+
+ r_err.error = Callable::CallError::CALL_OK;
+
+ Variant self;
+ Variant static_ref;
+ Variant retvalue;
+ Variant *stack = nullptr;
+ Variant **instruction_args;
+ const void **call_args_ptr = nullptr;
+ int defarg = 0;
+
+#ifdef DEBUG_ENABLED
+
+ //GDScriptLanguage::get_singleton()->calls++;
+
+#endif
+
+ uint32_t alloca_size = 0;
+ GDScript *script;
+ int ip = 0;
+ int line = _initial_line;
+
+ if (p_state) {
+ //use existing (supplied) state (awaited)
+ stack = (Variant *)p_state->stack.ptr();
+ instruction_args = (Variant **)&p_state->stack.ptr()[sizeof(Variant) * p_state->stack_size]; //ptr() to avoid bounds check
+ line = p_state->line;
+ ip = p_state->ip;
+ alloca_size = p_state->stack.size();
+ script = p_state->script;
+ p_instance = p_state->instance;
+ defarg = p_state->defarg;
+ self = p_state->self;
+
+ } else {
+ if (p_argcount != _argument_count) {
+ if (p_argcount > _argument_count) {
+ r_err.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_err.argument = _argument_count;
+
+ return Variant();
+ } else if (p_argcount < _argument_count - _default_arg_count) {
+ r_err.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_err.argument = _argument_count - _default_arg_count;
+ return Variant();
+ } else {
+ defarg = _argument_count - p_argcount;
+ }
+ }
+
+ alloca_size = sizeof(Variant *) * _instruction_args_size + sizeof(Variant) * _stack_size;
+
+ if (alloca_size) {
+ uint8_t *aptr = (uint8_t *)alloca(alloca_size);
+
+ if (_stack_size) {
+ stack = (Variant *)aptr;
+ for (int i = 0; i < p_argcount; i++) {
+ if (!argument_types[i].has_type) {
+ memnew_placement(&stack[i], Variant(*p_args[i]));
+ continue;
+ }
+
+ if (!argument_types[i].is_type(*p_args[i], true)) {
+ r_err.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_err.argument = i;
+ r_err.expected = argument_types[i].kind == GDScriptDataType::BUILTIN ? argument_types[i].builtin_type : Variant::OBJECT;
+ return Variant();
+ }
+ if (argument_types[i].kind == GDScriptDataType::BUILTIN) {
+ Variant arg;
+ Variant::construct(argument_types[i].builtin_type, arg, &p_args[i], 1, r_err);
+ memnew_placement(&stack[i], Variant(arg));
+ } else {
+ memnew_placement(&stack[i], Variant(*p_args[i]));
+ }
+ }
+ for (int i = p_argcount; i < _stack_size; i++) {
+ memnew_placement(&stack[i], Variant);
+ }
+ } else {
+ stack = nullptr;
+ }
+
+ if (_instruction_args_size) {
+ instruction_args = (Variant **)&aptr[sizeof(Variant) * _stack_size];
+ } else {
+ instruction_args = nullptr;
+ }
+
+ } else {
+ stack = nullptr;
+ instruction_args = nullptr;
+ }
+
+ if (p_instance) {
+ self = p_instance->owner;
+ script = p_instance->script.ptr();
+ } else {
+ script = _script;
+ }
+ }
+ if (_ptrcall_args_size) {
+ call_args_ptr = (const void **)alloca(_ptrcall_args_size * sizeof(void *));
+ } else {
+ call_args_ptr = nullptr;
+ }
+
+ static_ref = script;
+
+ String err_text;
+
+#ifdef DEBUG_ENABLED
+
+ if (EngineDebugger::is_active()) {
+ GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line);
+ }
+
+#define GD_ERR_BREAK(m_cond) \
+ { \
+ if (unlikely(m_cond)) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \
+ OPCODE_BREAK; \
+ } \
+ }
+
+#define CHECK_SPACE(m_space) \
+ GD_ERR_BREAK((ip + m_space) > _code_size)
+
+#define GET_VARIANT_PTR(m_v, m_code_ofs) \
+ Variant *m_v; \
+ m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text); \
+ if (unlikely(!m_v)) \
+ OPCODE_BREAK;
+
+#else
+#define GD_ERR_BREAK(m_cond)
+#define CHECK_SPACE(m_space)
+#define GET_VARIANT_PTR(m_v, m_code_ofs) \
+ Variant *m_v; \
+ m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, script, self, static_ref, stack, err_text);
+
+#endif
+
+#define GET_INSTRUCTION_ARG(m_v, m_idx) \
+ Variant *m_v = instruction_args[m_idx]
+
+#ifdef DEBUG_ENABLED
+
+ uint64_t function_start_time = 0;
+ uint64_t function_call_time = 0;
+
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_start_time = OS::get_singleton()->get_ticks_usec();
+ function_call_time = 0;
+ profile.call_count++;
+ profile.frame_call_count++;
+ }
+ bool exit_ok = false;
+ bool awaited = false;
+#endif
+
+#ifdef DEBUG_ENABLED
+ OPCODE_WHILE(ip < _code_size) {
+ int last_opcode = _code_ptr[ip];
+#else
+ OPCODE_WHILE(true) {
+#endif
+ // Load arguments for the instruction before each instruction.
+ int instr_arg_count = ((_code_ptr[ip]) & INSTR_ARGS_MASK) >> INSTR_BITS;
+ for (int i = 0; i < instr_arg_count; i++) {
+ GET_VARIANT_PTR(v, i + 1);
+ instruction_args[i] = v;
+ }
+
+ OPCODE_SWITCH(_code_ptr[ip] & INSTR_MASK) {
+ OPCODE(OPCODE_OPERATOR) {
+ CHECK_SPACE(5);
+
+ bool valid;
+ Variant::Operator op = (Variant::Operator)_code_ptr[ip + 4];
+ GD_ERR_BREAK(op >= Variant::OP_MAX);
+
+ GET_INSTRUCTION_ARG(a, 0);
+ GET_INSTRUCTION_ARG(b, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+#ifdef DEBUG_ENABLED
+
+ Variant ret;
+ Variant::evaluate(op, *a, *b, ret, valid);
+#else
+ Variant::evaluate(op, *a, *b, *dst, valid);
+#endif
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ if (ret.get_type() == Variant::STRING) {
+ //return a string when invalid with the error
+ err_text = ret;
+ err_text += " in operator '" + Variant::get_operator_name(op) + "'.";
+ } else {
+ err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'.";
+ }
+ OPCODE_BREAK;
+ }
+ *dst = ret;
+#endif
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_OPERATOR_VALIDATED) {
+ CHECK_SPACE(5);
+
+ int operator_idx = _code_ptr[ip + 4];
+ GD_ERR_BREAK(operator_idx < 0 || operator_idx >= _operator_funcs_count);
+ Variant::ValidatedOperatorEvaluator operator_func = _operator_funcs_ptr[operator_idx];
+
+ GET_INSTRUCTION_ARG(a, 0);
+ GET_INSTRUCTION_ARG(b, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+ operator_func(a, b, dst);
+
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_EXTENDS_TEST) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(a, 0);
+ GET_INSTRUCTION_ARG(b, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+#ifdef DEBUG_ENABLED
+ if (b->get_type() != Variant::OBJECT || b->operator Object *() == nullptr) {
+ err_text = "Right operand of 'is' is not a class.";
+ OPCODE_BREAK;
+ }
+#endif
+
+ bool extends_ok = false;
+ if (a->get_type() == Variant::OBJECT && a->operator Object *() != nullptr) {
+#ifdef DEBUG_ENABLED
+ bool was_freed;
+ Object *obj_A = a->get_validated_object_with_check(was_freed);
+
+ if (was_freed) {
+ err_text = "Left operand of 'is' is a previously freed instance.";
+ OPCODE_BREAK;
+ }
+
+ Object *obj_B = b->get_validated_object_with_check(was_freed);
+
+ if (was_freed) {
+ err_text = "Right operand of 'is' is a previously freed instance.";
+ OPCODE_BREAK;
+ }
+#else
+
+ Object *obj_A = *a;
+ Object *obj_B = *b;
+#endif // DEBUG_ENABLED
+
+ GDScript *scr_B = Object::cast_to<GDScript>(obj_B);
+
+ if (scr_B) {
+ //if B is a script, the only valid condition is that A has an instance which inherits from the script
+ //in other situation, this shoul return false.
+
+ if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) {
+ GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr());
+ //bool found=false;
+ while (cmp) {
+ if (cmp == scr_B) {
+ //inherits from script, all ok
+ extends_ok = true;
+ break;
+ }
+
+ cmp = cmp->_base;
+ }
+ }
+
+ } else {
+ GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(obj_B);
+
+#ifdef DEBUG_ENABLED
+ if (!nc) {
+ err_text = "Right operand of 'is' is not a class (type: '" + obj_B->get_class() + "').";
+ OPCODE_BREAK;
+ }
+#endif
+ extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name());
+ }
+ }
+
+ *dst = extends_ok;
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_IS_BUILTIN) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(value, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+ Variant::Type var_type = (Variant::Type)_code_ptr[ip + 3];
+
+ GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX);
+
+ *dst = value->get_type() == var_type;
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_KEYED) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(index, 1);
+ GET_INSTRUCTION_ARG(value, 2);
+
+ bool valid;
+ dst->set(*index, *value, &valid);
+
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ String v = index->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(index) + "'";
+ }
+ err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_KEYED_VALIDATED) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(index, 1);
+ GET_INSTRUCTION_ARG(value, 2);
+
+ int index_setter = _code_ptr[ip + 4];
+ GD_ERR_BREAK(index_setter < 0 || index_setter >= _keyed_setters_count);
+ const Variant::ValidatedKeyedSetter setter = _keyed_setters_ptr[index_setter];
+
+ bool valid;
+ setter(dst, index, value, &valid);
+
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ String v = index->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(index) + "'";
+ }
+ err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_INDEXED_VALIDATED) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(index, 1);
+ GET_INSTRUCTION_ARG(value, 2);
+
+ int index_setter = _code_ptr[ip + 4];
+ GD_ERR_BREAK(index_setter < 0 || index_setter >= _indexed_setters_count);
+ const Variant::ValidatedIndexedSetter setter = _indexed_setters_ptr[index_setter];
+
+ int64_t int_index = *VariantInternal::get_int(index);
+
+ bool oob;
+ setter(dst, int_index, value, &oob);
+
+#ifdef DEBUG_ENABLED
+ if (oob) {
+ String v = index->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(index) + "'";
+ }
+ err_text = "Out of bounds set index " + v + " (on base: '" + _get_var_type(dst) + "')";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_KEYED) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(index, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+ bool valid;
+#ifdef DEBUG_ENABLED
+ // Allow better error message in cases where src and dst are the same stack position.
+ Variant ret = src->get(*index, &valid);
+#else
+ *dst = src->get(*index, &valid);
+
+#endif
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ String v = index->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(index) + "'";
+ }
+ err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "').";
+ OPCODE_BREAK;
+ }
+ *dst = ret;
+#endif
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_KEYED_VALIDATED) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(key, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+ int index_getter = _code_ptr[ip + 4];
+ GD_ERR_BREAK(index_getter < 0 || index_getter >= _keyed_getters_count);
+ const Variant::ValidatedKeyedGetter getter = _keyed_getters_ptr[index_getter];
+
+ bool valid;
+#ifdef DEBUG_ENABLED
+ // Allow better error message in cases where src and dst are the same stack position.
+ Variant ret;
+ getter(src, key, &ret, &valid);
+#else
+ getter(src, key, dst, &valid);
+#endif
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ String v = key->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(key) + "'";
+ }
+ err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "').";
+ OPCODE_BREAK;
+ }
+ *dst = ret;
+#endif
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_INDEXED_VALIDATED) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(index, 1);
+ GET_INSTRUCTION_ARG(dst, 2);
+
+ int index_getter = _code_ptr[ip + 4];
+ GD_ERR_BREAK(index_getter < 0 || index_getter >= _indexed_getters_count);
+ const Variant::ValidatedIndexedGetter getter = _indexed_getters_ptr[index_getter];
+
+ int64_t int_index = *VariantInternal::get_int(index);
+
+ bool oob;
+ getter(src, int_index, dst, &oob);
+
+#ifdef DEBUG_ENABLED
+ if (oob) {
+ String v = index->operator String();
+ if (v != "") {
+ v = "'" + v + "'";
+ } else {
+ v = "of type '" + _get_var_type(index) + "'";
+ }
+ err_text = "Out of bounds get index " + v + " (on base: '" + _get_var_type(src) + "')";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 5;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_NAMED) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(value, 1);
+
+ int indexname = _code_ptr[ip + 3];
+
+ GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
+ const StringName *index = &_global_names_ptr[indexname];
+
+ bool valid;
+ dst->set_named(*index, *value, valid);
+
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ String err_type;
+ err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "') with value of type '" + _get_var_type(value) + "'.";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_NAMED_VALIDATED) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(value, 1);
+
+ int index_setter = _code_ptr[ip + 3];
+ GD_ERR_BREAK(index_setter < 0 || index_setter >= _setters_count);
+ const Variant::ValidatedSetter setter = _setters_ptr[index_setter];
+
+ setter(dst, value);
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_NAMED) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+
+ int indexname = _code_ptr[ip + 3];
+
+ GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
+ const StringName *index = &_global_names_ptr[indexname];
+
+ bool valid;
+#ifdef DEBUG_ENABLED
+ //allow better error message in cases where src and dst are the same stack position
+ Variant ret = src->get_named(*index, valid);
+
+#else
+ *dst = src->get_named(*index, valid);
+#endif
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ if (src->has_method(*index)) {
+ err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' or funcref(obj, \"" + index->operator String() + "\") ?";
+ } else {
+ err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "').";
+ }
+ OPCODE_BREAK;
+ }
+ *dst = ret;
+#endif
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_NAMED_VALIDATED) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+
+ int index_getter = _code_ptr[ip + 3];
+ GD_ERR_BREAK(index_getter < 0 || index_getter >= _getters_count);
+ const Variant::ValidatedGetter getter = _getters_ptr[index_getter];
+
+ getter(src, dst);
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_SET_MEMBER) {
+ CHECK_SPACE(3);
+ GET_INSTRUCTION_ARG(src, 0);
+ int indexname = _code_ptr[ip + 2];
+ GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
+ const StringName *index = &_global_names_ptr[indexname];
+
+ bool valid;
+#ifndef DEBUG_ENABLED
+ ClassDB::set_property(p_instance->owner, *index, *src, &valid);
+#else
+ bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid);
+ if (!ok) {
+ err_text = "Internal error setting property: " + String(*index);
+ OPCODE_BREAK;
+ } else if (!valid) {
+ err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + ".";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_GET_MEMBER) {
+ CHECK_SPACE(3);
+ GET_INSTRUCTION_ARG(dst, 0);
+ int indexname = _code_ptr[ip + 2];
+ GD_ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
+ const StringName *index = &_global_names_ptr[indexname];
+#ifndef DEBUG_ENABLED
+ ClassDB::get_property(p_instance->owner, *index, *dst);
+#else
+ bool ok = ClassDB::get_property(p_instance->owner, *index, *dst);
+ if (!ok) {
+ err_text = "Internal error getting property: " + String(*index);
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN) {
+ CHECK_SPACE(3);
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(src, 1);
+
+ *dst = *src;
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN_TRUE) {
+ CHECK_SPACE(2);
+ GET_INSTRUCTION_ARG(dst, 0);
+
+ *dst = true;
+
+ ip += 2;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN_FALSE) {
+ CHECK_SPACE(2);
+ GET_INSTRUCTION_ARG(dst, 0);
+
+ *dst = false;
+
+ ip += 2;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN_TYPED_BUILTIN) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(src, 1);
+
+ Variant::Type var_type = (Variant::Type)_code_ptr[ip + 3];
+ GD_ERR_BREAK(var_type < 0 || var_type >= Variant::VARIANT_MAX);
+
+ if (src->get_type() != var_type) {
+#ifdef DEBUG_ENABLED
+ if (Variant::can_convert_strict(src->get_type(), var_type)) {
+#endif // DEBUG_ENABLED
+ Callable::CallError ce;
+ Variant::construct(var_type, *dst, const_cast<const Variant **>(&src), 1, ce);
+ } else {
+#ifdef DEBUG_ENABLED
+ err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) +
+ "' to a variable of type '" + Variant::get_type_name(var_type) + "'.";
+ OPCODE_BREAK;
+ }
+ } else {
+#endif // DEBUG_ENABLED
+ *dst = *src;
+ }
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN_TYPED_NATIVE) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(src, 1);
+
+#ifdef DEBUG_ENABLED
+ GET_INSTRUCTION_ARG(type, 2);
+ GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(type->operator Object *());
+ GD_ERR_BREAK(!nc);
+ if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
+ err_text = "Trying to assign value of type '" + Variant::get_type_name(src->get_type()) +
+ "' to a variable of type '" + nc->get_name() + "'.";
+ OPCODE_BREAK;
+ }
+ Object *src_obj = src->operator Object *();
+
+ if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) {
+ err_text = "Trying to assign value of type '" + src_obj->get_class_name() +
+ "' to a variable of type '" + nc->get_name() + "'.";
+ OPCODE_BREAK;
+ }
+#endif // DEBUG_ENABLED
+ *dst = *src;
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSIGN_TYPED_SCRIPT) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(dst, 0);
+ GET_INSTRUCTION_ARG(src, 1);
+
+#ifdef DEBUG_ENABLED
+ GET_INSTRUCTION_ARG(type, 2);
+ Script *base_type = Object::cast_to<Script>(type->operator Object *());
+
+ GD_ERR_BREAK(!base_type);
+
+ if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
+ err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'.";
+ OPCODE_BREAK;
+ }
+
+ if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) {
+ ScriptInstance *scr_inst = src->operator Object *()->get_script_instance();
+ if (!scr_inst) {
+ err_text = "Trying to assign value of type '" + src->operator Object *()->get_class_name() +
+ "' to a variable of type '" + base_type->get_path().get_file() + "'.";
+ OPCODE_BREAK;
+ }
+
+ Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr();
+ bool valid = false;
+
+ while (src_type) {
+ if (src_type == base_type) {
+ valid = true;
+ break;
+ }
+ src_type = src_type->get_base_script().ptr();
+ }
+
+ if (!valid) {
+ err_text = "Trying to assign value of type '" + src->operator Object *()->get_script_instance()->get_script()->get_path().get_file() +
+ "' to a variable of type '" + base_type->get_path().get_file() + "'.";
+ OPCODE_BREAK;
+ }
+ }
+#endif // DEBUG_ENABLED
+
+ *dst = *src;
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CAST_TO_BUILTIN) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+ Variant::Type to_type = (Variant::Type)_code_ptr[ip + 3];
+
+ GD_ERR_BREAK(to_type < 0 || to_type >= Variant::VARIANT_MAX);
+
+ Callable::CallError err;
+ Variant::construct(to_type, *dst, (const Variant **)&src, 1, err);
+
+#ifdef DEBUG_ENABLED
+ if (err.error != Callable::CallError::CALL_OK) {
+ err_text = "Invalid cast: could not convert value to '" + Variant::get_type_name(to_type) + "'.";
+ OPCODE_BREAK;
+ }
+#endif
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CAST_TO_NATIVE) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+ GET_INSTRUCTION_ARG(to_type, 2);
+
+ GDScriptNativeClass *nc = Object::cast_to<GDScriptNativeClass>(to_type->operator Object *());
+ GD_ERR_BREAK(!nc);
+
+#ifdef DEBUG_ENABLED
+ if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
+ err_text = "Invalid cast: can't convert a non-object value to an object type.";
+ OPCODE_BREAK;
+ }
+#endif
+ Object *src_obj = src->operator Object *();
+
+ if (src_obj && !ClassDB::is_parent_class(src_obj->get_class_name(), nc->get_name())) {
+ *dst = Variant(); // invalid cast, assign NULL
+ } else {
+ *dst = *src;
+ }
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CAST_TO_SCRIPT) {
+ CHECK_SPACE(4);
+ GET_INSTRUCTION_ARG(src, 0);
+ GET_INSTRUCTION_ARG(dst, 1);
+ GET_INSTRUCTION_ARG(to_type, 2);
+
+ Script *base_type = Object::cast_to<Script>(to_type->operator Object *());
+
+ GD_ERR_BREAK(!base_type);
+
+#ifdef DEBUG_ENABLED
+ if (src->get_type() != Variant::OBJECT && src->get_type() != Variant::NIL) {
+ err_text = "Trying to assign a non-object value to a variable of type '" + base_type->get_path().get_file() + "'.";
+ OPCODE_BREAK;
+ }
+#endif
+
+ bool valid = false;
+
+ if (src->get_type() != Variant::NIL && src->operator Object *() != nullptr) {
+ ScriptInstance *scr_inst = src->operator Object *()->get_script_instance();
+
+ if (scr_inst) {
+ Script *src_type = src->operator Object *()->get_script_instance()->get_script().ptr();
+
+ while (src_type) {
+ if (src_type == base_type) {
+ valid = true;
+ break;
+ }
+ src_type = src_type->get_base_script().ptr();
+ }
+ }
+ }
+
+ if (valid) {
+ *dst = *src; // Valid cast, copy the source object
+ } else {
+ *dst = Variant(); // invalid cast, assign NULL
+ }
+
+ ip += 4;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CONSTRUCT) {
+ CHECK_SPACE(2 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+
+ Variant::Type t = Variant::Type(_code_ptr[ip + 2]);
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ Callable::CallError err;
+ Variant::construct(t, *dst, (const Variant **)argptrs, argc, err);
+
+#ifdef DEBUG_ENABLED
+ if (err.error != Callable::CallError::CALL_OK) {
+ err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs);
+ OPCODE_BREAK;
+ }
+#endif
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CONSTRUCT_VALIDATED) {
+ CHECK_SPACE(2 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+
+ int constructor_idx = _code_ptr[ip + 2];
+ GD_ERR_BREAK(constructor_idx < 0 || constructor_idx >= _constructors_count);
+ Variant::ValidatedConstructor constructor = _constructors_ptr[constructor_idx];
+
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ constructor(dst, (const Variant **)argptrs);
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CONSTRUCT_ARRAY) {
+ CHECK_SPACE(1 + instr_arg_count);
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ Array array;
+ array.resize(argc);
+
+ for (int i = 0; i < argc; i++) {
+ array[i] = *(instruction_args[i]);
+ }
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ *dst = array;
+
+ ip += 2;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CONSTRUCT_DICTIONARY) {
+ CHECK_SPACE(2 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ Dictionary dict;
+
+ for (int i = 0; i < argc; i++) {
+ GET_INSTRUCTION_ARG(k, i * 2 + 0);
+ GET_INSTRUCTION_ARG(v, i * 2 + 1);
+ dict[*k] = *v;
+ }
+
+ GET_INSTRUCTION_ARG(dst, argc * 2);
+
+ *dst = dict;
+
+ ip += 2;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_ASYNC)
+ OPCODE(OPCODE_CALL_RETURN)
+ OPCODE(OPCODE_CALL) {
+ CHECK_SPACE(3 + instr_arg_count);
+ bool call_ret = (_code_ptr[ip] & INSTR_MASK) != OPCODE_CALL;
+#ifdef DEBUG_ENABLED
+ bool call_async = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_ASYNC;
+#endif
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ int methodname_idx = _code_ptr[ip + 2];
+ GD_ERR_BREAK(methodname_idx < 0 || methodname_idx >= _global_names_count);
+ const StringName *methodname = &_global_names_ptr[methodname_idx];
+
+ GET_INSTRUCTION_ARG(base, argc);
+ Variant **argptrs = instruction_args;
+
+#ifdef DEBUG_ENABLED
+ uint64_t call_time = 0;
+
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ call_time = OS::get_singleton()->get_ticks_usec();
+ }
+
+#endif
+ Callable::CallError err;
+ if (call_ret) {
+ GET_INSTRUCTION_ARG(ret, argc + 1);
+ base->call(*methodname, (const Variant **)argptrs, argc, *ret, err);
+#ifdef DEBUG_ENABLED
+ if (!call_async && ret->get_type() == Variant::OBJECT) {
+ // Check if getting a function state without await.
+ bool was_freed = false;
+ Object *obj = ret->get_validated_object_with_check(was_freed);
+
+ if (was_freed) {
+ err_text = "Got a freed object as a result of the call.";
+ OPCODE_BREAK;
+ }
+ if (obj && obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) {
+ err_text = R"(Trying to call an async function without "await".)";
+ OPCODE_BREAK;
+ }
+ }
+#endif
+ } else {
+ Variant ret;
+ base->call(*methodname, (const Variant **)argptrs, argc, ret, err);
+ }
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
+ }
+
+ if (err.error != Callable::CallError::CALL_OK) {
+ String methodstr = *methodname;
+ String basestr = _get_var_type(base);
+
+ if (methodstr == "call") {
+ if (argc >= 1) {
+ methodstr = String(*argptrs[0]) + " (via call)";
+ if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ err.argument += 1;
+ }
+ }
+ } else if (methodstr == "free") {
+ if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
+ if (base->is_ref()) {
+ err_text = "Attempted to free a reference.";
+ OPCODE_BREAK;
+ } else if (base->get_type() == Variant::OBJECT) {
+ err_text = "Attempted to free a locked object (calling or emitting).";
+ OPCODE_BREAK;
+ }
+ }
+ } else if (methodstr == "call_recursive" && basestr == "TreeItem") {
+ if (argc >= 1) {
+ methodstr = String(*argptrs[0]) + " (via TreeItem.call_recursive)";
+ if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ err.argument += 1;
+ }
+ }
+ }
+ err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs);
+ OPCODE_BREAK;
+ }
+#endif
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_METHOD_BIND)
+ OPCODE(OPCODE_CALL_METHOD_BIND_RET) {
+ CHECK_SPACE(3 + instr_arg_count);
+ bool call_ret = (_code_ptr[ip] & INSTR_MASK) == OPCODE_CALL_METHOD_BIND_RET;
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count);
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2]];
+
+ GET_INSTRUCTION_ARG(base, argc);
+
+#ifdef DEBUG_ENABLED
+ bool freed = false;
+ Object *base_obj = base->get_validated_object_with_check(freed);
+ if (freed) {
+ err_text = "Trying to call a function on a previously freed instance.";
+ OPCODE_BREAK;
+ } else if (!base_obj) {
+ err_text = "Trying to call a function on a null value.";
+ OPCODE_BREAK;
+ }
+#else
+ Object *base_obj = base->operator Object *();
+#endif
+ Variant **argptrs = instruction_args;
+
+#ifdef DEBUG_ENABLED
+ uint64_t call_time = 0;
+
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ call_time = OS::get_singleton()->get_ticks_usec();
+ }
+#endif
+
+ Callable::CallError err;
+ if (call_ret) {
+ GET_INSTRUCTION_ARG(ret, argc + 1);
+ *ret = method->call(base_obj, (const Variant **)argptrs, argc, err);
+ } else {
+ method->call(base_obj, (const Variant **)argptrs, argc, err);
+ }
+
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
+ }
+
+ if (err.error != Callable::CallError::CALL_OK) {
+ String methodstr = method->get_name();
+ String basestr = _get_var_type(base);
+
+ if (methodstr == "call") {
+ if (argc >= 1) {
+ methodstr = String(*argptrs[0]) + " (via call)";
+ if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ err.argument += 1;
+ }
+ }
+ } else if (methodstr == "free") {
+ if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) {
+ if (base->is_ref()) {
+ err_text = "Attempted to free a reference.";
+ OPCODE_BREAK;
+ } else if (base->get_type() == Variant::OBJECT) {
+ err_text = "Attempted to free a locked object (calling or emitting).";
+ OPCODE_BREAK;
+ }
+ }
+ }
+ err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs);
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+#ifdef DEBUG_ENABLED
+#define OPCODE_CALL_PTR(m_type) \
+ OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \
+ CHECK_SPACE(3 + instr_arg_count); \
+ ip += instr_arg_count; \
+ int argc = _code_ptr[ip + 1]; \
+ GD_ERR_BREAK(argc < 0); \
+ GET_INSTRUCTION_ARG(base, argc); \
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count); \
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; \
+ bool freed = false; \
+ Object *base_obj = base->get_validated_object_with_check(freed); \
+ if (freed) { \
+ err_text = "Trying to call a function on a previously freed instance."; \
+ OPCODE_BREAK; \
+ } else if (!base_obj) { \
+ err_text = "Trying to call a function on a null value."; \
+ OPCODE_BREAK; \
+ } \
+ const void **argptrs = call_args_ptr; \
+ for (int i = 0; i < argc; i++) { \
+ GET_INSTRUCTION_ARG(v, i); \
+ argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); \
+ } \
+ uint64_t call_time = 0; \
+ if (GDScriptLanguage::get_singleton()->profiling) { \
+ call_time = OS::get_singleton()->get_ticks_usec(); \
+ } \
+ GET_INSTRUCTION_ARG(ret, argc + 1); \
+ VariantInternal::initialize(ret, Variant::m_type); \
+ void *ret_opaque = VariantInternal::OP_GET_##m_type(ret); \
+ method->ptrcall(base_obj, argptrs, ret_opaque); \
+ if (GDScriptLanguage::get_singleton()->profiling) { \
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; \
+ } \
+ ip += 3; \
+ } \
+ DISPATCH_OPCODE
+#else
+#define OPCODE_CALL_PTR(m_type) \
+ OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \
+ CHECK_SPACE(3 + instr_arg_count); \
+ int argc = _code_ptr[ip + 1]; \
+ GET_INSTRUCTION_ARG(base, argc); \
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2]]; \
+ Object *base_obj = *VariantInternal::get_object(base); \
+ const void **argptrs = call_args_ptr; \
+ for (int i = 0; i < argc; i++) { \
+ GET_INSTRUCTION_ARG(v, i); \
+ argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v); \
+ } \
+ GET_INSTRUCTION_ARG(ret, argc + 1); \
+ VariantInternal::initialize(ret, Variant::m_type); \
+ void *ret_opaque = VariantInternal::OP_GET_##m_type(ret); \
+ method->ptrcall(base_obj, argptrs, ret_opaque); \
+ ip += 3; \
+ } \
+ DISPATCH_OPCODE
+#endif
+
+ OPCODE_CALL_PTR(BOOL);
+ OPCODE_CALL_PTR(INT);
+ OPCODE_CALL_PTR(FLOAT);
+ OPCODE_CALL_PTR(STRING);
+ OPCODE_CALL_PTR(VECTOR2);
+ OPCODE_CALL_PTR(VECTOR2I);
+ OPCODE_CALL_PTR(RECT2);
+ OPCODE_CALL_PTR(RECT2I);
+ OPCODE_CALL_PTR(VECTOR3);
+ OPCODE_CALL_PTR(VECTOR3I);
+ OPCODE_CALL_PTR(TRANSFORM2D);
+ OPCODE_CALL_PTR(PLANE);
+ OPCODE_CALL_PTR(QUAT);
+ OPCODE_CALL_PTR(AABB);
+ OPCODE_CALL_PTR(BASIS);
+ OPCODE_CALL_PTR(TRANSFORM);
+ OPCODE_CALL_PTR(COLOR);
+ OPCODE_CALL_PTR(STRING_NAME);
+ OPCODE_CALL_PTR(NODE_PATH);
+ OPCODE_CALL_PTR(RID);
+ OPCODE_CALL_PTR(CALLABLE);
+ OPCODE_CALL_PTR(SIGNAL);
+ OPCODE_CALL_PTR(DICTIONARY);
+ OPCODE_CALL_PTR(ARRAY);
+ OPCODE_CALL_PTR(PACKED_BYTE_ARRAY);
+ OPCODE_CALL_PTR(PACKED_INT32_ARRAY);
+ OPCODE_CALL_PTR(PACKED_INT64_ARRAY);
+ OPCODE_CALL_PTR(PACKED_FLOAT32_ARRAY);
+ OPCODE_CALL_PTR(PACKED_FLOAT64_ARRAY);
+ OPCODE_CALL_PTR(PACKED_STRING_ARRAY);
+ OPCODE_CALL_PTR(PACKED_VECTOR2_ARRAY);
+ OPCODE_CALL_PTR(PACKED_VECTOR3_ARRAY);
+ OPCODE_CALL_PTR(PACKED_COLOR_ARRAY);
+ OPCODE(OPCODE_CALL_PTRCALL_OBJECT) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count);
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2]];
+
+ GET_INSTRUCTION_ARG(base, argc);
+#ifdef DEBUG_ENABLED
+ bool freed = false;
+ Object *base_obj = base->get_validated_object_with_check(freed);
+ if (freed) {
+ err_text = "Trying to call a function on a previously freed instance.";
+ OPCODE_BREAK;
+ } else if (!base_obj) {
+ err_text = "Trying to call a function on a null value.";
+ OPCODE_BREAK;
+ }
+#else
+ Object *base_obj = *VariantInternal::get_object(base);
+#endif
+
+ const void **argptrs = call_args_ptr;
+
+ for (int i = 0; i < argc; i++) {
+ GET_INSTRUCTION_ARG(v, i);
+ argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v);
+ }
+#ifdef DEBUG_ENABLED
+ uint64_t call_time = 0;
+
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ call_time = OS::get_singleton()->get_ticks_usec();
+ }
+#endif
+
+ GET_INSTRUCTION_ARG(ret, argc + 1);
+ VariantInternal::initialize(ret, Variant::OBJECT);
+ Object **ret_opaque = VariantInternal::get_object(ret);
+ method->ptrcall(base_obj, argptrs, ret_opaque);
+ VariantInternal::object_assign(ret, *ret_opaque); // Set so ID is correct too.
+
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+ OPCODE(OPCODE_CALL_PTRCALL_NO_RETURN) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _methods_count);
+ MethodBind *method = _methods_ptr[_code_ptr[ip + 2]];
+
+ GET_INSTRUCTION_ARG(base, argc);
+#ifdef DEBUG_ENABLED
+ bool freed = false;
+ Object *base_obj = base->get_validated_object_with_check(freed);
+ if (freed) {
+ err_text = "Trying to call a function on a previously freed instance.";
+ OPCODE_BREAK;
+ } else if (!base_obj) {
+ err_text = "Trying to call a function on a null value.";
+ OPCODE_BREAK;
+ }
+#else
+ Object *base_obj = *VariantInternal::get_object(base);
+#endif
+ const void **argptrs = call_args_ptr;
+
+ for (int i = 0; i < argc; i++) {
+ GET_INSTRUCTION_ARG(v, i);
+ argptrs[i] = VariantInternal::get_opaque_pointer((const Variant *)v);
+ }
+#ifdef DEBUG_ENABLED
+ uint64_t call_time = 0;
+
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ call_time = OS::get_singleton()->get_ticks_usec();
+ }
+#endif
+
+ GET_INSTRUCTION_ARG(ret, argc + 1);
+ VariantInternal::initialize(ret, Variant::NIL);
+ method->ptrcall(base_obj, argptrs, nullptr);
+
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_BUILTIN_TYPE_VALIDATED) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GET_INSTRUCTION_ARG(base, argc);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _builtin_methods_count);
+ Variant::ValidatedBuiltInMethod method = _builtin_methods_ptr[_code_ptr[ip + 2]];
+ Variant **argptrs = instruction_args;
+
+#ifdef DEBUG_ENABLED
+ uint64_t call_time = 0;
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ call_time = OS::get_singleton()->get_ticks_usec();
+ }
+#endif
+
+ GET_INSTRUCTION_ARG(ret, argc + 1);
+ method(base, (const Variant **)argptrs, argc, ret);
+
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
+ }
+#endif
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_UTILITY) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _global_names_count);
+ StringName function = _global_names_ptr[_code_ptr[ip + 2]];
+
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ Callable::CallError err;
+ Variant::call_utility_function(function, dst, (const Variant **)argptrs, argc, err);
+
+#ifdef DEBUG_ENABLED
+ if (err.error != Callable::CallError::CALL_OK) {
+ String methodstr = function;
+ if (dst->get_type() == Variant::STRING) {
+ // Call provided error string.
+ err_text = "Error calling utility function '" + methodstr + "': " + String(*dst);
+ } else {
+ err_text = _get_call_error(err, "utility function '" + methodstr + "'", (const Variant **)argptrs);
+ }
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_UTILITY_VALIDATED) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _utilities_count);
+ Variant::ValidatedUtilityFunction function = _utilities_ptr[_code_ptr[ip + 2]];
+
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ function(dst, (const Variant **)argptrs, argc);
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_GDSCRIPT_UTILITY) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int argc = _code_ptr[ip + 1];
+ GD_ERR_BREAK(argc < 0);
+
+ GD_ERR_BREAK(_code_ptr[ip + 2] < 0 || _code_ptr[ip + 2] >= _gds_utilities_count);
+ GDScriptUtilityFunctions::FunctionPtr function = _gds_utilities_ptr[_code_ptr[ip + 2]];
+
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ Callable::CallError err;
+ function(dst, (const Variant **)argptrs, argc, err);
+
+#ifdef DEBUG_ENABLED
+ if (err.error != Callable::CallError::CALL_OK) {
+ // TODO: Add this information in debug.
+ String methodstr = "<unkown function>";
+ if (dst->get_type() == Variant::STRING) {
+ // Call provided error string.
+ err_text = "Error calling GDScript utility function '" + methodstr + "': " + String(*dst);
+ } else {
+ err_text = _get_call_error(err, "GDScript utility function '" + methodstr + "'", (const Variant **)argptrs);
+ }
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_CALL_SELF_BASE) {
+ CHECK_SPACE(3 + instr_arg_count);
+
+ ip += instr_arg_count;
+
+ int self_fun = _code_ptr[ip + 1];
+#ifdef DEBUG_ENABLED
+ if (self_fun < 0 || self_fun >= _global_names_count) {
+ err_text = "compiler bug, function name not found";
+ OPCODE_BREAK;
+ }
+#endif
+ const StringName *methodname = &_global_names_ptr[self_fun];
+
+ int argc = _code_ptr[ip + 2];
+ GD_ERR_BREAK(argc < 0);
+
+ Variant **argptrs = instruction_args;
+
+ GET_INSTRUCTION_ARG(dst, argc);
+
+ const GDScript *gds = _script;
+
+ const Map<StringName, GDScriptFunction *>::Element *E = nullptr;
+ while (gds->base.ptr()) {
+ gds = gds->base.ptr();
+ E = gds->member_functions.find(*methodname);
+ if (E) {
+ break;
+ }
+ }
+
+ Callable::CallError err;
+
+ if (E) {
+ *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err);
+ } else if (gds->native.ptr()) {
+ if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
+ MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname);
+ if (!mb) {
+ err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ } else {
+ *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err);
+ }
+ } else {
+ err.error = Callable::CallError::CALL_OK;
+ }
+ } else {
+ if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
+ err.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
+ } else {
+ err.error = Callable::CallError::CALL_OK;
+ }
+ }
+
+ if (err.error != Callable::CallError::CALL_OK) {
+ String methodstr = *methodname;
+ err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs);
+
+ OPCODE_BREAK;
+ }
+
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_AWAIT) {
+ CHECK_SPACE(2);
+
+ // Do the oneshot connect.
+ GET_INSTRUCTION_ARG(argobj, 0);
+
+ Signal sig;
+ bool is_signal = true;
+
+ {
+ Variant result = *argobj;
+
+ if (argobj->get_type() == Variant::OBJECT) {
+ bool was_freed = false;
+ Object *obj = argobj->get_validated_object_with_check(was_freed);
+
+ if (was_freed) {
+ err_text = "Trying to await on a freed object.";
+ OPCODE_BREAK;
+ }
+
+ // Is this even possible to be null at this point?
+ if (obj) {
+ if (obj->is_class_ptr(GDScriptFunctionState::get_class_ptr_static())) {
+ static StringName completed = _scs_create("completed");
+ result = Signal(obj, completed);
+ }
+ }
+ }
+
+ if (result.get_type() != Variant::SIGNAL) {
+ ip += 4; // Skip OPCODE_AWAIT_RESUME and its data.
+ // The stack pointer should be the same, so we don't need to set a return value.
+ is_signal = false;
+ } else {
+ sig = result;
+ }
+ }
+
+ if (is_signal) {
+ Ref<GDScriptFunctionState> gdfs = memnew(GDScriptFunctionState);
+ gdfs->function = this;
+
+ gdfs->state.stack.resize(alloca_size);
+ //copy variant stack
+ for (int i = 0; i < _stack_size; i++) {
+ memnew_placement(&gdfs->state.stack.write[sizeof(Variant) * i], Variant(stack[i]));
+ }
+ gdfs->state.stack_size = _stack_size;
+ gdfs->state.self = self;
+ gdfs->state.alloca_size = alloca_size;
+ gdfs->state.ip = ip + 2;
+ gdfs->state.line = line;
+ gdfs->state.script = _script;
+ {
+ MutexLock lock(GDScriptLanguage::get_singleton()->lock);
+ _script->pending_func_states.add(&gdfs->scripts_list);
+ if (p_instance) {
+ gdfs->state.instance = p_instance;
+ p_instance->pending_func_states.add(&gdfs->instances_list);
+ } else {
+ gdfs->state.instance = nullptr;
+ }
+ }
+#ifdef DEBUG_ENABLED
+ gdfs->state.function_name = name;
+ gdfs->state.script_path = _script->get_path();
+#endif
+ gdfs->state.defarg = defarg;
+ gdfs->function = this;
+
+ retvalue = gdfs;
+
+ Error err = sig.connect(Callable(gdfs.ptr(), "_signal_callback"), varray(gdfs), Object::CONNECT_ONESHOT);
+ if (err != OK) {
+ err_text = "Error connecting to signal: " + sig.get_name() + " during await.";
+ OPCODE_BREAK;
+ }
+
+#ifdef DEBUG_ENABLED
+ exit_ok = true;
+ awaited = true;
+#endif
+ OPCODE_BREAK;
+ }
+ }
+ DISPATCH_OPCODE; // Needed for synchronous calls (when result is immediately available).
+
+ OPCODE(OPCODE_AWAIT_RESUME) {
+ CHECK_SPACE(2);
+#ifdef DEBUG_ENABLED
+ if (!p_state) {
+ err_text = ("Invalid Resume (bug?)");
+ OPCODE_BREAK;
+ }
+#endif
+ GET_INSTRUCTION_ARG(result, 0);
+ *result = p_state->result;
+ ip += 2;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_JUMP) {
+ CHECK_SPACE(2);
+ int to = _code_ptr[ip + 1];
+
+ GD_ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_JUMP_IF) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(test, 0);
+
+ bool result = test->booleanize();
+
+ if (result) {
+ int to = _code_ptr[ip + 2];
+ GD_ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
+ } else {
+ ip += 3;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_JUMP_IF_NOT) {
+ CHECK_SPACE(3);
+
+ GET_INSTRUCTION_ARG(test, 0);
+
+ bool result = test->booleanize();
+
+ if (!result) {
+ int to = _code_ptr[ip + 2];
+ GD_ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
+ } else {
+ ip += 3;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_JUMP_TO_DEF_ARGUMENT) {
+ CHECK_SPACE(2);
+ ip = _default_arg_ptr[defarg];
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_RETURN) {
+ CHECK_SPACE(2);
+ GET_INSTRUCTION_ARG(r, 0);
+ retvalue = *r;
+#ifdef DEBUG_ENABLED
+ exit_ok = true;
+#endif
+ OPCODE_BREAK;
+ }
+
+ OPCODE(OPCODE_ITERATE_BEGIN) {
+ CHECK_SPACE(8); // Space for this and a regular iterate.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ bool valid;
+ if (!container->iter_init(*counter, valid)) {
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "'.";
+ OPCODE_BREAK;
+ }
+#endif
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+
+ *iterator = container->iter_get(*counter, valid);
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "'.";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 5; // Skip regular iterate which is always next.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_INT) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ int64_t size = *VariantInternal::get_int(container);
+
+ VariantInternal::initialize(counter, Variant::INT);
+ *VariantInternal::get_int(counter) = 0;
+
+ if (size > 0) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::INT);
+ *VariantInternal::get_int(iterator) = 0;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_FLOAT) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ double size = *VariantInternal::get_float(container);
+
+ VariantInternal::initialize(counter, Variant::FLOAT);
+ *VariantInternal::get_float(counter) = 0.0;
+
+ if (size > 0) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::FLOAT);
+ *VariantInternal::get_float(iterator) = 0;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_VECTOR2) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Vector2 *bounds = VariantInternal::get_vector2(container);
+
+ VariantInternal::initialize(counter, Variant::FLOAT);
+ *VariantInternal::get_float(counter) = bounds->x;
+
+ if (bounds->x < bounds->y) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::FLOAT);
+ *VariantInternal::get_float(iterator) = bounds->x;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_VECTOR2I) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Vector2i *bounds = VariantInternal::get_vector2i(container);
+
+ VariantInternal::initialize(counter, Variant::FLOAT);
+ *VariantInternal::get_int(counter) = bounds->x;
+
+ if (bounds->x < bounds->y) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::INT);
+ *VariantInternal::get_int(iterator) = bounds->x;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_VECTOR3) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Vector3 *bounds = VariantInternal::get_vector3(container);
+ double from = bounds->x;
+ double to = bounds->y;
+ double step = bounds->z;
+
+ VariantInternal::initialize(counter, Variant::FLOAT);
+ *VariantInternal::get_float(counter) = from;
+
+ bool do_continue = from == to ? false : (from < to ? step > 0 : step < 0);
+
+ if (do_continue) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::FLOAT);
+ *VariantInternal::get_float(iterator) = from;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_VECTOR3I) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Vector3i *bounds = VariantInternal::get_vector3i(container);
+ int64_t from = bounds->x;
+ int64_t to = bounds->y;
+ int64_t step = bounds->z;
+
+ VariantInternal::initialize(counter, Variant::INT);
+ *VariantInternal::get_int(counter) = from;
+
+ bool do_continue = from == to ? false : (from < to ? step > 0 : step < 0);
+
+ if (do_continue) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::INT);
+ *VariantInternal::get_int(iterator) = from;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_STRING) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ String *str = VariantInternal::get_string(container);
+
+ VariantInternal::initialize(counter, Variant::INT);
+ *VariantInternal::get_int(counter) = 0;
+
+ if (!str->is_empty()) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ VariantInternal::initialize(iterator, Variant::STRING);
+ *VariantInternal::get_string(iterator) = str->substr(0, 1);
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_DICTIONARY) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Dictionary *dict = VariantInternal::get_dictionary(container);
+ const Variant *next = dict->next(nullptr);
+
+ if (!dict->is_empty()) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *counter = *next;
+ *iterator = *next;
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_BEGIN_ARRAY) {
+ CHECK_SPACE(8); // Check space for iterate instruction too.
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ Array *array = VariantInternal::get_array(container);
+
+ VariantInternal::initialize(counter, Variant::INT);
+ *VariantInternal::get_int(counter) = 0;
+
+ if (!array->is_empty()) {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *iterator = array->get(0);
+
+ // Skip regular iterate.
+ ip += 5;
+ } else {
+ // Jump to end of loop.
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ }
+ }
+ DISPATCH_OPCODE;
+
+#define OPCODE_ITERATE_BEGIN_PACKED_ARRAY(m_var_type, m_elem_type, m_get_func, m_var_ret_type, m_ret_type, m_ret_get_func) \
+ OPCODE(OPCODE_ITERATE_BEGIN_PACKED_##m_var_type##_ARRAY) { \
+ CHECK_SPACE(8); \
+ GET_INSTRUCTION_ARG(counter, 0); \
+ GET_INSTRUCTION_ARG(container, 1); \
+ Vector<m_elem_type> *array = VariantInternal::m_get_func(container); \
+ VariantInternal::initialize(counter, Variant::INT); \
+ *VariantInternal::get_int(counter) = 0; \
+ if (!array->is_empty()) { \
+ GET_INSTRUCTION_ARG(iterator, 2); \
+ VariantInternal::initialize(iterator, Variant::m_var_ret_type); \
+ m_ret_type *it = VariantInternal::m_ret_get_func(iterator); \
+ *it = array->get(0); \
+ ip += 5; \
+ } else { \
+ int jumpto = _code_ptr[ip + 4]; \
+ GD_ERR_BREAK(jumpto<0 || jumpto> _code_size); \
+ ip = jumpto; \
+ } \
+ } \
+ DISPATCH_OPCODE
+
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(BYTE, uint8_t, get_byte_array, INT, int64_t, get_int);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(INT32, int32_t, get_int32_array, INT, int64_t, get_int);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(INT64, int64_t, get_int64_array, INT, int64_t, get_int);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(FLOAT32, float, get_float32_array, FLOAT, double, get_float);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(FLOAT64, double, get_float64_array, FLOAT, double, get_float);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(STRING, String, get_string_array, STRING, String, get_string);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(VECTOR2, Vector2, get_vector2_array, VECTOR2, Vector2, get_vector2);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(VECTOR3, Vector3, get_vector3_array, VECTOR3, Vector3, get_vector3);
+ OPCODE_ITERATE_BEGIN_PACKED_ARRAY(COLOR, Color, get_color_array, COLOR, Color, get_color);
+
+ OPCODE(OPCODE_ITERATE_BEGIN_OBJECT) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+#ifdef DEBUG_ENABLED
+ bool freed = false;
+ Object *obj = container->get_validated_object_with_check(freed);
+ if (freed) {
+ err_text = "Trying to iterate on a previously freed object.";
+ OPCODE_BREAK;
+ } else if (!obj) {
+ err_text = "Trying to iterate on a null value.";
+ OPCODE_BREAK;
+ }
+#else
+ Object *obj = *VariantInternal::get_object(container);
+#endif
+ Array ref;
+ ref.push_back(*counter);
+ Variant vref;
+ VariantInternal::initialize(&vref, Variant::ARRAY);
+ *VariantInternal::get_array(&vref) = ref;
+
+ Variant **args = instruction_args; // Overriding an instruction argument, but we don't need access to that anymore.
+ args[0] = &vref;
+
+ Callable::CallError ce;
+ Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_init, (const Variant **)args, 1, ce);
+
+#ifdef DEBUG_ENABLED
+ if (ce.error != Callable::CallError::CALL_OK) {
+ err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container);
+ OPCODE_BREAK;
+ }
+#endif
+ if (!has_next.booleanize()) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce);
+#ifdef DEBUG_ENABLED
+ if (ce.error != Callable::CallError::CALL_OK) {
+ err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container);
+ OPCODE_BREAK;
+ }
+#endif
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ bool valid;
+ if (!container->iter_next(*counter, valid)) {
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ err_text = "Unable to iterate on object of type '" + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?).";
+ OPCODE_BREAK;
+ }
+#endif
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+
+ *iterator = container->iter_get(*counter, valid);
+#ifdef DEBUG_ENABLED
+ if (!valid) {
+ err_text = "Unable to obtain iterator object of type '" + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?).";
+ OPCODE_BREAK;
+ }
+#endif
+ ip += 5; //loop again
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_INT) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ int64_t size = *VariantInternal::get_int(container);
+ int64_t *count = VariantInternal::get_int(counter);
+
+ (*count)++;
+
+ if (*count >= size) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_int(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_FLOAT) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ double size = *VariantInternal::get_float(container);
+ double *count = VariantInternal::get_float(counter);
+
+ (*count)++;
+
+ if (*count >= size) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_float(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_VECTOR2) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Vector2 *bounds = VariantInternal::get_vector2((const Variant *)container);
+ double *count = VariantInternal::get_float(counter);
+
+ (*count)++;
+
+ if (*count >= bounds->y) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_float(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_VECTOR2I) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Vector2i *bounds = VariantInternal::get_vector2i((const Variant *)container);
+ int64_t *count = VariantInternal::get_int(counter);
+
+ (*count)++;
+
+ if (*count >= bounds->y) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_int(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_VECTOR3) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Vector3 *bounds = VariantInternal::get_vector3((const Variant *)container);
+ double *count = VariantInternal::get_float(counter);
+
+ *count += bounds->z;
+
+ if ((bounds->z < 0 && *count <= bounds->y) || (bounds->z > 0 && *count >= bounds->y)) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_float(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_VECTOR3I) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Vector3i *bounds = VariantInternal::get_vector3i((const Variant *)container);
+ int64_t *count = VariantInternal::get_int(counter);
+
+ *count += bounds->z;
+
+ if ((bounds->z < 0 && *count <= bounds->y) || (bounds->z > 0 && *count >= bounds->y)) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_int(iterator) = *count;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_STRING) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const String *str = VariantInternal::get_string((const Variant *)container);
+ int64_t *idx = VariantInternal::get_int(counter);
+ (*idx)++;
+
+ if (*idx >= str->length()) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *VariantInternal::get_string(iterator) = str->substr(*idx, 1);
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_DICTIONARY) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Dictionary *dict = VariantInternal::get_dictionary((const Variant *)container);
+ const Variant *next = dict->next(counter);
+
+ if (!next) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *counter = *next;
+ *iterator = *next;
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ITERATE_ARRAY) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+ const Array *array = VariantInternal::get_array((const Variant *)container);
+ int64_t *idx = VariantInternal::get_int(counter);
+ (*idx)++;
+
+ if (*idx >= array->size()) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *iterator = array->get(*idx);
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+#define OPCODE_ITERATE_PACKED_ARRAY(m_var_type, m_elem_type, m_get_func, m_ret_get_func) \
+ OPCODE(OPCODE_ITERATE_PACKED_##m_var_type##_ARRAY) { \
+ CHECK_SPACE(4); \
+ GET_INSTRUCTION_ARG(counter, 0); \
+ GET_INSTRUCTION_ARG(container, 1); \
+ const Vector<m_elem_type> *array = VariantInternal::m_get_func((const Variant *)container); \
+ int64_t *idx = VariantInternal::get_int(counter); \
+ (*idx)++; \
+ if (*idx >= array->size()) { \
+ int jumpto = _code_ptr[ip + 4]; \
+ GD_ERR_BREAK(jumpto<0 || jumpto> _code_size); \
+ ip = jumpto; \
+ } else { \
+ GET_INSTRUCTION_ARG(iterator, 2); \
+ *VariantInternal::m_ret_get_func(iterator) = array->get(*idx); \
+ ip += 5; \
+ } \
+ } \
+ DISPATCH_OPCODE
+
+ OPCODE_ITERATE_PACKED_ARRAY(BYTE, uint8_t, get_byte_array, get_int);
+ OPCODE_ITERATE_PACKED_ARRAY(INT32, int32_t, get_int32_array, get_int);
+ OPCODE_ITERATE_PACKED_ARRAY(INT64, int64_t, get_int64_array, get_int);
+ OPCODE_ITERATE_PACKED_ARRAY(FLOAT32, float, get_float32_array, get_float);
+ OPCODE_ITERATE_PACKED_ARRAY(FLOAT64, double, get_float64_array, get_float);
+ OPCODE_ITERATE_PACKED_ARRAY(STRING, String, get_string_array, get_string);
+ OPCODE_ITERATE_PACKED_ARRAY(VECTOR2, Vector2, get_vector2_array, get_vector2);
+ OPCODE_ITERATE_PACKED_ARRAY(VECTOR3, Vector3, get_vector3_array, get_vector3);
+ OPCODE_ITERATE_PACKED_ARRAY(COLOR, Color, get_color_array, get_color);
+
+ OPCODE(OPCODE_ITERATE_OBJECT) {
+ CHECK_SPACE(4);
+
+ GET_INSTRUCTION_ARG(counter, 0);
+ GET_INSTRUCTION_ARG(container, 1);
+
+#ifdef DEBUG_ENABLED
+ bool freed = false;
+ Object *obj = container->get_validated_object_with_check(freed);
+ if (freed) {
+ err_text = "Trying to iterate on a previously freed object.";
+ OPCODE_BREAK;
+ } else if (!obj) {
+ err_text = "Trying to iterate on a null value.";
+ OPCODE_BREAK;
+ }
+#else
+ Object *obj = *VariantInternal::get_object(container);
+#endif
+ Array ref;
+ ref.push_back(*counter);
+ Variant vref;
+ VariantInternal::initialize(&vref, Variant::ARRAY);
+ *VariantInternal::get_array(&vref) = ref;
+
+ Variant **args = instruction_args; // Overriding an instruction argument, but we don't need access to that anymore.
+ args[0] = &vref;
+
+ Callable::CallError ce;
+ Variant has_next = obj->call(CoreStringNames::get_singleton()->_iter_next, (const Variant **)args, 1, ce);
+
+#ifdef DEBUG_ENABLED
+ if (ce.error != Callable::CallError::CALL_OK) {
+ err_text = vformat(R"(There was an error calling "_iter_next" on iterator object of type %s.)", *container);
+ OPCODE_BREAK;
+ }
+#endif
+ if (!has_next.booleanize()) {
+ int jumpto = _code_ptr[ip + 4];
+ GD_ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
+ } else {
+ GET_INSTRUCTION_ARG(iterator, 2);
+ *iterator = obj->call(CoreStringNames::get_singleton()->_iter_get, (const Variant **)args, 1, ce);
+#ifdef DEBUG_ENABLED
+ if (ce.error != Callable::CallError::CALL_OK) {
+ err_text = vformat(R"(There was an error calling "_iter_get" on iterator object of type %s.)", *container);
+ OPCODE_BREAK;
+ }
+#endif
+
+ ip += 5; // Loop again.
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_ASSERT) {
+ CHECK_SPACE(3);
+
+#ifdef DEBUG_ENABLED
+ GET_INSTRUCTION_ARG(test, 0);
+ bool result = test->booleanize();
+
+ if (!result) {
+ String message_str;
+ if (_code_ptr[ip + 2] != 0) {
+ GET_INSTRUCTION_ARG(message, 1);
+ message_str = *message;
+ }
+ if (message_str.is_empty()) {
+ err_text = "Assertion failed.";
+ } else {
+ err_text = "Assertion failed: " + message_str;
+ }
+ OPCODE_BREAK;
+ }
+
+#endif
+ ip += 3;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_BREAKPOINT) {
+#ifdef DEBUG_ENABLED
+ if (EngineDebugger::is_active()) {
+ GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true);
+ }
+#endif
+ ip += 1;
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_LINE) {
+ CHECK_SPACE(2);
+
+ line = _code_ptr[ip + 1];
+ ip += 2;
+
+ if (EngineDebugger::is_active()) {
+ // line
+ bool do_break = false;
+
+ if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) {
+ if (EngineDebugger::get_script_debugger()->get_depth() <= 0) {
+ EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1);
+ }
+ if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0) {
+ do_break = true;
+ }
+ }
+
+ if (EngineDebugger::get_script_debugger()->is_breakpoint(line, source)) {
+ do_break = true;
+ }
+
+ if (do_break) {
+ GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true);
+ }
+
+ EngineDebugger::get_singleton()->line_poll();
+ }
+ }
+ DISPATCH_OPCODE;
+
+ OPCODE(OPCODE_END) {
+#ifdef DEBUG_ENABLED
+ exit_ok = true;
+#endif
+ OPCODE_BREAK;
+ }
+
+#if 0 // Enable for debugging.
+ default: {
+ err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip);
+ OPCODE_BREAK;
+ }
+#endif
+ }
+
+ OPCODES_END
+#ifdef DEBUG_ENABLED
+ if (exit_ok) {
+ OPCODE_OUT;
+ }
+ //error
+ // function, file, line, error, explanation
+ String err_file;
+ if (p_instance && ObjectDB::get_instance(p_instance->owner_id) != nullptr && 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 && ObjectDB::get_instance(p_instance->owner_id) != nullptr && p_instance->script->is_valid() && p_instance->script->name != "") {
+ err_func = p_instance->script->name + "." + err_func;
+ }
+ int err_line = line;
+ if (err_text == "") {
+ err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please).";
+ }
+
+ if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) {
+ // debugger break did not happen
+
+ _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT);
+ }
+
+#endif
+ OPCODE_OUT;
+ }
+
+ OPCODES_OUT
+#ifdef DEBUG_ENABLED
+ if (GDScriptLanguage::get_singleton()->profiling) {
+ uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time;
+ profile.total_time += time_taken;
+ profile.self_time += time_taken - function_call_time;
+ profile.frame_total_time += time_taken;
+ profile.frame_self_time += time_taken - function_call_time;
+ GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time;
+ }
+
+ // Check if this is the last time the function is resuming from await
+ // Will be true if never awaited 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 || awaited) {
+ if (EngineDebugger::is_active()) {
+ GDScriptLanguage::get_singleton()->exit_function();
+ }
+#endif
+
+ if (_stack_size) {
+ //free stack
+ for (int i = 0; i < _stack_size; i++) {
+ stack[i].~Variant();
+ }
+ }
+
+#ifdef DEBUG_ENABLED
+ }
+#endif
+
+ return retvalue;
+}
diff --git a/modules/gdscript/gdscript_warning.cpp b/modules/gdscript/gdscript_warning.cpp
new file mode 100644
index 0000000000..ad41b60a4e
--- /dev/null
+++ b/modules/gdscript/gdscript_warning.cpp
@@ -0,0 +1,210 @@
+/*************************************************************************/
+/* gdscript_warning.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gdscript_warning.h"
+
+#include "core/variant/variant.h"
+
+#ifdef DEBUG_ENABLED
+
+String GDScriptWarning::get_message() const {
+#define CHECK_SYMBOLS(m_amount) ERR_FAIL_COND_V(symbols.size() < m_amount, String());
+
+ switch (code) {
+ case UNASSIGNED_VARIABLE_OP_ASSIGN: {
+ CHECK_SYMBOLS(1);
+ return "Using assignment with operation but the variable '" + symbols[0] + "' was not previously assigned a value.";
+ } break;
+ case UNASSIGNED_VARIABLE: {
+ CHECK_SYMBOLS(1);
+ return "The variable '" + symbols[0] + "' was used but never assigned a value.";
+ } break;
+ case UNUSED_VARIABLE: {
+ CHECK_SYMBOLS(1);
+ return "The local variable '" + symbols[0] + "' is declared but never used in the block. If this is intended, prefix it with an underscore: '_" + symbols[0] + "'";
+ } break;
+ case UNUSED_LOCAL_CONSTANT: {
+ CHECK_SYMBOLS(1);
+ return "The local constant '" + symbols[0] + "' is declared but never used in the block. If this is intended, prefix it with an underscore: '_" + symbols[0] + "'";
+ } break;
+ case SHADOWED_VARIABLE: {
+ CHECK_SYMBOLS(4);
+ return vformat(R"(The local %s "%s" is shadowing an already-declared %s at line %s.)", symbols[0], symbols[1], symbols[2], symbols[3]);
+ } break;
+ case SHADOWED_VARIABLE_BASE_CLASS: {
+ CHECK_SYMBOLS(4);
+ return vformat(R"(The local %s "%s" is shadowing an already-declared %s at the base class "%s".)", symbols[0], symbols[1], symbols[2], symbols[3]);
+ } break;
+ case UNUSED_PRIVATE_CLASS_VARIABLE: {
+ CHECK_SYMBOLS(1);
+ return "The class variable '" + symbols[0] + "' is declared but never used in the script.";
+ } break;
+ case UNUSED_PARAMETER: {
+ CHECK_SYMBOLS(2);
+ return "The parameter '" + symbols[1] + "' is never used in the function '" + symbols[0] + "'. If this is intended, prefix it with an underscore: '_" + symbols[1] + "'";
+ } break;
+ case UNREACHABLE_CODE: {
+ CHECK_SYMBOLS(1);
+ return "Unreachable code (statement after return) in function '" + symbols[0] + "()'.";
+ } break;
+ case UNREACHABLE_PATTERN: {
+ return "Unreachable pattern (pattern after wildcard or bind).";
+ } break;
+ case STANDALONE_EXPRESSION: {
+ return "Standalone expression (the line has no effect).";
+ } break;
+ case VOID_ASSIGNMENT: {
+ CHECK_SYMBOLS(1);
+ return "Assignment operation, but the function '" + symbols[0] + "()' returns void.";
+ } break;
+ case NARROWING_CONVERSION: {
+ return "Narrowing conversion (float is converted to int and loses precision).";
+ } break;
+ case INCOMPATIBLE_TERNARY: {
+ return "Values of the ternary conditional are not mutually compatible.";
+ } break;
+ case UNUSED_SIGNAL: {
+ CHECK_SYMBOLS(1);
+ return "The signal '" + symbols[0] + "' is declared but never emitted.";
+ } break;
+ case RETURN_VALUE_DISCARDED: {
+ CHECK_SYMBOLS(1);
+ return "The function '" + symbols[0] + "()' returns a value, but this value is never used.";
+ } break;
+ case PROPERTY_USED_AS_FUNCTION: {
+ CHECK_SYMBOLS(2);
+ return "The method '" + symbols[0] + "()' was not found in base '" + symbols[1] + "' but there's a property with the same name. Did you mean to access it?";
+ } break;
+ case CONSTANT_USED_AS_FUNCTION: {
+ CHECK_SYMBOLS(2);
+ return "The method '" + symbols[0] + "()' was not found in base '" + symbols[1] + "' but there's a constant with the same name. Did you mean to access it?";
+ } break;
+ case FUNCTION_USED_AS_PROPERTY: {
+ CHECK_SYMBOLS(2);
+ return "The property '" + symbols[0] + "' was not found in base '" + symbols[1] + "' but there's a method with the same name. Did you mean to call it?";
+ } break;
+ case INTEGER_DIVISION: {
+ return "Integer division, decimal part will be discarded.";
+ } break;
+ case UNSAFE_PROPERTY_ACCESS: {
+ CHECK_SYMBOLS(2);
+ return "The property '" + symbols[0] + "' is not present on the inferred type '" + symbols[1] + "' (but may be present on a subtype).";
+ } break;
+ case UNSAFE_METHOD_ACCESS: {
+ CHECK_SYMBOLS(2);
+ return "The method '" + symbols[0] + "' is not present on the inferred type '" + symbols[1] + "' (but may be present on a subtype).";
+ } break;
+ case UNSAFE_CAST: {
+ CHECK_SYMBOLS(1);
+ return "The value is cast to '" + symbols[0] + "' but has an unknown type.";
+ } break;
+ case UNSAFE_CALL_ARGUMENT: {
+ CHECK_SYMBOLS(4);
+ return "The argument '" + symbols[0] + "' of the function '" + symbols[1] + "' requires a the subtype '" + symbols[2] + "' but the supertype '" + symbols[3] + "' was provided";
+ } break;
+ case DEPRECATED_KEYWORD: {
+ CHECK_SYMBOLS(2);
+ return "The '" + symbols[0] + "' keyword is deprecated and will be removed in a future release, please replace its uses by '" + symbols[1] + "'.";
+ } break;
+ case STANDALONE_TERNARY: {
+ return "Standalone ternary conditional operator: the return value is being discarded.";
+ }
+ case ASSERT_ALWAYS_TRUE: {
+ return "Assert statement is redundant because the expression is always true.";
+ }
+ case ASSERT_ALWAYS_FALSE: {
+ return "Assert statement will raise an error because the expression is always false.";
+ }
+ case REDUNDANT_AWAIT: {
+ return R"("await" keyword not needed in this case, because the expression isn't a coroutine nor a signal.)";
+ }
+ case WARNING_MAX:
+ break; // Can't happen, but silences warning
+ }
+ ERR_FAIL_V_MSG(String(), "Invalid GDScript warning code: " + get_name_from_code(code) + ".");
+
+#undef CHECK_SYMBOLS
+}
+
+String GDScriptWarning::get_name() const {
+ return get_name_from_code(code);
+}
+
+String GDScriptWarning::get_name_from_code(Code p_code) {
+ ERR_FAIL_COND_V(p_code < 0 || p_code >= WARNING_MAX, String());
+
+ static const char *names[] = {
+ "UNASSIGNED_VARIABLE",
+ "UNASSIGNED_VARIABLE_OP_ASSIGN",
+ "UNUSED_VARIABLE",
+ "UNUSED_LOCAL_CONSTANT",
+ "SHADOWED_VARIABLE",
+ "SHADOWED_VARIABLE_BASE_CLASS",
+ "UNUSED_PRIVATE_CLASS_VARIABLE",
+ "UNUSED_PARAMETER",
+ "UNREACHABLE_CODE",
+ "UNREACHABLE_PATTERN",
+ "STANDALONE_EXPRESSION",
+ "VOID_ASSIGNMENT",
+ "NARROWING_CONVERSION",
+ "INCOMPATIBLE_TERNARY",
+ "UNUSED_SIGNAL",
+ "RETURN_VALUE_DISCARDED",
+ "PROPERTY_USED_AS_FUNCTION",
+ "CONSTANT_USED_AS_FUNCTION",
+ "FUNCTION_USED_AS_PROPERTY",
+ "INTEGER_DIVISION",
+ "UNSAFE_PROPERTY_ACCESS",
+ "UNSAFE_METHOD_ACCESS",
+ "UNSAFE_CAST",
+ "UNSAFE_CALL_ARGUMENT",
+ "DEPRECATED_KEYWORD",
+ "STANDALONE_TERNARY",
+ "ASSERT_ALWAYS_TRUE",
+ "ASSERT_ALWAYS_FALSE",
+ "REDUNDANT_AWAIT",
+ };
+
+ static_assert((sizeof(names) / sizeof(*names)) == WARNING_MAX, "Amount of warning types don't match the amount of warning names.");
+
+ return names[(int)p_code];
+}
+
+GDScriptWarning::Code GDScriptWarning::get_code_from_name(const String &p_name) {
+ for (int i = 0; i < WARNING_MAX; i++) {
+ if (get_name_from_code((Code)i) == p_name) {
+ return (Code)i;
+ }
+ }
+
+ ERR_FAIL_V_MSG(WARNING_MAX, "Invalid GDScript warning name: " + p_name);
+}
+
+#endif // DEBUG_ENABLED
diff --git a/modules/gdscript/gdscript_warning.h b/modules/gdscript/gdscript_warning.h
new file mode 100644
index 0000000000..4b295b5eb8
--- /dev/null
+++ b/modules/gdscript/gdscript_warning.h
@@ -0,0 +1,87 @@
+/*************************************************************************/
+/* gdscript_warning.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GDSCRIPT_WARNINGS
+#define GDSCRIPT_WARNINGS
+
+#ifdef DEBUG_ENABLED
+
+#include "core/string/ustring.h"
+#include "core/templates/vector.h"
+
+class GDScriptWarning {
+public:
+ enum Code {
+ UNASSIGNED_VARIABLE, // Variable used but never assigned.
+ UNASSIGNED_VARIABLE_OP_ASSIGN, // Variable never assigned but used in an assignment operation (+=, *=, etc).
+ UNUSED_VARIABLE, // Local variable is declared but never used.
+ UNUSED_LOCAL_CONSTANT, // Local constant is declared but never used.
+ SHADOWED_VARIABLE, // Variable name shadowed by other variable in same class.
+ SHADOWED_VARIABLE_BASE_CLASS, // Variable name shadowed by other variable in some base class.
+ UNUSED_PRIVATE_CLASS_VARIABLE, // Class variable is declared private ("_" prefix) but never used in the file.
+ UNUSED_PARAMETER, // Function parameter is never used.
+ UNREACHABLE_CODE, // Code after a return statement.
+ UNREACHABLE_PATTERN, // Pattern in a match statement after a catch all pattern (wildcard or bind).
+ STANDALONE_EXPRESSION, // Expression not assigned to a variable.
+ VOID_ASSIGNMENT, // Function returns void but it's assigned to a variable.
+ NARROWING_CONVERSION, // Float value into an integer slot, precision is lost.
+ INCOMPATIBLE_TERNARY, // Possible values of a ternary if are not mutually compatible.
+ UNUSED_SIGNAL, // Signal is defined but never emitted.
+ RETURN_VALUE_DISCARDED, // Function call returns something but the value isn't used.
+ PROPERTY_USED_AS_FUNCTION, // Function not found, but there's a property with the same name.
+ CONSTANT_USED_AS_FUNCTION, // Function not found, but there's a constant with the same name.
+ FUNCTION_USED_AS_PROPERTY, // Property not found, but there's a function with the same name.
+ INTEGER_DIVISION, // Integer divide by integer, decimal part is discarded.
+ UNSAFE_PROPERTY_ACCESS, // Property not found in the detected type (but can be in subtypes).
+ UNSAFE_METHOD_ACCESS, // Function not found in the detected type (but can be in subtypes).
+ UNSAFE_CAST, // Cast used in an unknown type.
+ UNSAFE_CALL_ARGUMENT, // Function call argument is of a supertype of the require argument.
+ DEPRECATED_KEYWORD, // The keyword is deprecated and should be replaced.
+ STANDALONE_TERNARY, // Return value of ternary expression is discarded.
+ ASSERT_ALWAYS_TRUE, // Expression for assert argument is always true.
+ ASSERT_ALWAYS_FALSE, // Expression for assert argument is always false.
+ REDUNDANT_AWAIT, // await is used but expression is synchronous (not a signal nor a coroutine).
+ WARNING_MAX,
+ };
+
+ Code code = WARNING_MAX;
+ int start_line = -1, end_line = -1;
+ int leftmost_column = -1, rightmost_column = -1;
+ Vector<String> symbols;
+
+ String get_name() const;
+ String get_message() const;
+ static String get_name_from_code(Code p_code);
+ static Code get_code_from_name(const String &p_name);
+};
+
+#endif // DEBUG_ENABLED
+
+#endif // GDSCRIPT_WARNINGS
diff --git a/modules/gdscript/icons/GDScript.svg b/modules/gdscript/icons/GDScript.svg
index 953bb9ae9e..aa59125ea9 100644
--- a/modules/gdscript/icons/GDScript.svg
+++ b/modules/gdscript/icons/GDScript.svg
@@ -1,5 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625v2l2.2578.56445a5 5 0 0 0 .2793.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 .68555.28516l.5625 2.2539h2l.56445-2.2578a5 5 0 0 0 .6875-.2793l1.9902 1.1934 1.4141-1.4141-1.1953-1.9941a5 5 0 0 0 .28516-.68555l2.2539-.5625v-2l-2.2578-.56445a5 5 0 0 0 -.2793-.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.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"/></svg>
diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp
index b2c6b0e1ab..e63b6ab20e 100644
--- a/modules/gdscript/language_server/gdscript_extend_parser.cpp
+++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,24 +29,27 @@
/*************************************************************************/
#include "gdscript_extend_parser.h"
+
#include "../gdscript.h"
+#include "../gdscript_analyzer.h"
#include "core/io/json.h"
#include "gdscript_language_protocol.h"
#include "gdscript_workspace.h"
void ExtendGDScriptParser::update_diagnostics() {
-
diagnostics.clear();
- if (has_error()) {
+ const List<ParserError> &errors = get_errors();
+ for (const List<ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
+ const ParserError &error = E->get();
lsp::Diagnostic diagnostic;
diagnostic.severity = lsp::DiagnosticSeverity::Error;
- diagnostic.message = get_error();
+ diagnostic.message = error.message;
diagnostic.source = "gdscript";
diagnostic.code = -1;
lsp::Range range;
lsp::Position pos;
- int line = LINE_NUMBER_TO_INDEX(get_error_line());
+ int line = LINE_NUMBER_TO_INDEX(error.line);
const String &line_text = get_lines()[line];
pos.line = line;
pos.character = line_text.length() - line_text.strip_edges(true, false).length();
@@ -62,12 +65,12 @@ void ExtendGDScriptParser::update_diagnostics() {
const GDScriptWarning &warning = E->get();
lsp::Diagnostic diagnostic;
diagnostic.severity = lsp::DiagnosticSeverity::Warning;
- diagnostic.message = warning.get_message();
+ diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message();
diagnostic.source = "gdscript";
diagnostic.code = warning.code;
lsp::Range range;
lsp::Position pos;
- int line = LINE_NUMBER_TO_INDEX(warning.line);
+ int line = LINE_NUMBER_TO_INDEX(warning.start_line);
const String &line_text = get_lines()[line];
pos.line = line;
pos.character = line_text.length() - line_text.strip_edges(true, false).length();
@@ -80,12 +83,10 @@ void ExtendGDScriptParser::update_diagnostics() {
}
void ExtendGDScriptParser::update_symbols() {
-
members.clear();
- const GDScriptParser::Node *head = get_parse_tree();
+ const GDScriptParser::Node *head = get_tree();
if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) {
-
parse_class_symbol(gdclass, class_symbol);
for (int i = 0; i < class_symbol.children.size(); i++) {
@@ -108,15 +109,15 @@ void ExtendGDScriptParser::update_symbols() {
void ExtendGDScriptParser::update_document_links(const String &p_code) {
document_links.clear();
- GDScriptTokenizerText tokenizer;
+ GDScriptTokenizer tokenizer;
FileAccessRef fs = FileAccess::create(FileAccess::ACCESS_RESOURCES);
- tokenizer.set_code(p_code);
+ tokenizer.set_source_code(p_code);
while (true) {
- GDScriptTokenizerText::Token token = tokenizer.get_token();
- if (token == GDScriptTokenizer::TK_EOF || token == GDScriptTokenizer::TK_ERROR) {
+ GDScriptTokenizer::Token token = tokenizer.scan();
+ if (token.type == GDScriptTokenizer::Token::TK_EOF) {
break;
- } else if (token == GDScriptTokenizer::TK_CONSTANT) {
- const Variant &const_val = tokenizer.get_token_constant();
+ } else if (token.type == GDScriptTokenizer::Token::LITERAL) {
+ const Variant &const_val = token.literal;
if (const_val.get_type() == Variant::STRING) {
String path = const_val;
bool exists = fs->file_exists(path);
@@ -128,239 +129,255 @@ void ExtendGDScriptParser::update_document_links(const String &p_code) {
String value = const_val;
lsp::DocumentLink link;
link.target = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_uri(path);
- link.range.start.line = LINE_NUMBER_TO_INDEX(tokenizer.get_token_line());
- link.range.end.line = link.range.start.line;
- link.range.end.character = LINE_NUMBER_TO_INDEX(tokenizer.get_token_column());
- link.range.start.character = link.range.end.character - value.length();
+ link.range.start.line = LINE_NUMBER_TO_INDEX(token.start_line);
+ link.range.end.line = LINE_NUMBER_TO_INDEX(token.end_line);
+ link.range.start.character = LINE_NUMBER_TO_INDEX(token.start_column);
+ link.range.end.character = LINE_NUMBER_TO_INDEX(token.end_column);
document_links.push_back(link);
}
}
}
- tokenizer.advance();
}
}
void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p_class, lsp::DocumentSymbol &r_symbol) {
-
const String uri = get_uri();
r_symbol.uri = uri;
r_symbol.script_path = path;
r_symbol.children.clear();
- r_symbol.name = p_class->name;
- if (r_symbol.name.empty())
+ r_symbol.name = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
+ if (r_symbol.name.is_empty()) {
r_symbol.name = path.get_file();
+ }
r_symbol.kind = lsp::SymbolKind::Class;
r_symbol.deprecated = false;
- r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_class->line);
- r_symbol.range.start.character = p_class->column;
+ r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_class->start_line);
+ r_symbol.range.start.character = LINE_NUMBER_TO_INDEX(p_class->start_column);
r_symbol.range.end.line = LINE_NUMBER_TO_INDEX(p_class->end_line);
r_symbol.selectionRange.start.line = r_symbol.range.start.line;
r_symbol.detail = "class " + r_symbol.name;
bool is_root_class = &r_symbol == &class_symbol;
- r_symbol.documentation = parse_documentation(is_root_class ? 0 : LINE_NUMBER_TO_INDEX(p_class->line), is_root_class);
-
- for (int i = 0; i < p_class->variables.size(); ++i) {
-
- const GDScriptParser::ClassNode::Member &m = p_class->variables[i];
-
- lsp::DocumentSymbol symbol;
- symbol.name = m.identifier;
- symbol.kind = lsp::SymbolKind::Variable;
- symbol.deprecated = false;
- const int line = LINE_NUMBER_TO_INDEX(m.line);
- symbol.range.start.line = line;
- symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length();
- symbol.range.end.line = line;
- symbol.range.end.character = lines[line].length();
- symbol.selectionRange.start.line = symbol.range.start.line;
- if (m._export.type != Variant::NIL) {
- symbol.detail += "export ";
- }
- symbol.detail += "var " + m.identifier;
- if (m.data_type.kind != GDScriptParser::DataType::UNRESOLVED) {
- symbol.detail += ": " + m.data_type.to_string();
- }
- if (m.default_value.get_type() != Variant::NIL) {
- symbol.detail += " = " + JSON::print(m.default_value);
- }
-
- symbol.documentation = parse_documentation(line);
- symbol.uri = uri;
- symbol.script_path = path;
-
- r_symbol.children.push_back(symbol);
- }
-
- for (int i = 0; i < p_class->_signals.size(); ++i) {
- const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i];
-
- lsp::DocumentSymbol symbol;
- symbol.name = signal.name;
- symbol.kind = lsp::SymbolKind::Event;
- symbol.deprecated = false;
- const int line = LINE_NUMBER_TO_INDEX(signal.line);
- symbol.range.start.line = line;
- symbol.range.start.character = lines[line].length() - lines[line].strip_edges(true, false).length();
- symbol.range.end.line = symbol.range.start.line;
- symbol.range.end.character = lines[line].length();
- symbol.selectionRange.start.line = symbol.range.start.line;
- symbol.documentation = parse_documentation(line);
- symbol.uri = uri;
- symbol.script_path = path;
- symbol.detail = "signal " + signal.name + "(";
- for (int j = 0; j < signal.arguments.size(); j++) {
- if (j > 0) {
- symbol.detail += ", ";
- }
- symbol.detail += signal.arguments[j];
- }
- symbol.detail += ")";
-
- r_symbol.children.push_back(symbol);
- }
+ r_symbol.documentation = parse_documentation(is_root_class ? 0 : LINE_NUMBER_TO_INDEX(p_class->start_line), is_root_class);
+
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const ClassNode::Member &m = p_class->members[i];
+
+ switch (m.type) {
+ case ClassNode::Member::VARIABLE: {
+ lsp::DocumentSymbol symbol;
+ symbol.name = m.variable->identifier->name;
+ symbol.kind = lsp::SymbolKind::Variable;
+ symbol.deprecated = false;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.variable->start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.variable->start_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(m.variable->end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(m.variable->end_column);
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ if (m.variable->exported) {
+ symbol.detail += "@export ";
+ }
+ symbol.detail += "var " + m.variable->identifier->name;
+ if (m.get_datatype().is_hard_type()) {
+ symbol.detail += ": " + m.get_datatype().to_string();
+ }
+ if (m.variable->initializer != nullptr && m.variable->initializer->is_constant) {
+ symbol.detail += " = " + JSON::print(m.variable->initializer->reduced_value);
+ }
- for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
- lsp::DocumentSymbol symbol;
- const GDScriptParser::ClassNode::Constant &c = E->value();
- const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression);
- ERR_FAIL_COND(!node);
- symbol.name = E->key();
- symbol.kind = lsp::SymbolKind::Constant;
- symbol.deprecated = false;
- const int line = LINE_NUMBER_TO_INDEX(E->get().expression->line);
- symbol.range.start.line = line;
- symbol.range.start.character = E->get().expression->column;
- symbol.range.end.line = symbol.range.start.line;
- symbol.range.end.character = lines[line].length();
- symbol.selectionRange.start.line = symbol.range.start.line;
- symbol.documentation = parse_documentation(line);
- symbol.uri = uri;
- symbol.script_path = path;
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.variable->start_line));
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::CONSTANT: {
+ lsp::DocumentSymbol symbol;
+
+ symbol.name = m.constant->identifier->name;
+ symbol.kind = lsp::SymbolKind::Constant;
+ symbol.deprecated = false;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.constant->start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.constant->start_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(m.constant->end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(m.constant->start_column);
+ symbol.selectionRange.start.line = LINE_NUMBER_TO_INDEX(m.constant->start_line);
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.constant->start_line));
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ symbol.detail = "const " + symbol.name;
+ if (m.constant->get_datatype().is_hard_type()) {
+ symbol.detail += ": " + m.constant->get_datatype().to_string();
+ }
- symbol.detail = "const " + symbol.name;
- if (c.type.kind != GDScriptParser::DataType::UNRESOLVED) {
- symbol.detail += ": " + c.type.to_string();
- }
+ const Variant &default_value = m.constant->initializer->reduced_value;
+ String value_text;
+ if (default_value.get_type() == Variant::OBJECT) {
+ RES res = default_value;
+ if (res.is_valid() && !res->get_path().is_empty()) {
+ value_text = "preload(\"" + res->get_path() + "\")";
+ if (symbol.documentation.is_empty()) {
+ if (Map<String, ExtendGDScriptParser *>::Element *S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
+ symbol.documentation = S->get()->class_symbol.documentation;
+ }
+ }
+ } else {
+ value_text = JSON::print(default_value);
+ }
+ } else {
+ value_text = JSON::print(default_value);
+ }
+ if (!value_text.is_empty()) {
+ symbol.detail += " = " + value_text;
+ }
- String value_text;
- if (node->value.get_type() == Variant::OBJECT) {
- RES res = node->value;
- if (res.is_valid() && !res->get_path().empty()) {
- value_text = "preload(\"" + res->get_path() + "\")";
- if (symbol.documentation.empty()) {
- if (Map<String, ExtendGDScriptParser *>::Element *S = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.find(res->get_path())) {
- symbol.documentation = S->get()->class_symbol.documentation;
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::ENUM_VALUE: {
+ lsp::DocumentSymbol symbol;
+
+ symbol.name = m.enum_value.identifier->name;
+ symbol.kind = lsp::SymbolKind::EnumMember;
+ symbol.deprecated = false;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.enum_value.line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.enum_value.leftmost_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(m.enum_value.line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(m.enum_value.rightmost_column);
+ symbol.selectionRange.start.line = LINE_NUMBER_TO_INDEX(m.enum_value.line);
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.enum_value.line));
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ symbol.detail = symbol.name + " = " + itos(m.enum_value.value);
+
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::SIGNAL: {
+ lsp::DocumentSymbol symbol;
+ symbol.name = m.signal->identifier->name;
+ symbol.kind = lsp::SymbolKind::Event;
+ symbol.deprecated = false;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.signal->start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.signal->start_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(m.signal->end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(m.signal->end_column);
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.signal->start_line));
+ symbol.uri = uri;
+ symbol.script_path = path;
+ symbol.detail = "signal " + String(m.signal->identifier->name) + "(";
+ for (int j = 0; j < m.signal->parameters.size(); j++) {
+ if (j > 0) {
+ symbol.detail += ", ";
}
+ symbol.detail += m.signal->parameters[i]->identifier->name;
}
- } else {
- value_text = JSON::print(node->value);
- }
- } else {
- value_text = JSON::print(node->value);
- }
- if (!value_text.empty()) {
- symbol.detail += " = " + value_text;
+ symbol.detail += ")";
+
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::ENUM: {
+ lsp::DocumentSymbol symbol;
+ symbol.kind = lsp::SymbolKind::Enum;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.m_enum->start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.m_enum->start_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(m.m_enum->end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(m.m_enum->end_column);
+ symbol.selectionRange.start.line = symbol.range.start.line;
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.m_enum->start_line));
+ symbol.uri = uri;
+ symbol.script_path = path;
+
+ symbol.detail = "enum " + String(m.m_enum->identifier->name) + "{";
+ for (int j = 0; j < m.m_enum->values.size(); j++) {
+ if (j > 0) {
+ symbol.detail += ", ";
+ }
+ symbol.detail += String(m.m_enum->values[j].identifier->name) + " = " + itos(m.m_enum->values[j].value);
+ }
+ symbol.detail += "}";
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::FUNCTION: {
+ lsp::DocumentSymbol symbol;
+ parse_function_symbol(m.function, symbol);
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::CLASS: {
+ lsp::DocumentSymbol symbol;
+ parse_class_symbol(m.m_class, symbol);
+ r_symbol.children.push_back(symbol);
+ } break;
+ case ClassNode::Member::UNDEFINED:
+ break; // Unreachable.
}
-
- r_symbol.children.push_back(symbol);
- }
-
- for (int i = 0; i < p_class->functions.size(); ++i) {
- const GDScriptParser::FunctionNode *func = p_class->functions[i];
- lsp::DocumentSymbol symbol;
- parse_function_symbol(func, symbol);
- r_symbol.children.push_back(symbol);
- }
-
- for (int i = 0; i < p_class->static_functions.size(); ++i) {
- const GDScriptParser::FunctionNode *func = p_class->static_functions[i];
- lsp::DocumentSymbol symbol;
- parse_function_symbol(func, symbol);
- r_symbol.children.push_back(symbol);
- }
-
- for (int i = 0; i < p_class->subclasses.size(); ++i) {
- const GDScriptParser::ClassNode *subclass = p_class->subclasses[i];
- lsp::DocumentSymbol symbol;
- parse_class_symbol(subclass, symbol);
- r_symbol.children.push_back(symbol);
}
}
void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionNode *p_func, lsp::DocumentSymbol &r_symbol) {
-
const String uri = get_uri();
- r_symbol.name = p_func->name;
+ r_symbol.name = p_func->identifier->name;
r_symbol.kind = lsp::SymbolKind::Function;
- r_symbol.detail = "func " + p_func->name + "(";
+ r_symbol.detail = "func " + String(p_func->identifier->name) + "(";
r_symbol.deprecated = false;
- const int line = LINE_NUMBER_TO_INDEX(p_func->line);
- r_symbol.range.start.line = line;
- r_symbol.range.start.character = p_func->column;
- r_symbol.range.end.line = MAX(p_func->body->end_line - 2, r_symbol.range.start.line);
- r_symbol.range.end.character = lines[r_symbol.range.end.line].length();
+ r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_func->start_line);
+ r_symbol.range.start.character = LINE_NUMBER_TO_INDEX(p_func->start_column);
+ r_symbol.range.end.line = LINE_NUMBER_TO_INDEX(p_func->start_line);
+ r_symbol.range.end.character = LINE_NUMBER_TO_INDEX(p_func->end_column);
r_symbol.selectionRange.start.line = r_symbol.range.start.line;
- r_symbol.documentation = parse_documentation(line);
+ r_symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(p_func->start_line));
r_symbol.uri = uri;
r_symbol.script_path = path;
- String arguments;
- for (int i = 0; i < p_func->arguments.size(); i++) {
+ String parameters;
+ for (int i = 0; i < p_func->parameters.size(); i++) {
+ const ParameterNode *parameter = p_func->parameters[i];
lsp::DocumentSymbol symbol;
symbol.kind = lsp::SymbolKind::Variable;
- symbol.name = p_func->arguments[i];
- symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_func->body->line);
- symbol.range.start.character = p_func->body->column;
- symbol.range.end = symbol.range.start;
+ symbol.name = parameter->identifier->name;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(parameter->start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(parameter->start_line);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(parameter->end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(parameter->end_column);
symbol.uri = uri;
symbol.script_path = path;
r_symbol.children.push_back(symbol);
if (i > 0) {
- arguments += ", ";
+ parameters += ", ";
}
- arguments += String(p_func->arguments[i]);
- if (p_func->argument_types[i].kind != GDScriptParser::DataType::UNRESOLVED) {
- arguments += ": " + p_func->argument_types[i].to_string();
+ parameters += String(parameter->identifier->name);
+ if (parameter->get_datatype().is_hard_type()) {
+ parameters += ": " + parameter->get_datatype().to_string();
}
- int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size());
- if (default_value_idx >= 0) {
- const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]);
- if (const_node == nullptr) {
- const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]);
- if (operator_node) {
- const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next);
- }
- }
-
- if (const_node) {
- String value = JSON::print(const_node->value);
- arguments += " = " + value;
- }
+ if (parameter->default_value != nullptr) {
+ String value = JSON::print(parameter->default_value->reduced_value);
+ parameters += " = " + value;
}
}
- r_symbol.detail += arguments + ")";
- if (p_func->return_type.kind != GDScriptParser::DataType::UNRESOLVED) {
- r_symbol.detail += " -> " + p_func->return_type.to_string();
+ r_symbol.detail += parameters + ")";
+ if (p_func->get_datatype().is_hard_type()) {
+ r_symbol.detail += " -> " + p_func->get_datatype().to_string();
}
- for (const Map<StringName, LocalVarNode *>::Element *E = p_func->body->variables.front(); E; E = E->next()) {
+ for (int i = 0; i < p_func->body->locals.size(); i++) {
+ const SuiteNode::Local &local = p_func->body->locals[i];
lsp::DocumentSymbol symbol;
- const GDScriptParser::LocalVarNode *var = E->value();
- symbol.name = E->key();
- symbol.kind = lsp::SymbolKind::Variable;
- symbol.range.start.line = LINE_NUMBER_TO_INDEX(E->get()->line);
- symbol.range.start.character = E->get()->column;
- symbol.range.end.line = symbol.range.start.line;
- symbol.range.end.character = lines[symbol.range.end.line].length();
+ symbol.name = local.name;
+ symbol.kind = local.type == SuiteNode::Local::CONSTANT ? lsp::SymbolKind::Constant : lsp::SymbolKind::Variable;
+ symbol.range.start.line = LINE_NUMBER_TO_INDEX(local.start_line);
+ symbol.range.start.character = LINE_NUMBER_TO_INDEX(local.start_column);
+ symbol.range.end.line = LINE_NUMBER_TO_INDEX(local.end_line);
+ symbol.range.end.character = LINE_NUMBER_TO_INDEX(local.end_column);
symbol.uri = uri;
symbol.script_path = path;
- symbol.detail = "var " + symbol.name;
- if (var->datatype.kind != GDScriptParser::DataType::UNRESOLVED) {
- symbol.detail += ": " + var->datatype.to_string();
+ symbol.detail = SuiteNode::Local::CONSTANT ? "const " : "var ";
+ symbol.detail += symbol.name;
+ if (local.get_datatype().is_hard_type()) {
+ symbol.detail += ": " + local.get_datatype().to_string();
}
- symbol.documentation = parse_documentation(line);
+ symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(local.start_line));
r_symbol.children.push_back(symbol);
}
}
@@ -384,8 +401,9 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) {
int step = p_docs_down ? 1 : -1;
int start_line = p_docs_down ? p_line : p_line - 1;
for (int i = start_line; true; i += step) {
-
- if (i < 0 || i >= lines.size()) break;
+ if (i < 0 || i >= lines.size()) {
+ break;
+ }
String line_comment = lines[i].strip_edges(true, false);
if (line_comment.begins_with("#")) {
@@ -408,22 +426,20 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) {
}
String ExtendGDScriptParser::get_text_for_completion(const lsp::Position &p_cursor) const {
-
String longthing;
int len = lines.size();
for (int i = 0; i < len; i++) {
-
if (i == p_cursor.line) {
longthing += lines[i].substr(0, p_cursor.character);
longthing += String::chr(0xFFFF); //not unicode, represents the cursor
longthing += lines[i].substr(p_cursor.character, lines[i].size());
} else {
-
longthing += lines[i];
}
- if (i != len - 1)
+ if (i != len - 1) {
longthing += "\n";
+ }
}
return longthing;
@@ -433,12 +449,11 @@ String ExtendGDScriptParser::get_text_for_lookup_symbol(const lsp::Position &p_c
String longthing;
int len = lines.size();
for (int i = 0; i < len; i++) {
-
if (i == p_cursor.line) {
String line = lines[i];
String first_part = line.substr(0, p_cursor.character);
String last_part = line.substr(p_cursor.character + 1, lines[i].length());
- if (!p_symbol.empty()) {
+ if (!p_symbol.is_empty()) {
String left_cursor_text;
for (int c = p_cursor.character - 1; c >= 0; c--) {
left_cursor_text = line.substr(c, p_cursor.character - c);
@@ -457,19 +472,18 @@ String ExtendGDScriptParser::get_text_for_lookup_symbol(const lsp::Position &p_c
}
longthing += last_part;
} else {
-
longthing += lines[i];
}
- if (i != len - 1)
+ if (i != len - 1) {
longthing += "\n";
+ }
}
return longthing;
}
String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &p_position, Vector2i &p_offset) const {
-
ERR_FAIL_INDEX_V(p_position.line, lines.size(), "");
String line = lines[p_position.line];
ERR_FAIL_INDEX_V(p_position.character, line.size(), "");
@@ -477,7 +491,7 @@ String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &
int start_pos = p_position.character;
for (int c = p_position.character; c >= 0; c--) {
start_pos = c;
- CharType ch = line[c];
+ char32_t ch = line[c];
bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_';
if (!valid_char) {
break;
@@ -486,7 +500,7 @@ String ExtendGDScriptParser::get_identifier_under_position(const lsp::Position &
int end_pos = p_position.character;
for (int c = p_position.character; c < line.length(); c++) {
- CharType ch = line[c];
+ char32_t ch = line[c];
bool valid_char = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_';
if (!valid_char) {
break;
@@ -524,7 +538,6 @@ const lsp::DocumentSymbol *ExtendGDScriptParser::search_symbol_defined_at_line(i
}
Error ExtendGDScriptParser::get_left_function_call(const lsp::Position &p_position, lsp::Position &r_func_pos, int &r_arg_index) const {
-
ERR_FAIL_INDEX_V(p_position.line, lines.size(), ERR_INVALID_PARAMETER);
int bracket_stack = 0;
@@ -539,7 +552,7 @@ Error ExtendGDScriptParser::get_left_function_call(const lsp::Position &p_positi
}
while (c >= 0) {
- const CharType &character = line[c];
+ const char32_t &character = line[c];
if (character == ')') {
++bracket_stack;
} else if (character == '(') {
@@ -576,8 +589,7 @@ const lsp::DocumentSymbol *ExtendGDScriptParser::get_symbol_defined_at_line(int
}
const lsp::DocumentSymbol *ExtendGDScriptParser::get_member_symbol(const String &p_name, const String &p_subclass) const {
-
- if (p_subclass.empty()) {
+ if (p_subclass.is_empty()) {
const lsp::DocumentSymbol *const *ptr = members.getptr(p_name);
if (ptr) {
return *ptr;
@@ -599,12 +611,9 @@ const List<lsp::DocumentLink> &ExtendGDScriptParser::get_document_links() const
}
const Array &ExtendGDScriptParser::get_member_completions() {
-
- if (member_completions.empty()) {
-
+ if (member_completions.is_empty()) {
const String *name = members.next(nullptr);
while (name) {
-
const lsp::DocumentSymbol *symbol = members.get(*name);
lsp::CompletionItem item = symbol->make_completion_item();
item.data = JOIN_SYMBOLS(path, *name);
@@ -615,7 +624,6 @@ const Array &ExtendGDScriptParser::get_member_completions() {
const String *_class = inner_classes.next(nullptr);
while (_class) {
-
const ClassMembers *inner_class = inner_classes.getptr(*_class);
const String *member_name = inner_class->next(nullptr);
while (member_name) {
@@ -637,34 +645,24 @@ const Array &ExtendGDScriptParser::get_member_completions() {
Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::FunctionNode *p_func) const {
Dictionary func;
ERR_FAIL_NULL_V(p_func, func);
- func["name"] = p_func->name;
- func["return_type"] = p_func->return_type.to_string();
+ func["name"] = p_func->identifier->name;
+ func["return_type"] = p_func->get_datatype().to_string();
func["rpc_mode"] = p_func->rpc_mode;
- Array arguments;
- for (int i = 0; i < p_func->arguments.size(); i++) {
+ Array parameters;
+ for (int i = 0; i < p_func->parameters.size(); i++) {
Dictionary arg;
- arg["name"] = p_func->arguments[i];
- arg["type"] = p_func->argument_types[i].to_string();
- int default_value_idx = i - (p_func->arguments.size() - p_func->default_values.size());
- if (default_value_idx >= 0) {
- const GDScriptParser::ConstantNode *const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(p_func->default_values[default_value_idx]);
- if (const_node == nullptr) {
- const GDScriptParser::OperatorNode *operator_node = dynamic_cast<const GDScriptParser::OperatorNode *>(p_func->default_values[default_value_idx]);
- if (operator_node) {
- const_node = dynamic_cast<const GDScriptParser::ConstantNode *>(operator_node->next);
- }
- }
- if (const_node) {
- arg["default_value"] = const_node->value;
- }
+ arg["name"] = p_func->parameters[i]->identifier->name;
+ arg["type"] = p_func->parameters[i]->get_datatype().to_string();
+ if (p_func->parameters[i]->default_value != nullptr) {
+ arg["default_value"] = p_func->parameters[i]->default_value->reduced_value;
}
- arguments.push_back(arg);
+ parameters.push_back(arg);
}
- if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->line))) {
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_func->start_line))) {
func["signature"] = symbol->detail;
func["description"] = symbol->documentation;
}
- func["arguments"] = arguments;
+ func["arguments"] = parameters;
return func;
}
@@ -673,101 +671,125 @@ Dictionary ExtendGDScriptParser::dump_class_api(const GDScriptParser::ClassNode
ERR_FAIL_NULL_V(p_class, class_api);
- class_api["name"] = String(p_class->name);
+ class_api["name"] = p_class->identifier != nullptr ? String(p_class->identifier->name) : String();
class_api["path"] = path;
Array extends_class;
- for (int i = 0; i < p_class->extends_class.size(); i++) {
- extends_class.append(String(p_class->extends_class[i]));
+ for (int i = 0; i < p_class->extends.size(); i++) {
+ extends_class.append(String(p_class->extends[i]));
}
class_api["extends_class"] = extends_class;
- class_api["extends_file"] = String(p_class->extends_file);
+ class_api["extends_file"] = String(p_class->extends_path);
class_api["icon"] = String(p_class->icon_path);
- if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->line))) {
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(p_class->start_line))) {
class_api["signature"] = symbol->detail;
class_api["description"] = symbol->documentation;
}
- Array subclasses;
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- subclasses.push_back(dump_class_api(p_class->subclasses[i]));
- }
- class_api["sub_classes"] = subclasses;
-
+ Array nested_classes;
Array constants;
- for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_class->constant_expressions.front(); E; E = E->next()) {
-
- const GDScriptParser::ClassNode::Constant &c = E->value();
- const GDScriptParser::ConstantNode *node = dynamic_cast<const GDScriptParser::ConstantNode *>(c.expression);
- ERR_FAIL_COND_V(!node, class_api);
-
- Dictionary api;
- api["name"] = E->key();
- api["value"] = node->value;
- api["data_type"] = node->datatype.to_string();
- if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(node->line))) {
- api["signature"] = symbol->detail;
- api["description"] = symbol->documentation;
- }
- constants.push_back(api);
- }
- class_api["constants"] = constants;
-
Array members;
- for (int i = 0; i < p_class->variables.size(); ++i) {
- const GDScriptParser::ClassNode::Member &m = p_class->variables[i];
- Dictionary api;
- api["name"] = m.identifier;
- api["data_type"] = m.data_type.to_string();
- api["default_value"] = m.default_value;
- api["setter"] = String(m.setter);
- api["getter"] = String(m.getter);
- api["export"] = m._export.type != Variant::NIL;
- if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.line))) {
- api["signature"] = symbol->detail;
- api["description"] = symbol->documentation;
- }
- members.push_back(api);
- }
- class_api["members"] = members;
-
Array signals;
- for (int i = 0; i < p_class->_signals.size(); ++i) {
- const GDScriptParser::ClassNode::Signal &signal = p_class->_signals[i];
- Dictionary api;
- api["name"] = signal.name;
- Array args;
- for (int j = 0; j < signal.arguments.size(); j++) {
- args.append(signal.arguments[j]);
- }
- api["arguments"] = args;
- if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(signal.line))) {
- api["signature"] = symbol->detail;
- api["description"] = symbol->documentation;
+ Array methods;
+ Array static_functions;
+
+ for (int i = 0; i < p_class->members.size(); i++) {
+ const ClassNode::Member &m = p_class->members[i];
+ switch (m.type) {
+ case ClassNode::Member::CLASS:
+ nested_classes.push_back(dump_class_api(m.m_class));
+ break;
+ case ClassNode::Member::CONSTANT: {
+ Dictionary api;
+ api["name"] = m.constant->identifier->name;
+ api["value"] = m.constant->initializer->reduced_value;
+ api["data_type"] = m.constant->get_datatype().to_string();
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.constant->start_line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ constants.push_back(api);
+ } break;
+ case ClassNode::Member::ENUM_VALUE: {
+ Dictionary api;
+ api["name"] = m.enum_value.identifier->name;
+ api["value"] = m.enum_value.value;
+ api["data_type"] = m.get_datatype().to_string();
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.enum_value.line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ constants.push_back(api);
+ } break;
+ case ClassNode::Member::ENUM: {
+ Dictionary enum_dict;
+ for (int j = 0; j < m.m_enum->values.size(); j++) {
+ enum_dict[m.m_enum->values[j].identifier->name] = m.m_enum->values[j].value;
+ }
+
+ Dictionary api;
+ api["name"] = m.m_enum->identifier->name;
+ api["value"] = enum_dict;
+ api["data_type"] = m.get_datatype().to_string();
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.m_enum->start_line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ constants.push_back(api);
+ } break;
+ case ClassNode::Member::VARIABLE: {
+ Dictionary api;
+ api["name"] = m.variable->identifier->name;
+ api["data_type"] = m.variable->get_datatype().to_string();
+ api["default_value"] = m.variable->initializer != nullptr ? m.variable->initializer->reduced_value : Variant();
+ api["setter"] = m.variable->setter ? ("@" + String(m.variable->identifier->name) + "_setter") : (m.variable->setter_pointer != nullptr ? String(m.variable->setter_pointer->name) : String());
+ api["getter"] = m.variable->getter ? ("@" + String(m.variable->identifier->name) + "_getter") : (m.variable->getter_pointer != nullptr ? String(m.variable->getter_pointer->name) : String());
+ api["export"] = m.variable->exported;
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.variable->start_line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ members.push_back(api);
+ } break;
+ case ClassNode::Member::SIGNAL: {
+ Dictionary api;
+ api["name"] = m.signal->identifier->name;
+ Array pars;
+ for (int j = 0; j < m.signal->parameters.size(); j++) {
+ pars.append(String(m.signal->parameters[i]->identifier->name));
+ }
+ api["arguments"] = pars;
+ if (const lsp::DocumentSymbol *symbol = get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(m.signal->start_line))) {
+ api["signature"] = symbol->detail;
+ api["description"] = symbol->documentation;
+ }
+ signals.push_back(api);
+ } break;
+ case ClassNode::Member::FUNCTION: {
+ if (m.function->is_static) {
+ static_functions.append(dump_function_api(m.function));
+ } else {
+ methods.append(dump_function_api(m.function));
+ }
+ } break;
+ case ClassNode::Member::UNDEFINED:
+ break; // Unreachable.
}
- signals.push_back(api);
}
- class_api["signals"] = signals;
- Array methods;
- for (int i = 0; i < p_class->functions.size(); ++i) {
- methods.append(dump_function_api(p_class->functions[i]));
- }
+ class_api["sub_classes"] = nested_classes;
+ class_api["constants"] = constants;
+ class_api["members"] = members;
+ class_api["signals"] = signals;
class_api["methods"] = methods;
-
- Array static_functions;
- for (int i = 0; i < p_class->static_functions.size(); ++i) {
- static_functions.append(dump_function_api(p_class->static_functions[i]));
- }
class_api["static_functions"] = static_functions;
return class_api;
}
Dictionary ExtendGDScriptParser::generate_api() const {
-
Dictionary api;
- const GDScriptParser::Node *head = get_parse_tree();
+ const GDScriptParser::Node *head = get_tree();
if (const GDScriptParser::ClassNode *gdclass = dynamic_cast<const GDScriptParser::ClassNode *>(head)) {
api = dump_class_api(gdclass);
}
@@ -778,7 +800,11 @@ Error ExtendGDScriptParser::parse(const String &p_code, const String &p_path) {
path = p_path;
lines = p_code.split("\n");
- Error err = GDScriptParser::parse(p_code, p_path.get_base_dir(), false, p_path, false, nullptr, false);
+ Error err = GDScriptParser::parse(p_code, p_path, false);
+ if (err == OK) {
+ GDScriptAnalyzer analyzer(this);
+ err = analyzer.analyze();
+ }
update_diagnostics();
update_symbols();
update_document_links(p_code);
diff --git a/modules/gdscript/language_server/gdscript_extend_parser.h b/modules/gdscript/language_server/gdscript_extend_parser.h
index 43dfce994b..28b9b3c82a 100644
--- a/modules/gdscript/language_server/gdscript_extend_parser.h
+++ b/modules/gdscript/language_server/gdscript_extend_parser.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define GDSCRIPT_EXTEND_PARSER_H
#include "../gdscript_parser.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#include "lsp.hpp"
#ifndef LINE_NUMBER_TO_INDEX
@@ -50,7 +50,6 @@
typedef HashMap<String, const lsp::DocumentSymbol *> ClassMembers;
class ExtendGDScriptParser : public GDScriptParser {
-
String path;
Vector<String> lines;
diff --git a/modules/gdscript/language_server/gdscript_language_protocol.cpp b/modules/gdscript/language_server/gdscript_language_protocol.cpp
index 69662e96f7..5e3d6213d3 100644
--- a/modules/gdscript/language_server/gdscript_language_protocol.cpp
+++ b/modules/gdscript/language_server/gdscript_language_protocol.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,9 +29,11 @@
/*************************************************************************/
#include "gdscript_language_protocol.h"
+
+#include "core/config/project_settings.h"
#include "core/io/json.h"
#include "core/os/copymem.h"
-#include "core/project_settings.h"
+#include "editor/doc_tools.h"
#include "editor/editor_log.h"
#include "editor/editor_node.h"
@@ -47,10 +49,11 @@ Error GDScriptLanguageProtocol::LSPeer::handle_data() {
ERR_FAIL_COND_V_MSG(true, ERR_OUT_OF_MEMORY, "Response header too big");
}
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
- if (err != OK)
+ if (err != OK) {
return FAILED;
- else if (read != 1) // Busy, wait until next poll
+ } else if (read != 1) { // Busy, wait until next poll
return ERR_BUSY;
+ }
char *r = (char *)req_buf;
int l = req_pos;
@@ -75,10 +78,11 @@ Error GDScriptLanguageProtocol::LSPeer::handle_data() {
ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
}
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
- if (err != OK)
+ if (err != OK) {
return FAILED;
- else if (read != 1)
+ } else if (read != 1) {
return ERR_BUSY;
+ }
req_pos++;
}
@@ -92,7 +96,7 @@ Error GDScriptLanguageProtocol::LSPeer::handle_data() {
// Response
String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
- if (!output.empty()) {
+ if (!output.is_empty()) {
res_queue.push_back(output.utf8());
}
}
@@ -101,7 +105,7 @@ Error GDScriptLanguageProtocol::LSPeer::handle_data() {
Error GDScriptLanguageProtocol::LSPeer::send_data() {
int sent = 0;
- if (!res_queue.empty()) {
+ if (!res_queue.is_empty()) {
CharString c_res = res_queue[0];
if (res_sent < c_res.size()) {
Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
@@ -137,7 +141,7 @@ void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
String GDScriptLanguageProtocol::process_message(const String &p_text) {
String ret = process_string(p_text);
- if (ret.empty()) {
+ if (ret.is_empty()) {
return ret;
} else {
return format_output(ret);
@@ -145,7 +149,6 @@ String GDScriptLanguageProtocol::process_message(const String &p_text) {
}
String GDScriptLanguageProtocol::format_output(const String &p_text) {
-
String header = "Content-Length: ";
CharString charstr = p_text.utf8();
size_t len = charstr.length();
@@ -160,7 +163,7 @@ void GDScriptLanguageProtocol::_bind_methods() {
ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
- ClassDB::bind_method(D_METHOD("notify_client", "p_method", "p_params"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("notify_client", "method", "params"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
@@ -168,7 +171,6 @@ void GDScriptLanguageProtocol::_bind_methods() {
}
Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
-
lsp::InitializeResult ret;
String root_uri = p_params["rootUri"];
@@ -183,13 +185,14 @@ Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
if (root_uri.length() && is_same_workspace) {
workspace->root_uri = root_uri;
} else {
-
workspace->root_uri = "file://" + workspace->root;
Dictionary params;
params["path"] = workspace->root;
- Dictionary request = make_notification("gdscrip_client/changeWorkspace", params);
+ Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
+ ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
+ vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
Ref<LSPeer> peer = clients.get(latest_client_id);
if (peer != nullptr) {
String msg = JSON::print(request);
@@ -208,12 +211,10 @@ Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
}
void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
-
lsp::GodotCapabilities capabilities;
- DocData *doc = EditorHelp::get_doc_data();
+ DocTools *doc = EditorHelp::get_doc_data();
for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
-
lsp::GodotNativeClassInfo gdclass;
gdclass.name = E->get().name;
gdclass.class_doc = &(E->get());
@@ -271,8 +272,11 @@ void GDScriptLanguageProtocol::stop() {
void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
if (p_client_id == -1) {
+ ERR_FAIL_COND_MSG(latest_client_id == -1,
+ "GDScript LSP: Can't notify client as none was connected.");
p_client_id = latest_client_id;
}
+ ERR_FAIL_COND(!clients.has(p_client_id));
Ref<LSPeer> peer = clients.get(p_client_id);
ERR_FAIL_COND(peer == nullptr);
@@ -293,13 +297,10 @@ bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
server.instance();
singleton = this;
- _initialized = false;
workspace.instance();
text_document.instance();
set_scope("textDocument", text_document.ptr());
set_scope("completionItem", text_document.ptr());
set_scope("workspace", workspace.ptr());
workspace->root = ProjectSettings::get_singleton()->get_resource_path();
- latest_client_id = 0;
- next_client_id = 0;
}
diff --git a/modules/gdscript/language_server/gdscript_language_protocol.h b/modules/gdscript/language_server/gdscript_language_protocol.h
index d929fd255d..8b08ae0655 100644
--- a/modules/gdscript/language_server/gdscript_language_protocol.h
+++ b/modules/gdscript/language_server/gdscript_language_protocol.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -70,8 +70,8 @@ private:
HashMap<int, Ref<LSPeer>> clients;
Ref<TCP_Server> server;
- int latest_client_id;
- int next_client_id;
+ int latest_client_id = 0;
+ int next_client_id = 0;
Ref<GDScriptTextDocument> text_document;
Ref<GDScriptWorkspace> workspace;
@@ -82,7 +82,7 @@ private:
String process_message(const String &p_text);
String format_output(const String &p_text);
- bool _initialized;
+ bool _initialized = false;
protected:
static void _bind_methods();
diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp
index e1d86ecdd4..aac9cb7fd7 100644
--- a/modules/gdscript/language_server/gdscript_language_server.cpp
+++ b/modules/gdscript/language_server/gdscript_language_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "gdscript_language_server.h"
+
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "editor/editor_log.h"
@@ -48,7 +49,6 @@ GDScriptLanguageServer::GDScriptLanguageServer() {
}
void GDScriptLanguageServer::_notification(int p_what) {
-
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
start();
diff --git a/modules/gdscript/language_server/gdscript_language_server.h b/modules/gdscript/language_server/gdscript_language_server.h
index 228d29bf42..218f42199e 100644
--- a/modules/gdscript/language_server/gdscript_language_server.h
+++ b/modules/gdscript/language_server/gdscript_language_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp
index f065b33570..9f2373bf56 100644
--- a/modules/gdscript/language_server/gdscript_text_document.cpp
+++ b/modules/gdscript/language_server/gdscript_text_document.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,6 +29,7 @@
/*************************************************************************/
#include "gdscript_text_document.h"
+
#include "../gdscript.h"
#include "core/os/os.h"
#include "editor/editor_settings.h"
@@ -85,19 +86,15 @@ void GDScriptTextDocument::notify_client_show_symbol(const lsp::DocumentSymbol *
}
void GDScriptTextDocument::initialize() {
-
if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
-
const HashMap<StringName, ClassMembers> &native_members = GDScriptLanguageProtocol::get_singleton()->get_workspace()->native_members;
const StringName *class_ptr = native_members.next(nullptr);
while (class_ptr) {
-
const ClassMembers &members = native_members.get(*class_ptr);
const String *name = members.next(nullptr);
while (name) {
-
const lsp::DocumentSymbol *symbol = members.get(*name);
lsp::CompletionItem item = symbol->make_completion_item();
item.data = JOIN_SYMBOLS(String(*class_ptr), *name);
@@ -112,7 +109,6 @@ void GDScriptTextDocument::initialize() {
}
Variant GDScriptTextDocument::nativeSymbol(const Dictionary &p_params) {
-
Variant ret;
lsp::NativeSymbolInspectParams params;
@@ -142,7 +138,6 @@ Array GDScriptTextDocument::documentSymbol(const Dictionary &p_params) {
}
Array GDScriptTextDocument::completion(const Dictionary &p_params) {
-
Array arr;
lsp::CompletionParams params;
@@ -152,13 +147,11 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) {
List<ScriptCodeCompletionOption> options;
GDScriptLanguageProtocol::get_singleton()->get_workspace()->completion(params, &options);
- if (!options.empty()) {
-
+ if (!options.is_empty()) {
int i = 0;
arr.resize(options.size());
for (const List<ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) {
-
const ScriptCodeCompletionOption &option = E->get();
lsp::CompletionItem item;
item.label = option.display;
@@ -201,11 +194,9 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) {
i++;
}
} else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
-
arr = native_member_completions.duplicate();
for (Map<String, ExtendGDScriptParser *>::Element *E = GDScriptLanguageProtocol::get_singleton()->get_workspace()->scripts.front(); E; E = E->next()) {
-
ExtendGDScriptParser *script = E->get();
const Array &items = script->get_member_completions();
@@ -220,7 +211,6 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) {
}
Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
-
lsp::CompletionItem item;
item.load(p_params);
@@ -230,18 +220,15 @@ Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
const lsp::DocumentSymbol *symbol = nullptr;
if (data.get_type() == Variant::DICTIONARY) {
-
params.load(p_params["data"]);
symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params, item.label, item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function);
} else if (data.get_type() == Variant::STRING) {
-
String query = data;
Vector<String> param_symbols = query.split(SYMBOL_SEPERATOR, false);
if (param_symbols.size() >= 2) {
-
String class_ = param_symbols[0];
StringName class_name = class_;
String member_name = param_symbols[param_symbols.size() - 1];
@@ -270,7 +257,7 @@ Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) {
if ((item.kind == lsp::CompletionItemKind::Method || item.kind == lsp::CompletionItemKind::Function) && !item.label.ends_with("):")) {
item.insertText = item.label + "(";
- if (symbol && symbol->children.empty()) {
+ if (symbol && symbol->children.is_empty()) {
item.insertText += ")";
}
} else if (item.kind == lsp::CompletionItemKind::Event) {
@@ -313,13 +300,11 @@ Array GDScriptTextDocument::colorPresentation(const Dictionary &p_params) {
}
Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
-
lsp::TextDocumentPositionParams params;
params.load(p_params);
const lsp::DocumentSymbol *symbol = GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_symbol(params);
if (symbol) {
-
lsp::Hover hover;
hover.contents = symbol->render();
hover.range.start = params.position;
@@ -327,7 +312,6 @@ Variant GDScriptTextDocument::hover(const Dictionary &p_params) {
return hover.to_json();
} else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
-
Dictionary ret;
Array contents;
List<const lsp::DocumentSymbol *> list;
@@ -357,7 +341,7 @@ Variant GDScriptTextDocument::declaration(const Dictionary &p_params) {
params.load(p_params);
List<const lsp::DocumentSymbol *> symbols;
Array arr = this->find_symbols(params, symbols);
- if (arr.empty() && !symbols.empty() && !symbols.front()->get()->native_class.empty()) { // Find a native symbol
+ if (arr.is_empty() && !symbols.is_empty() && !symbols.front()->get()->native_class.is_empty()) { // Find a native symbol
const lsp::DocumentSymbol *symbol = symbols.front()->get();
if (GDScriptLanguageProtocol::get_singleton()->is_goto_native_symbols_enabled()) {
String id;
@@ -441,7 +425,7 @@ Array GDScriptTextDocument::find_symbols(const lsp::TextDocumentPositionParams &
GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(p_location, list);
for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) {
if (const lsp::DocumentSymbol *s = E->get()) {
- if (!s->uri.empty()) {
+ if (!s->uri.is_empty()) {
lsp::Location location;
location.uri = s->uri;
location.range = s->range;
diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h
index b2fd0c31f9..792e601bc1 100644
--- a/modules/gdscript/language_server/gdscript_text_document.h
+++ b/modules/gdscript/language_server/gdscript_text_document.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef GDSCRIPT_TEXT_DOCUMENT_H
#define GDSCRIPT_TEXT_DOCUMENT_H
+#include "core/object/reference.h"
#include "core/os/file_access.h"
-#include "core/reference.h"
#include "lsp.hpp"
class GDScriptTextDocument : public Reference {
diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp
index 32fc8f36f0..7b502f079b 100644
--- a/modules/gdscript/language_server/gdscript_workspace.cpp
+++ b/modules/gdscript/language_server/gdscript_workspace.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,10 +29,12 @@
/*************************************************************************/
#include "gdscript_workspace.h"
+
#include "../gdscript.h"
#include "../gdscript_parser.h"
-#include "core/project_settings.h"
-#include "core/script_language.h"
+#include "core/config/project_settings.h"
+#include "core/object/script_language.h"
+#include "editor/doc_tools.h"
#include "editor/editor_file_system.h"
#include "editor/editor_help.h"
#include "editor/editor_node.h"
@@ -41,12 +43,12 @@
void GDScriptWorkspace::_bind_methods() {
ClassDB::bind_method(D_METHOD("symbol"), &GDScriptWorkspace::symbol);
- ClassDB::bind_method(D_METHOD("parse_script", "p_path", "p_content"), &GDScriptWorkspace::parse_script);
- ClassDB::bind_method(D_METHOD("parse_local_script", "p_path"), &GDScriptWorkspace::parse_local_script);
- ClassDB::bind_method(D_METHOD("get_file_path", "p_uri"), &GDScriptWorkspace::get_file_path);
- ClassDB::bind_method(D_METHOD("get_file_uri", "p_path"), &GDScriptWorkspace::get_file_uri);
- ClassDB::bind_method(D_METHOD("publish_diagnostics", "p_path"), &GDScriptWorkspace::publish_diagnostics);
- ClassDB::bind_method(D_METHOD("generate_script_api", "p_path"), &GDScriptWorkspace::generate_script_api);
+ ClassDB::bind_method(D_METHOD("parse_script", "path", "content"), &GDScriptWorkspace::parse_script);
+ ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_local_script);
+ ClassDB::bind_method(D_METHOD("get_file_path", "uri"), &GDScriptWorkspace::get_file_path);
+ ClassDB::bind_method(D_METHOD("get_file_uri", "path"), &GDScriptWorkspace::get_file_uri);
+ ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
+ ClassDB::bind_method(D_METHOD("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api);
}
void GDScriptWorkspace::remove_cache_parser(const String &p_path) {
@@ -71,7 +73,6 @@ void GDScriptWorkspace::remove_cache_parser(const String &p_path) {
}
const lsp::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
-
StringName class_name = p_class;
StringName empty;
@@ -79,7 +80,7 @@ const lsp::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_
if (const Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(class_name)) {
const lsp::DocumentSymbol &class_symbol = E->value();
- if (p_member.empty()) {
+ if (p_member.is_empty()) {
return &class_symbol;
} else {
for (int i = 0; i < class_symbol.children.size(); i++) {
@@ -118,7 +119,7 @@ void GDScriptWorkspace::reload_all_workspace_scripts() {
Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(path);
String err_msg = "Failed parse script " + path;
if (S) {
- err_msg += "\n" + S->get()->get_error();
+ err_msg += "\n" + S->get()->get_errors()[0].message;
}
ERR_CONTINUE_MSG(err != OK, err_msg);
}
@@ -170,7 +171,7 @@ ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path)
Array GDScriptWorkspace::symbol(const Dictionary &p_params) {
String query = p_params["query"];
Array arr;
- if (!query.empty()) {
+ if (!query.is_empty()) {
for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
Vector<lsp::DocumentedSymbolInformation> script_symbols;
E->get()->get_symbols().symbol_tree_as_list(E->key(), script_symbols);
@@ -185,11 +186,12 @@ Array GDScriptWorkspace::symbol(const Dictionary &p_params) {
}
Error GDScriptWorkspace::initialize() {
- if (initialized) return OK;
+ if (initialized) {
+ return OK;
+ }
- DocData *doc = EditorHelp::get_doc_data();
+ DocTools *doc = EditorHelp::get_doc_data();
for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
-
const DocData::ClassDoc &class_data = E->value();
lsp::DocumentSymbol class_symbol;
String class_name = E->key();
@@ -197,7 +199,7 @@ Error GDScriptWorkspace::initialize() {
class_symbol.native_class = class_name;
class_symbol.kind = lsp::SymbolKind::Class;
class_symbol.detail = String("<Native> class ") + class_name;
- if (!class_data.inherits.empty()) {
+ if (!class_data.inherits.is_empty()) {
class_symbol.detail += " extends " + class_data.inherits;
}
class_symbol.documentation = class_data.brief_description + "\n" + class_data.description;
@@ -261,7 +263,7 @@ Error GDScriptWorkspace::initialize() {
symbol_arg.kind = lsp::SymbolKind::Variable;
symbol_arg.detail = arg.type;
- if (!arg_default_value_started && !arg.default_value.empty()) {
+ if (!arg_default_value_started && !arg.default_value.is_empty()) {
arg_default_value_started = true;
}
String arg_str = arg.name + ": " + arg.type;
@@ -276,11 +278,11 @@ Error GDScriptWorkspace::initialize() {
symbol.children.push_back(symbol_arg);
}
if (data.qualifiers.find("vararg") != -1) {
- params += params.empty() ? "..." : ", ...";
+ params += params.is_empty() ? "..." : ", ...";
}
String return_type = data.return_type;
- if (return_type.empty()) {
+ if (return_type.is_empty()) {
return_type = "void";
}
symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
@@ -314,14 +316,12 @@ Error GDScriptWorkspace::initialize() {
}
Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
-
ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
Error err = parser->parse(p_content, p_path);
Map<String, ExtendGDScriptParser *>::Element *last_parser = parse_results.find(p_path);
Map<String, ExtendGDScriptParser *>::Element *last_script = scripts.find(p_path);
if (err == OK) {
-
remove_cache_parser(p_path);
parse_results[p_path] = parser;
scripts[p_path] = parser;
@@ -377,15 +377,15 @@ void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
}
void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
- if (!efsd)
+ if (!efsd) {
return;
+ }
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_get_owners(efsd->get_subdir(i), p_path, owners);
}
for (int i = 0; i < efsd->get_file_count(); i++) {
-
Vector<String> deps = efsd->get_file_deps(i);
bool found = false;
for (int j = 0; j < deps.size(); j++) {
@@ -394,8 +394,9 @@ void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_pa
break;
}
}
- if (!found)
+ if (!found) {
continue;
+ }
owners.push_back(efsd->get_file_path(i));
}
@@ -421,7 +422,6 @@ Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
}
void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options) {
-
String path = get_file_path(p_params.textDocument.uri);
String call_hint;
bool forced = false;
@@ -437,12 +437,10 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S
}
const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_requred) {
-
const lsp::DocumentSymbol *symbol = nullptr;
String path = get_file_path(p_doc_pos.textDocument.uri);
if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
-
String symbol_identifier = p_symbol_name;
Vector<String> identifier_parts = symbol_identifier.split("(");
if (identifier_parts.size()) {
@@ -450,26 +448,21 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocu
}
lsp::Position pos = p_doc_pos.position;
- if (symbol_identifier.empty()) {
+ if (symbol_identifier.is_empty()) {
Vector2i offset;
symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
pos.character += offset.y;
}
- if (!symbol_identifier.empty()) {
-
+ if (!symbol_identifier.is_empty()) {
if (ScriptServer::is_global_class(symbol_identifier)) {
-
String class_path = ScriptServer::get_global_class_path(symbol_identifier);
symbol = get_script_symbol(class_path);
} else {
-
ScriptLanguage::LookupResult ret;
if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_requred), symbol_identifier, path, nullptr, ret)) {
-
if (ret.type == ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION) {
-
String target_script_path = path;
if (!ret.script.is_null()) {
target_script_path = ret.script->get_path();
@@ -480,9 +473,8 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocu
}
} else {
-
String member = ret.class_member;
- if (member.empty() && symbol_identifier != ret.class_name) {
+ if (member.is_empty() && symbol_identifier != ret.class_name) {
member = symbol_identifier;
}
symbol = get_native_symbol(ret.class_name, member);
@@ -498,10 +490,8 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocu
}
void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list) {
-
String path = get_file_path(p_doc_pos.textDocument.uri);
if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
-
String symbol_identifier;
Vector2i offset;
symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
@@ -525,7 +515,6 @@ void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionP
const HashMap<String, ClassMembers> &inner_classes = script->get_inner_classes();
const String *_class = inner_classes.next(nullptr);
while (_class) {
-
const ClassMembers *inner_class = inner_classes.getptr(*_class);
if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
r_list.push_back(*symbol);
@@ -538,10 +527,9 @@ void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionP
}
const lsp::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const lsp::NativeSymbolInspectParams &p_params) {
-
if (Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(p_params.native_class)) {
const lsp::DocumentSymbol &symbol = E->get();
- if (p_params.symbol_name.empty() || p_params.symbol_name == symbol.name) {
+ if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
return &symbol;
}
@@ -574,12 +562,10 @@ Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
Error GDScriptWorkspace::resolve_signature(const lsp::TextDocumentPositionParams &p_doc_pos, lsp::SignatureHelp &r_signature) {
if (const ExtendGDScriptParser *parser = get_parse_result(get_file_path(p_doc_pos.textDocument.uri))) {
-
lsp::TextDocumentPositionParams text_pos;
text_pos.textDocument = p_doc_pos.textDocument;
if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
-
List<const lsp::DocumentSymbol *> symbols;
if (const lsp::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
@@ -591,7 +577,6 @@ Error GDScriptWorkspace::resolve_signature(const lsp::TextDocumentPositionParams
for (List<const lsp::DocumentSymbol *>::Element *E = symbols.front(); E; E = E->next()) {
const lsp::DocumentSymbol *symbol = E->get();
if (symbol->kind == lsp::SymbolKind::Method || symbol->kind == lsp::SymbolKind::Function) {
-
lsp::SignatureInformation signature_info;
signature_info.label = symbol->detail;
signature_info.documentation = symbol->render();
diff --git a/modules/gdscript/language_server/gdscript_workspace.h b/modules/gdscript/language_server/gdscript_workspace.h
index e45b06747d..7fd8bfcf20 100644
--- a/modules/gdscript/language_server/gdscript_workspace.h
+++ b/modules/gdscript/language_server/gdscript_workspace.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define GDSCRIPT_WORKSPACE_H
#include "../gdscript_parser.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#include "editor/editor_file_system.h"
#include "gdscript_extend_parser.h"
#include "lsp.hpp"
diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/lsp.hpp
index 124fcbfed8..6a913edbbf 100644
--- a/modules/gdscript/language_server/lsp.hpp
+++ b/modules/gdscript/language_server/lsp.hpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,9 +31,9 @@
#ifndef GODOT_LSP_H
#define GODOT_LSP_H
-#include "core/class_db.h"
-#include "core/list.h"
-#include "editor/doc_data.h"
+#include "core/doc_data.h"
+#include "core/object/class_db.h"
+#include "core/templates/list.h"
namespace lsp {
@@ -149,7 +149,6 @@ struct Location {
* Represents a link between a source and a target location.
*/
struct LocationLink {
-
/**
* Span of the origin of this link.
*
@@ -220,7 +219,6 @@ struct DocumentLinkParams {
* text document or a web site.
*/
struct DocumentLink {
-
/**
* The range this link applies to.
*/
@@ -282,7 +280,9 @@ struct Command {
Dictionary dict;
dict["title"] = title;
dict["command"] = command;
- if (arguments.size()) dict["arguments"] = arguments;
+ if (arguments.size()) {
+ dict["arguments"] = arguments;
+ }
return dict;
}
};
@@ -486,7 +486,7 @@ struct TextDocumentSyncOptions {
* If present save notifications are sent to the server. If omitted the notification should not be
* sent.
*/
- SaveOptions save;
+ bool save = false;
Dictionary to_json() {
Dictionary dict;
@@ -494,7 +494,7 @@ struct TextDocumentSyncOptions {
dict["willSave"] = willSave;
dict["openClose"] = openClose;
dict["change"] = change;
- dict["save"] = save.to_json();
+ dict["save"] = save;
return dict;
}
};
@@ -687,7 +687,7 @@ struct Diagnostic {
dict["severity"] = severity;
dict["message"] = message;
dict["source"] = source;
- if (!relatedInformation.empty()) {
+ if (!relatedInformation.is_empty()) {
Array arr;
arr.resize(relatedInformation.size());
for (int i = 0; i < relatedInformation.size(); i++) {
@@ -946,16 +946,24 @@ struct CompletionItem {
dict["preselect"] = preselect;
dict["sortText"] = sortText;
dict["filterText"] = filterText;
- if (commitCharacters.size()) dict["commitCharacters"] = commitCharacters;
+ if (commitCharacters.size()) {
+ dict["commitCharacters"] = commitCharacters;
+ }
dict["command"] = command.to_json();
}
return dict;
}
void load(const Dictionary &p_dict) {
- if (p_dict.has("label")) label = p_dict["label"];
- if (p_dict.has("kind")) kind = p_dict["kind"];
- if (p_dict.has("detail")) detail = p_dict["detail"];
+ if (p_dict.has("label")) {
+ label = p_dict["label"];
+ }
+ if (p_dict.has("kind")) {
+ kind = p_dict["kind"];
+ }
+ if (p_dict.has("detail")) {
+ detail = p_dict["detail"];
+ }
if (p_dict.has("documentation")) {
Variant doc = p_dict["documentation"];
if (doc.get_type() == Variant::STRING) {
@@ -965,12 +973,24 @@ struct CompletionItem {
documentation.value = v["value"];
}
}
- if (p_dict.has("deprecated")) deprecated = p_dict["deprecated"];
- if (p_dict.has("preselect")) preselect = p_dict["preselect"];
- if (p_dict.has("sortText")) sortText = p_dict["sortText"];
- if (p_dict.has("filterText")) filterText = p_dict["filterText"];
- if (p_dict.has("insertText")) insertText = p_dict["insertText"];
- if (p_dict.has("data")) data = p_dict["data"];
+ if (p_dict.has("deprecated")) {
+ deprecated = p_dict["deprecated"];
+ }
+ if (p_dict.has("preselect")) {
+ preselect = p_dict["preselect"];
+ }
+ if (p_dict.has("sortText")) {
+ sortText = p_dict["sortText"];
+ }
+ if (p_dict.has("filterText")) {
+ filterText = p_dict["filterText"];
+ }
+ if (p_dict.has("insertText")) {
+ insertText = p_dict["insertText"];
+ }
+ if (p_dict.has("data")) {
+ data = p_dict["data"];
+ }
}
};
@@ -1096,7 +1116,6 @@ struct DocumentedSymbolInformation : public SymbolInformation {
* e.g. the range of an identifier.
*/
struct DocumentSymbol {
-
/**
* The name of this symbol. Will be displayed in the user interface and therefore must not be
* an empty string or a string only consisting of white spaces.
@@ -1172,7 +1191,7 @@ struct DocumentSymbol {
void symbol_tree_as_list(const String &p_uri, Vector<DocumentedSymbolInformation> &r_list, const String &p_container = "", bool p_join_name = false) const {
DocumentedSymbolInformation si;
- if (p_join_name && !p_container.empty()) {
+ if (p_join_name && !p_container.is_empty()) {
si.name = p_container + ">" + name;
} else {
si.name = name;
@@ -1205,7 +1224,6 @@ struct DocumentSymbol {
}
_FORCE_INLINE_ CompletionItem make_completion_item(bool resolved = false) const {
-
lsp::CompletionItem item;
item.label = name;
@@ -1249,7 +1267,6 @@ struct DocumentSymbol {
};
struct NativeSymbolInspectParams {
-
String native_class;
String symbol_name;
@@ -1281,7 +1298,6 @@ static const String Region = "region";
* Represents a folding range.
*/
struct FoldingRange {
-
/**
* The zero-based line number from where the folded range starts.
*/
@@ -1364,7 +1380,6 @@ struct CompletionContext {
};
struct CompletionParams : public TextDocumentPositionParams {
-
/**
* The completion context. This is only available if the client specifies
* to send this using `ClientCapabilities.textDocument.completion.contextSupport === true`
@@ -1405,7 +1420,6 @@ struct Hover {
* have a label and a doc-comment.
*/
struct ParameterInformation {
-
/**
* The label of this parameter information.
*
@@ -1642,7 +1656,7 @@ struct ServerCapabilities {
_FORCE_INLINE_ Dictionary to_json() {
Dictionary dict;
- dict["textDocumentSync"] = (int)textDocumentSync.change;
+ dict["textDocumentSync"] = textDocumentSync.to_json();
dict["completionProvider"] = completionProvider.to_json();
signatureHelpProvider.triggerCharacters.push_back(",");
signatureHelpProvider.triggerCharacters.push_back("(");
@@ -1684,7 +1698,6 @@ struct InitializeResult {
};
struct GodotNativeClassInfo {
-
String name;
const DocData::ClassDoc *class_doc = nullptr;
const ClassDB::ClassInfo *class_info = nullptr;
@@ -1699,7 +1712,6 @@ struct GodotNativeClassInfo {
/** Features not included in the standard lsp specifications */
struct GodotCapabilities {
-
/**
* Native class list
*/
@@ -1718,7 +1730,6 @@ struct GodotCapabilities {
/** Format BBCode documentation from DocData to markdown */
static String marked_documentation(const String &p_bbcode) {
-
String markdown = p_bbcode.strip_edges();
Vector<String> lines = markdown.split("\n");
@@ -1770,7 +1781,6 @@ static String marked_documentation(const String &p_bbcode) {
}
return markdown;
}
-
} // namespace lsp
#endif
diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp
index 62b9d94d6c..e90475a60e 100644
--- a/modules/gdscript/register_types.cpp
+++ b/modules/gdscript/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,31 +35,42 @@
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "gdscript.h"
+#include "gdscript_analyzer.h"
+#include "gdscript_cache.h"
#include "gdscript_tokenizer.h"
+#include "gdscript_utility_functions.h"
+
+#ifdef TESTS_ENABLED
+#include "tests/test_gdscript.h"
+#include "tests/test_macros.h"
+#endif
GDScriptLanguage *script_language_gd = nullptr;
Ref<ResourceFormatLoaderGDScript> resource_loader_gd;
Ref<ResourceFormatSaverGDScript> resource_saver_gd;
+GDScriptCache *gdscript_cache = nullptr;
#ifdef TOOLS_ENABLED
#include "editor/editor_export.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/editor_translation_parser.h"
#include "editor/gdscript_highlighter.h"
+#include "editor/gdscript_translation_parser_plugin.h"
#ifndef GDSCRIPT_NO_LSP
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "language_server/gdscript_language_server.h"
#endif // !GDSCRIPT_NO_LSP
-class EditorExportGDScript : public EditorExportPlugin {
+Ref<GDScriptEditorTranslationParserPlugin> gdscript_translation_parser_plugin;
+class EditorExportGDScript : public EditorExportPlugin {
GDCLASS(EditorExportGDScript, EditorExportPlugin);
public:
- virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features) {
-
+ virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features) override {
int script_mode = EditorExportPreset::MODE_SCRIPT_COMPILED;
String script_key;
@@ -70,76 +81,26 @@ public:
script_key = preset->get_script_encryption_key().to_lower();
}
- if (!p_path.ends_with(".gd") || script_mode == EditorExportPreset::MODE_SCRIPT_TEXT)
+ if (!p_path.ends_with(".gd") || script_mode == EditorExportPreset::MODE_SCRIPT_TEXT) {
return;
-
- Vector<uint8_t> file = FileAccess::get_file_as_array(p_path);
- if (file.empty())
- return;
-
- String txt;
- txt.parse_utf8((const char *)file.ptr(), file.size());
- file = GDScriptTokenizerBuffer::parse_code_string(txt);
-
- if (!file.empty()) {
-
- if (script_mode == EditorExportPreset::MODE_SCRIPT_ENCRYPTED) {
-
- String tmp_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("script.gde");
- FileAccess *fa = FileAccess::open(tmp_path, FileAccess::WRITE);
-
- Vector<uint8_t> key;
- key.resize(32);
- for (int i = 0; i < 32; i++) {
- int v = 0;
- if (i * 2 < script_key.length()) {
- CharType ct = script_key[i * 2];
- if (ct >= '0' && ct <= '9')
- ct = ct - '0';
- else if (ct >= 'a' && ct <= 'f')
- ct = 10 + ct - 'a';
- v |= ct << 4;
- }
-
- if (i * 2 + 1 < script_key.length()) {
- CharType ct = script_key[i * 2 + 1];
- if (ct >= '0' && ct <= '9')
- ct = ct - '0';
- else if (ct >= 'a' && ct <= 'f')
- ct = 10 + ct - 'a';
- v |= ct;
- }
- key.write[i] = v;
- }
- FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
- Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_WRITE_AES256);
-
- if (err == OK) {
- fae->store_buffer(file.ptr(), file.size());
- }
-
- memdelete(fae);
-
- file = FileAccess::get_file_as_array(tmp_path);
- add_file(p_path.get_basename() + ".gde", file, true);
-
- // Clean up temporary file.
- DirAccess::remove_file_or_error(tmp_path);
-
- } else {
-
- add_file(p_path.get_basename() + ".gdc", file, true);
- }
}
+
+ // TODO: Readd compiled GDScript on export.
+ return;
}
};
static void _editor_init() {
-
Ref<EditorExportGDScript> gd_export;
gd_export.instance();
EditorExport::get_singleton()->add_export_plugin(gd_export);
+#ifdef TOOLS_ENABLED
+ Ref<GDScriptSyntaxHighlighter> gdscript_syntax_highlighter;
+ gdscript_syntax_highlighter.instance();
+ ScriptEditor::get_singleton()->register_syntax_highlighter(gdscript_syntax_highlighter);
+#endif
+
#ifndef GDSCRIPT_NO_LSP
register_lsp_types();
GDScriptLanguageServer *lsp_plugin = memnew(GDScriptLanguageServer);
@@ -151,9 +112,7 @@ static void _editor_init() {
#endif // TOOLS_ENABLED
void register_gdscript_types() {
-
ClassDB::register_class<GDScript>();
- ClassDB::register_virtual_class<GDScriptFunctionState>();
script_language_gd = memnew(GDScriptLanguage);
ScriptServer::register_language(script_language_gd);
@@ -164,22 +123,64 @@ void register_gdscript_types() {
resource_saver_gd.instance();
ResourceSaver::add_resource_format_saver(resource_saver_gd);
+ gdscript_cache = memnew(GDScriptCache);
+
#ifdef TOOLS_ENABLED
- ScriptEditor::register_create_syntax_highlighter_function(GDScriptSyntaxHighlighter::create);
EditorNode::add_init_callback(_editor_init);
+
+ gdscript_translation_parser_plugin.instance();
+ EditorTranslationParser::get_singleton()->add_parser(gdscript_translation_parser_plugin, EditorTranslationParser::STANDARD);
#endif // TOOLS_ENABLED
+
+ GDScriptUtilityFunctions::register_functions();
}
void unregister_gdscript_types() {
-
ScriptServer::unregister_language(script_language_gd);
- if (script_language_gd)
+ if (gdscript_cache) {
+ memdelete(gdscript_cache);
+ }
+
+ if (script_language_gd) {
memdelete(script_language_gd);
+ }
ResourceLoader::remove_resource_format_loader(resource_loader_gd);
resource_loader_gd.unref();
ResourceSaver::remove_resource_format_saver(resource_saver_gd);
resource_saver_gd.unref();
+
+#ifdef TOOLS_ENABLED
+ EditorTranslationParser::get_singleton()->remove_parser(gdscript_translation_parser_plugin, EditorTranslationParser::STANDARD);
+ gdscript_translation_parser_plugin.unref();
+#endif // TOOLS_ENABLED
+
+ GDScriptParser::cleanup();
+ GDScriptAnalyzer::cleanup();
+ GDScriptUtilityFunctions::unregister_functions();
+}
+
+#ifdef TESTS_ENABLED
+void test_tokenizer() {
+ TestGDScript::test(TestGDScript::TestType::TEST_TOKENIZER);
+}
+
+void test_parser() {
+ TestGDScript::test(TestGDScript::TestType::TEST_PARSER);
+}
+
+void test_compiler() {
+ TestGDScript::test(TestGDScript::TestType::TEST_COMPILER);
+}
+
+void test_bytecode() {
+ TestGDScript::test(TestGDScript::TestType::TEST_BYTECODE);
}
+
+REGISTER_TEST_COMMAND("gdscript-tokenizer", &test_tokenizer);
+REGISTER_TEST_COMMAND("gdscript-parser", &test_parser);
+REGISTER_TEST_COMMAND("gdscript-compiler", &test_compiler);
+REGISTER_TEST_COMMAND("gdscript-bytecode", &test_bytecode);
+#endif
diff --git a/modules/gdscript/register_types.h b/modules/gdscript/register_types.h
index 18e57c1211..ce1c03d1d0 100644
--- a/modules/gdscript/register_types.h
+++ b/modules/gdscript/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gdscript/tests/test_gdscript.cpp b/modules/gdscript/tests/test_gdscript.cpp
new file mode 100644
index 0000000000..898ac653f5
--- /dev/null
+++ b/modules/gdscript/tests/test_gdscript.cpp
@@ -0,0 +1,306 @@
+/*************************************************************************/
+/* test_gdscript.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "test_gdscript.h"
+
+#include "core/config/project_settings.h"
+#include "core/io/file_access_pack.h"
+#include "core/os/file_access.h"
+#include "core/os/main_loop.h"
+#include "core/os/os.h"
+#include "core/string/string_builder.h"
+#include "scene/resources/packed_scene.h"
+
+#include "modules/gdscript/gdscript_analyzer.h"
+#include "modules/gdscript/gdscript_compiler.h"
+#include "modules/gdscript/gdscript_parser.h"
+#include "modules/gdscript/gdscript_tokenizer.h"
+
+#ifdef TOOLS_ENABLED
+#include "editor/editor_settings.h"
+#endif
+
+namespace TestGDScript {
+
+static void test_tokenizer(const String &p_code, const Vector<String> &p_lines) {
+ GDScriptTokenizer tokenizer;
+ tokenizer.set_source_code(p_code);
+
+ int tab_size = 4;
+#ifdef TOOLS_ENABLED
+ if (EditorSettings::get_singleton()) {
+ tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
+ }
+#endif // TOOLS_ENABLED
+ String tab = String(" ").repeat(tab_size);
+
+ GDScriptTokenizer::Token current = tokenizer.scan();
+ while (current.type != GDScriptTokenizer::Token::TK_EOF) {
+ StringBuilder token;
+ token += " --> "; // Padding for line number.
+
+ for (int l = current.start_line; l <= current.end_line; l++) {
+ print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab));
+ }
+
+ {
+ // Print carets to point at the token.
+ StringBuilder pointer;
+ pointer += " "; // Padding for line number.
+ int rightmost_column = current.rightmost_column;
+ if (current.end_line > current.start_line) {
+ rightmost_column--; // Don't point to the newline as a column.
+ }
+ for (int col = 1; col < rightmost_column; col++) {
+ if (col < current.leftmost_column) {
+ pointer += " ";
+ } else {
+ pointer += "^";
+ }
+ }
+ print_line(pointer.as_string());
+ }
+
+ token += current.get_name();
+
+ if (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::LITERAL || current.type == GDScriptTokenizer::Token::IDENTIFIER || current.type == GDScriptTokenizer::Token::ANNOTATION) {
+ token += "(";
+ token += Variant::get_type_name(current.literal.get_type());
+ token += ") ";
+ token += current.literal;
+ }
+
+ print_line(token.as_string());
+
+ print_line("-------------------------------------------------------");
+
+ current = tokenizer.scan();
+ }
+
+ print_line(current.get_name()); // Should be EOF
+}
+
+static void test_parser(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
+ GDScriptParser parser;
+ Error err = parser.parse(p_code, p_script_path, false);
+
+ if (err != OK) {
+ const List<GDScriptParser::ParserError> &errors = parser.get_errors();
+ for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
+ const GDScriptParser::ParserError &error = E->get();
+ print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
+ }
+ }
+
+ GDScriptParser::TreePrinter printer;
+
+ printer.print_tree(parser);
+}
+
+static void test_compiler(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
+ GDScriptParser parser;
+ Error err = parser.parse(p_code, p_script_path, false);
+
+ if (err != OK) {
+ print_line("Error in parser:");
+ const List<GDScriptParser::ParserError> &errors = parser.get_errors();
+ for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
+ const GDScriptParser::ParserError &error = E->get();
+ print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
+ }
+ return;
+ }
+
+ GDScriptAnalyzer analyzer(&parser);
+ err = analyzer.analyze();
+
+ if (err != OK) {
+ print_line("Error in analyzer:");
+ const List<GDScriptParser::ParserError> &errors = parser.get_errors();
+ for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
+ const GDScriptParser::ParserError &error = E->get();
+ print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
+ }
+ return;
+ }
+
+ GDScriptCompiler compiler;
+ Ref<GDScript> script;
+ script.instance();
+ script->set_path(p_script_path);
+
+ err = compiler.compile(&parser, script.ptr(), false);
+
+ if (err) {
+ print_line("Error in compiler:");
+ print_line(vformat("%02d:%02d: %s", compiler.get_error_line(), compiler.get_error_column(), compiler.get_error()));
+ return;
+ }
+
+ for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) {
+ const GDScriptFunction *func = E->value();
+
+ String signature = "Disassembling " + func->get_name().operator String() + "(";
+ for (int i = 0; i < func->get_argument_count(); i++) {
+ if (i > 0) {
+ signature += ", ";
+ }
+ signature += func->get_argument_name(i);
+ }
+ print_line(signature + ")");
+
+ func->disassemble(p_lines);
+ print_line("");
+ print_line("");
+ }
+}
+
+void init_autoloads() {
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+
+ // First pass, add the constants so they exist before any script is loaded.
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ const ProjectSettings::AutoloadInfo &info = E->get();
+
+ if (info.is_singleton) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
+ }
+ }
+ }
+
+ // Second pass, load into global constants.
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ const ProjectSettings::AutoloadInfo &info = E->get();
+
+ if (!info.is_singleton) {
+ // Skip non-singletons since we don't have a scene tree here anyway.
+ continue;
+ }
+
+ RES res = ResourceLoader::load(info.path);
+ ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
+ Node *n = nullptr;
+ if (res->is_class("PackedScene")) {
+ Ref<PackedScene> ps = res;
+ n = ps->instance();
+ } else if (res->is_class("Script")) {
+ Ref<Script> script_res = res;
+ StringName ibt = script_res->get_instance_base_type();
+ bool valid_type = ClassDB::is_parent_class(ibt, "Node");
+ ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
+
+ Object *obj = ClassDB::instance(ibt);
+
+ ERR_CONTINUE_MSG(obj == nullptr,
+ "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
+ String(ibt));
+
+ n = Object::cast_to<Node>(obj);
+ n->set_script(script_res);
+ }
+
+ ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + info.path);
+ n->set_name(info.name);
+
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ScriptServer::get_language(i)->add_global_constant(info.name, n);
+ }
+ }
+}
+
+void test(TestType p_type) {
+ List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
+
+ if (cmdlargs.is_empty()) {
+ return;
+ }
+
+ String test = cmdlargs.back()->get();
+ if (!test.ends_with(".gd")) {
+ print_line("This test expects a path to a GDScript file as its last parameter. Got: " + test);
+ return;
+ }
+
+ FileAccessRef fa = FileAccess::open(test, FileAccess::READ);
+ ERR_FAIL_COND_MSG(!fa, "Could not open file: " + test);
+
+ // Init PackedData since it's used by ProjectSettings.
+ PackedData *packed_data = memnew(PackedData);
+
+ // Setup project settings since it's needed by the languages to get the global scripts.
+ // This also sets up the base resource path.
+ Error err = ProjectSettings::get_singleton()->setup(fa->get_path_absolute().get_base_dir(), String(), true);
+ if (err) {
+ print_line("Could not load project settings.");
+ // Keep going since some scripts still work without this.
+ }
+
+ // Initialize the language for the test routine.
+ ScriptServer::init_languages();
+ init_autoloads();
+
+ Vector<uint8_t> buf;
+ int flen = fa->get_len();
+ buf.resize(fa->get_len() + 1);
+ fa->get_buffer(buf.ptrw(), flen);
+ buf.write[flen] = 0;
+
+ String code;
+ code.parse_utf8((const char *)&buf[0]);
+
+ Vector<String> lines;
+ int last = 0;
+ for (int i = 0; i <= code.length(); i++) {
+ if (code[i] == '\n' || code[i] == 0) {
+ lines.push_back(code.substr(last, i - last));
+ last = i + 1;
+ }
+ }
+
+ switch (p_type) {
+ case TEST_TOKENIZER:
+ test_tokenizer(code, lines);
+ break;
+ case TEST_PARSER:
+ test_parser(code, test, lines);
+ break;
+ case TEST_COMPILER:
+ test_compiler(code, test, lines);
+ break;
+ case TEST_BYTECODE:
+ print_line("Not implemented.");
+ }
+
+ // Destroy stuff we set up earlier.
+ ScriptServer::finish_languages();
+ memdelete(packed_data);
+}
+} // namespace TestGDScript
diff --git a/modules/gdscript/tests/test_gdscript.h b/modules/gdscript/tests/test_gdscript.h
new file mode 100644
index 0000000000..bbda46cdad
--- /dev/null
+++ b/modules/gdscript/tests/test_gdscript.h
@@ -0,0 +1,46 @@
+/*************************************************************************/
+/* test_gdscript.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEST_GDSCRIPT_H
+#define TEST_GDSCRIPT_H
+
+namespace TestGDScript {
+
+enum TestType {
+ TEST_TOKENIZER,
+ TEST_PARSER,
+ TEST_COMPILER,
+ TEST_BYTECODE,
+};
+
+void test(TestType p_type);
+} // namespace TestGDScript
+
+#endif // TEST_GDSCRIPT_H
diff --git a/modules/glslang/SCsub b/modules/glslang/SCsub
index c1d23a138b..182272ffc7 100644
--- a/modules/glslang/SCsub
+++ b/modules/glslang/SCsub
@@ -6,9 +6,13 @@ Import("env_modules")
env_glslang = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_glslang"]:
thirdparty_dir = "#thirdparty/glslang/"
thirdparty_sources = [
+ "glslang/CInterface/glslang_c_interface.cpp",
"glslang/MachineIndependent/RemoveTree.cpp",
"glslang/MachineIndependent/ParseHelper.cpp",
"glslang/MachineIndependent/iomapper.cpp",
@@ -30,7 +34,6 @@ if env["builtin_glslang"]:
"glslang/MachineIndependent/intermOut.cpp",
"glslang/MachineIndependent/SymbolTable.cpp",
"glslang/MachineIndependent/glslang_tab.cpp",
- "glslang/MachineIndependent/pch.cpp",
"glslang/MachineIndependent/Versions.cpp",
"glslang/MachineIndependent/ShaderLang.cpp",
"glslang/MachineIndependent/parseConst.cpp",
@@ -40,6 +43,7 @@ if env["builtin_glslang"]:
"glslang/GenericCodeGen/Link.cpp",
"glslang/GenericCodeGen/CodeGen.cpp",
"OGLCompilersDLL/InitializeDll.cpp",
+ "SPIRV/CInterface/spirv_c_interface.cpp",
"SPIRV/InReadableOrder.cpp",
"SPIRV/GlslangToSpv.cpp",
"SPIRV/SpvBuilder.cpp",
@@ -49,6 +53,7 @@ if env["builtin_glslang"]:
"SPIRV/SPVRemapper.cpp",
"SPIRV/SpvPostProcess.cpp",
"SPIRV/Logger.cpp",
+ "StandAlone/ResourceLimits.cpp",
]
if env["platform"] == "windows":
@@ -64,9 +69,20 @@ if env["builtin_glslang"]:
else:
env_glslang.Prepend(CPPPATH=[thirdparty_dir])
+ env_glslang.Append(CPPDEFINES=["ENABLE_OPT=0"])
+
env_thirdparty = env_glslang.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_glslang.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_glslang.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/glslang/register_types.cpp b/modules/glslang/register_types.cpp
index 2540ba476c..a7ae3e6bab 100644
--- a/modules/glslang/register_types.cpp
+++ b/modules/glslang/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,117 +33,11 @@
#include "servers/rendering/rendering_device.h"
#include <SPIRV/GlslangToSpv.h>
+#include <StandAlone/ResourceLimits.h>
#include <glslang/Include/Types.h>
#include <glslang/Public/ShaderLang.h>
-static const TBuiltInResource default_builtin_resource = {
- /*maxLights*/ 32,
- /*maxClipPlanes*/ 6,
- /*maxTextureUnits*/ 32,
- /*maxTextureCoords*/ 32,
- /*maxVertexAttribs*/ 64,
- /*maxVertexUniformComponents*/ 4096,
- /*maxVaryingFloats*/ 64,
- /*maxVertexTextureImageUnits*/ 32,
- /*maxCombinedTextureImageUnits*/ 80,
- /*maxTextureImageUnits*/ 32,
- /*maxFragmentUniformComponents*/ 4096,
- /*maxDrawBuffers*/ 32,
- /*maxVertexUniformVectors*/ 128,
- /*maxVaryingVectors*/ 8,
- /*maxFragmentUniformVectors*/ 16,
- /*maxVertexOutputVectors*/ 16,
- /*maxFragmentInputVectors*/ 15,
- /*minProgramTexelOffset*/ -8,
- /*maxProgramTexelOffset*/ 7,
- /*maxClipDistances*/ 8,
- /*maxComputeWorkGroupCountX*/ 65535,
- /*maxComputeWorkGroupCountY*/ 65535,
- /*maxComputeWorkGroupCountZ*/ 65535,
- /*maxComputeWorkGroupSizeX*/ 1024,
- /*maxComputeWorkGroupSizeY*/ 1024,
- /*maxComputeWorkGroupSizeZ*/ 64,
- /*maxComputeUniformComponents*/ 1024,
- /*maxComputeTextureImageUnits*/ 16,
- /*maxComputeImageUniforms*/ 8,
- /*maxComputeAtomicCounters*/ 8,
- /*maxComputeAtomicCounterBuffers*/ 1,
- /*maxVaryingComponents*/ 60,
- /*maxVertexOutputComponents*/ 64,
- /*maxGeometryInputComponents*/ 64,
- /*maxGeometryOutputComponents*/ 128,
- /*maxFragmentInputComponents*/ 128,
- /*maxImageUnits*/ 8,
- /*maxCombinedImageUnitsAndFragmentOutputs*/ 8,
- /*maxCombinedShaderOutputResources*/ 8,
- /*maxImageSamples*/ 0,
- /*maxVertexImageUniforms*/ 0,
- /*maxTessControlImageUniforms*/ 0,
- /*maxTessEvaluationImageUniforms*/ 0,
- /*maxGeometryImageUniforms*/ 0,
- /*maxFragmentImageUniforms*/ 8,
- /*maxCombinedImageUniforms*/ 8,
- /*maxGeometryTextureImageUnits*/ 16,
- /*maxGeometryOutputVertices*/ 256,
- /*maxGeometryTotalOutputComponents*/ 1024,
- /*maxGeometryUniformComponents*/ 1024,
- /*maxGeometryVaryingComponents*/ 64,
- /*maxTessControlInputComponents*/ 128,
- /*maxTessControlOutputComponents*/ 128,
- /*maxTessControlTextureImageUnits*/ 16,
- /*maxTessControlUniformComponents*/ 1024,
- /*maxTessControlTotalOutputComponents*/ 4096,
- /*maxTessEvaluationInputComponents*/ 128,
- /*maxTessEvaluationOutputComponents*/ 128,
- /*maxTessEvaluationTextureImageUnits*/ 16,
- /*maxTessEvaluationUniformComponents*/ 1024,
- /*maxTessPatchComponents*/ 120,
- /*maxPatchVertices*/ 32,
- /*maxTessGenLevel*/ 64,
- /*maxViewports*/ 16,
- /*maxVertexAtomicCounters*/ 0,
- /*maxTessControlAtomicCounters*/ 0,
- /*maxTessEvaluationAtomicCounters*/ 0,
- /*maxGeometryAtomicCounters*/ 0,
- /*maxFragmentAtomicCounters*/ 8,
- /*maxCombinedAtomicCounters*/ 8,
- /*maxAtomicCounterBindings*/ 1,
- /*maxVertexAtomicCounterBuffers*/ 0,
- /*maxTessControlAtomicCounterBuffers*/ 0,
- /*maxTessEvaluationAtomicCounterBuffers*/ 0,
- /*maxGeometryAtomicCounterBuffers*/ 0,
- /*maxFragmentAtomicCounterBuffers*/ 1,
- /*maxCombinedAtomicCounterBuffers*/ 1,
- /*maxAtomicCounterBufferSize*/ 16384,
- /*maxTransformFeedbackBuffers*/ 4,
- /*maxTransformFeedbackInterleavedComponents*/ 64,
- /*maxCullDistances*/ 8,
- /*maxCombinedClipAndCullDistances*/ 8,
- /*maxSamples*/ 4,
- /*maxMeshOutputVerticesNV*/ 0,
- /*maxMeshOutputPrimitivesNV*/ 0,
- /*maxMeshWorkGroupSizeX_NV*/ 0,
- /*maxMeshWorkGroupSizeY_NV*/ 0,
- /*maxMeshWorkGroupSizeZ_NV*/ 0,
- /*maxTaskWorkGroupSizeX_NV*/ 0,
- /*maxTaskWorkGroupSizeY_NV*/ 0,
- /*maxTaskWorkGroupSizeZ_NV*/ 0,
- /*maxMeshViewCountNV*/ 0,
- /*limits*/ {
- /*nonInductiveForLoops*/ 1,
- /*whileLoops*/ 1,
- /*doWhileLoops*/ 1,
- /*generalUniformIndexing*/ 1,
- /*generalAttributeMatrixVectorIndexing*/ 1,
- /*generalVaryingIndexing*/ 1,
- /*generalSamplerIndexing*/ 1,
- /*generalVariableIndexing*/ 1,
- /*generalConstantMatrixVectorIndexing*/ 1,
- }
-};
-
static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage, const String &p_source_code, RenderingDevice::ShaderLanguage p_language, String *r_error) {
-
Vector<uint8_t> ret;
ERR_FAIL_COND_V(p_language == RenderingDevice::SHADER_LANGUAGE_HLSL, ret);
@@ -176,8 +70,7 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage
std::string pre_processed_code;
//preprocess
- if (!shader.preprocess(&default_builtin_resource, DefaultVersion, ENoProfile, false, false, messages, &pre_processed_code, includer)) {
-
+ if (!shader.preprocess(&glslang::DefaultTBuiltInResource, DefaultVersion, ENoProfile, false, false, messages, &pre_processed_code, includer)) {
if (r_error) {
(*r_error) = "Failed pre-process:\n";
(*r_error) += shader.getInfoLog();
@@ -192,7 +85,7 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage
shader.setStrings(&cs_strings, 1);
//parse
- if (!shader.parse(&default_builtin_resource, DefaultVersion, false, messages)) {
+ if (!shader.parse(&glslang::DefaultTBuiltInResource, DefaultVersion, false, messages)) {
if (r_error) {
(*r_error) = "Failed parse:\n";
(*r_error) += shader.getInfoLog();
@@ -240,7 +133,7 @@ void preregister_glslang_types() {
void register_glslang_types() {
}
-void unregister_glslang_types() {
+void unregister_glslang_types() {
glslang::FinalizeProcess();
}
diff --git a/modules/glslang/register_types.h b/modules/glslang/register_types.h
index 2437e2b27a..a1264b77c9 100644
--- a/modules/glslang/register_types.h
+++ b/modules/glslang/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/gltf/SCsub b/modules/gltf/SCsub
new file mode 100644
index 0000000000..5d03ee8361
--- /dev/null
+++ b/modules/gltf/SCsub
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_gltf = env_modules.Clone()
+env_gltf.Prepend(CPPPATH=["."])
+
+# Godot's own source files
+env_gltf.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/gltf/config.py b/modules/gltf/config.py
new file mode 100644
index 0000000000..1505a456d7
--- /dev/null
+++ b/modules/gltf/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return env["tools"] and not env["disable_3d"]
+
+
+def configure(env):
+ pass
diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp
new file mode 100644
index 0000000000..4cdaccde6f
--- /dev/null
+++ b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp
@@ -0,0 +1,90 @@
+/*************************************************************************/
+/* editor_scene_exporter_gltf_plugin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_scene_exporter_gltf_plugin.h"
+#include "core/config/project_settings.h"
+#include "core/object/object.h"
+#include "core/templates/vector.h"
+#include "editor/editor_file_system.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/gui/check_box.h"
+#include "scene/main/node.h"
+
+#include "editor/editor_node.h"
+
+String SceneExporterGLTFPlugin::get_name() const {
+ return "ConvertGLTF2";
+}
+
+bool SceneExporterGLTFPlugin::has_main_screen() const {
+ return false;
+}
+
+SceneExporterGLTFPlugin::SceneExporterGLTFPlugin(EditorNode *p_node) {
+ editor = p_node;
+ convert_gltf2.instance();
+ file_export_lib = memnew(EditorFileDialog);
+ editor->get_gui_base()->add_child(file_export_lib);
+ file_export_lib->connect("file_selected", callable_mp(this, &SceneExporterGLTFPlugin::_gltf2_dialog_action));
+ file_export_lib->set_title(TTR("Export Library"));
+ file_export_lib->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
+ file_export_lib->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
+ file_export_lib->clear_filters();
+ file_export_lib->add_filter("*.glb");
+ file_export_lib->add_filter("*.gltf");
+ file_export_lib->set_title(TTR("Export Mesh GLTF2"));
+ String gltf_scene_name = TTR("Export GLTF...");
+ add_tool_menu_item(gltf_scene_name, callable_mp(this, &SceneExporterGLTFPlugin::convert_scene_to_gltf2));
+}
+
+void SceneExporterGLTFPlugin::_gltf2_dialog_action(String p_file) {
+ Node *root = editor->get_tree()->get_edited_scene_root();
+ if (!root) {
+ editor->show_accept(TTR("This operation can't be done without a scene."), TTR("OK"));
+ return;
+ }
+ List<String> deps;
+ convert_gltf2->save_scene(root, p_file, p_file, 0, 1000.0f, &deps);
+ EditorFileSystem::get_singleton()->scan_changes();
+}
+
+void SceneExporterGLTFPlugin::convert_scene_to_gltf2() {
+ Node *root = editor->get_tree()->get_edited_scene_root();
+ if (!root) {
+ editor->show_accept(TTR("This operation can't be done without a scene."), TTR("OK"));
+ return;
+ }
+ String filename = String(root->get_filename().get_file().get_basename());
+ if (filename.is_empty()) {
+ filename = root->get_name();
+ }
+ file_export_lib->set_current_file(filename + String(".gltf"));
+ file_export_lib->popup_centered_ratio();
+}
diff --git a/modules/mono/glue/string_glue.h b/modules/gltf/editor_scene_exporter_gltf_plugin.h
index a5e833ba61..d952894c16 100644
--- a/modules/mono/glue/string_glue.h
+++ b/modules/gltf/editor_scene_exporter_gltf_plugin.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* string_glue.h */
+/* editor_scene_exporter_gltf_plugin.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,29 +28,25 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef STRING_GLUE_H
-#define STRING_GLUE_H
+#ifndef EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H
+#define EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H
-#ifdef MONO_GLUE_ENABLED
+#include "editor/editor_plugin.h"
+#include "editor_scene_importer_gltf.h"
-#include "../mono_gd/gd_mono_marshal.h"
+class SceneExporterGLTFPlugin : public EditorPlugin {
+ GDCLASS(SceneExporterGLTFPlugin, EditorPlugin);
-MonoArray *godot_icall_String_md5_buffer(MonoString *p_str);
+ Ref<PackedSceneGLTF> convert_gltf2;
+ EditorNode *editor = nullptr;
+ EditorFileDialog *file_export_lib = nullptr;
+ void _gltf2_dialog_action(String p_file);
+ void convert_scene_to_gltf2();
-MonoString *godot_icall_String_md5_text(MonoString *p_str);
+public:
+ virtual String get_name() const override;
+ bool has_main_screen() const override;
+ SceneExporterGLTFPlugin(class EditorNode *p_node);
+};
-int godot_icall_String_rfind(MonoString *p_str, MonoString *p_what, int p_from);
-
-int godot_icall_String_rfindn(MonoString *p_str, MonoString *p_what, int p_from);
-
-MonoArray *godot_icall_String_sha256_buffer(MonoString *p_str);
-
-MonoString *godot_icall_String_sha256_text(MonoString *p_str);
-
-// Register internal calls
-
-void godot_register_string_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // STRING_GLUE_H
+#endif // EDITOR_SCENE_EXPORTER_GLTF_PLUGIN_H
diff --git a/modules/gltf/editor_scene_importer_gltf.cpp b/modules/gltf/editor_scene_importer_gltf.cpp
new file mode 100644
index 0000000000..6ea722a216
--- /dev/null
+++ b/modules/gltf/editor_scene_importer_gltf.cpp
@@ -0,0 +1,180 @@
+/*************************************************************************/
+/* editor_scene_importer_gltf.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "core/crypto/crypto_core.h"
+#include "core/io/json.h"
+#include "core/math/disjoint_set.h"
+#include "core/math/math_defs.h"
+#include "core/os/file_access.h"
+#include "core/os/os.h"
+#include "editor/import/resource_importer_scene.h"
+#include "modules/gltf/gltf_state.h"
+#include "modules/regex/regex.h"
+#include "scene/3d/bone_attachment_3d.h"
+#include "scene/3d/camera_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/packed_scene.h"
+#include "scene/resources/surface_tool.h"
+
+#include "modules/gltf/editor_scene_importer_gltf.h"
+
+uint32_t EditorSceneImporterGLTF::get_import_flags() const {
+ return ImportFlags::IMPORT_SCENE | ImportFlags::IMPORT_ANIMATION;
+}
+
+void EditorSceneImporterGLTF::get_extensions(List<String> *r_extensions) const {
+ r_extensions->push_back("gltf");
+ r_extensions->push_back("glb");
+}
+
+Node *EditorSceneImporterGLTF::import_scene(const String &p_path,
+ uint32_t p_flags, int p_bake_fps,
+ List<String> *r_missing_deps,
+ Error *r_err) {
+ Ref<PackedSceneGLTF> importer;
+ importer.instance();
+ return importer->import_scene(p_path, p_flags, p_bake_fps, r_missing_deps, r_err, Ref<GLTFState>());
+}
+
+Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path,
+ uint32_t p_flags,
+ int p_bake_fps) {
+ return Ref<Animation>();
+}
+
+void PackedSceneGLTF::_bind_methods() {
+ ClassDB::bind_method(
+ D_METHOD("export_gltf", "node", "path", "flags", "bake_fps"),
+ &PackedSceneGLTF::export_gltf, DEFVAL(0), DEFVAL(1000.0f));
+ ClassDB::bind_method(D_METHOD("pack_gltf", "path", "flags", "bake_fps", "state"),
+ &PackedSceneGLTF::pack_gltf, DEFVAL(0), DEFVAL(1000.0f), DEFVAL(Ref<GLTFState>()));
+ ClassDB::bind_method(D_METHOD("import_gltf_scene", "path", "flags", "bake_fps", "state"),
+ &PackedSceneGLTF::import_gltf_scene, DEFVAL(0), DEFVAL(1000.0f), DEFVAL(Ref<GLTFState>()));
+}
+Node *PackedSceneGLTF::import_gltf_scene(const String &p_path, uint32_t p_flags, float p_bake_fps, Ref<GLTFState> r_state) {
+ Error err = FAILED;
+ List<String> deps;
+ return import_scene(p_path, p_flags, p_bake_fps, &deps, &err, r_state);
+}
+
+Node *PackedSceneGLTF::import_scene(const String &p_path, uint32_t p_flags,
+ int p_bake_fps,
+ List<String> *r_missing_deps,
+ Error *r_err,
+ Ref<GLTFState> r_state) {
+ if (r_state == Ref<GLTFState>()) {
+ r_state.instance();
+ }
+ r_state->use_named_skin_binds =
+ p_flags & EditorSceneImporter::IMPORT_USE_NAMED_SKIN_BINDS;
+
+ Ref<GLTFDocument> gltf_document;
+ gltf_document.instance();
+ Error err = gltf_document->parse(r_state, p_path);
+ *r_err = err;
+ ERR_FAIL_COND_V(err != Error::OK, nullptr);
+
+ Node3D *root = memnew(Node3D);
+ for (int32_t root_i = 0; root_i < r_state->root_nodes.size(); root_i++) {
+ gltf_document->_generate_scene_node(r_state, root, root, r_state->root_nodes[root_i]);
+ }
+ gltf_document->_process_mesh_instances(r_state, root);
+ if (r_state->animations.size()) {
+ AnimationPlayer *ap = memnew(AnimationPlayer);
+ root->add_child(ap);
+ ap->set_owner(root);
+ for (int i = 0; i < r_state->animations.size(); i++) {
+ gltf_document->_import_animation(r_state, ap, i, p_bake_fps);
+ }
+ }
+
+ return cast_to<Node3D>(root);
+}
+
+void PackedSceneGLTF::pack_gltf(String p_path, int32_t p_flags,
+ real_t p_bake_fps, Ref<GLTFState> r_state) {
+ Error err = FAILED;
+ List<String> deps;
+ Node *root = import_scene(p_path, p_flags, p_bake_fps, &deps, &err, r_state);
+ ERR_FAIL_COND(err != OK);
+ pack(root);
+}
+
+void PackedSceneGLTF::save_scene(Node *p_node, const String &p_path,
+ const String &p_src_path, uint32_t p_flags,
+ int p_bake_fps, List<String> *r_missing_deps,
+ Error *r_err) {
+ Error err = FAILED;
+ if (r_err) {
+ *r_err = err;
+ }
+ Ref<GLTFDocument> gltf_document;
+ gltf_document.instance();
+ Ref<GLTFState> state;
+ state.instance();
+ err = gltf_document->serialize(state, p_node, p_path);
+ if (r_err) {
+ *r_err = err;
+ }
+}
+
+void PackedSceneGLTF::_build_parent_hierachy(Ref<GLTFState> state) {
+ // build the hierarchy
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); node_i++) {
+ for (int j = 0; j < state->nodes[node_i]->children.size(); j++) {
+ GLTFNodeIndex child_i = state->nodes[node_i]->children[j];
+ ERR_FAIL_INDEX(child_i, state->nodes.size());
+ if (state->nodes.write[child_i]->parent != -1) {
+ continue;
+ }
+ state->nodes.write[child_i]->parent = node_i;
+ }
+ }
+}
+
+Error PackedSceneGLTF::export_gltf(Node *p_root, String p_path,
+ int32_t p_flags,
+ real_t p_bake_fps) {
+ ERR_FAIL_COND_V(!p_root, FAILED);
+ List<String> deps;
+ Error err;
+ String path = p_path;
+ int32_t flags = p_flags;
+ real_t baked_fps = p_bake_fps;
+ Ref<PackedSceneGLTF> exporter;
+ exporter.instance();
+ exporter->save_scene(p_root, path, "", flags, baked_fps, &deps, &err);
+ int32_t error_code = err;
+ if (error_code != 0) {
+ return Error(error_code);
+ }
+ return OK;
+}
diff --git a/modules/gltf/editor_scene_importer_gltf.h b/modules/gltf/editor_scene_importer_gltf.h
new file mode 100644
index 0000000000..db961e591d
--- /dev/null
+++ b/modules/gltf/editor_scene_importer_gltf.h
@@ -0,0 +1,96 @@
+/*************************************************************************/
+/* editor_scene_importer_gltf.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 EDITOR_SCENE_IMPORTER_GLTF_H
+#define EDITOR_SCENE_IMPORTER_GLTF_H
+
+#include "core/config/project_settings.h"
+#include "core/io/json.h"
+#include "core/object/object.h"
+#include "core/templates/vector.h"
+#include "editor/import/resource_importer_scene.h"
+#include "modules/csg/csg_shape.h"
+#include "modules/gridmap/grid_map.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/3d/multimesh_instance_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/3d/skeleton_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/gui/check_box.h"
+#include "scene/main/node.h"
+#include "scene/resources/packed_scene.h"
+#include "scene/resources/surface_tool.h"
+
+#include "gltf_document.h"
+#include "gltf_state.h"
+
+class AnimationPlayer;
+class BoneAttachment;
+class EditorSceneImporterMeshNode3D;
+
+#ifdef TOOLS_ENABLED
+class EditorSceneImporterGLTF : public EditorSceneImporter {
+ GDCLASS(EditorSceneImporterGLTF, EditorSceneImporter);
+
+public:
+ virtual uint32_t get_import_flags() const override;
+ virtual void get_extensions(List<String> *r_extensions) const override;
+ virtual Node *import_scene(const String &p_path, uint32_t p_flags,
+ int p_bake_fps,
+ List<String> *r_missing_deps = NULL,
+ Error *r_err = NULL) override;
+ virtual Ref<Animation> import_animation(const String &p_path,
+ uint32_t p_flags, int p_bake_fps) override;
+};
+#endif
+
+class PackedSceneGLTF : public PackedScene {
+ GDCLASS(PackedSceneGLTF, PackedScene);
+
+protected:
+ static void _bind_methods();
+
+public:
+ virtual void save_scene(Node *p_node, const String &p_path, const String &p_src_path,
+ uint32_t p_flags, int p_bake_fps,
+ List<String> *r_missing_deps, Error *r_err = NULL);
+ virtual void _build_parent_hierachy(Ref<GLTFState> state);
+ virtual Error export_gltf(Node *p_root, String p_path, int32_t p_flags = 0,
+ real_t p_bake_fps = 1000.0f);
+ virtual Node *import_scene(const String &p_path, uint32_t p_flags,
+ int p_bake_fps,
+ List<String> *r_missing_deps,
+ Error *r_err,
+ Ref<GLTFState> r_state);
+ virtual Node *import_gltf_scene(const String &p_path, uint32_t p_flags, float p_bake_fps, Ref<GLTFState> r_state = Ref<GLTFState>());
+ virtual void pack_gltf(String p_path, int32_t p_flags = 0,
+ real_t p_bake_fps = 1000.0f, Ref<GLTFState> r_state = Ref<GLTFState>());
+};
+#endif // EDITOR_SCENE_IMPORTER_GLTF_H
diff --git a/modules/gltf/gltf_accessor.cpp b/modules/gltf/gltf_accessor.cpp
new file mode 100644
index 0000000000..daeb084916
--- /dev/null
+++ b/modules/gltf/gltf_accessor.cpp
@@ -0,0 +1,189 @@
+/*************************************************************************/
+/* gltf_accessor.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_accessor.h"
+
+void GLTFAccessor::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_buffer_view"), &GLTFAccessor::get_buffer_view);
+ ClassDB::bind_method(D_METHOD("set_buffer_view", "buffer_view"), &GLTFAccessor::set_buffer_view);
+ ClassDB::bind_method(D_METHOD("get_byte_offset"), &GLTFAccessor::get_byte_offset);
+ ClassDB::bind_method(D_METHOD("set_byte_offset", "byte_offset"), &GLTFAccessor::set_byte_offset);
+ ClassDB::bind_method(D_METHOD("get_component_type"), &GLTFAccessor::get_component_type);
+ ClassDB::bind_method(D_METHOD("set_component_type", "component_type"), &GLTFAccessor::set_component_type);
+ ClassDB::bind_method(D_METHOD("get_normalized"), &GLTFAccessor::get_normalized);
+ ClassDB::bind_method(D_METHOD("set_normalized", "normalized"), &GLTFAccessor::set_normalized);
+ ClassDB::bind_method(D_METHOD("get_count"), &GLTFAccessor::get_count);
+ ClassDB::bind_method(D_METHOD("set_count", "count"), &GLTFAccessor::set_count);
+ ClassDB::bind_method(D_METHOD("get_type"), &GLTFAccessor::get_type);
+ ClassDB::bind_method(D_METHOD("set_type", "type"), &GLTFAccessor::set_type);
+ ClassDB::bind_method(D_METHOD("get_min"), &GLTFAccessor::get_min);
+ ClassDB::bind_method(D_METHOD("set_min", "min"), &GLTFAccessor::set_min);
+ ClassDB::bind_method(D_METHOD("get_max"), &GLTFAccessor::get_max);
+ ClassDB::bind_method(D_METHOD("set_max", "max"), &GLTFAccessor::set_max);
+ ClassDB::bind_method(D_METHOD("get_sparse_count"), &GLTFAccessor::get_sparse_count);
+ ClassDB::bind_method(D_METHOD("set_sparse_count", "sparse_count"), &GLTFAccessor::set_sparse_count);
+ ClassDB::bind_method(D_METHOD("get_sparse_indices_buffer_view"), &GLTFAccessor::get_sparse_indices_buffer_view);
+ ClassDB::bind_method(D_METHOD("set_sparse_indices_buffer_view", "sparse_indices_buffer_view"), &GLTFAccessor::set_sparse_indices_buffer_view);
+ ClassDB::bind_method(D_METHOD("get_sparse_indices_byte_offset"), &GLTFAccessor::get_sparse_indices_byte_offset);
+ ClassDB::bind_method(D_METHOD("set_sparse_indices_byte_offset", "sparse_indices_byte_offset"), &GLTFAccessor::set_sparse_indices_byte_offset);
+ ClassDB::bind_method(D_METHOD("get_sparse_indices_component_type"), &GLTFAccessor::get_sparse_indices_component_type);
+ ClassDB::bind_method(D_METHOD("set_sparse_indices_component_type", "sparse_indices_component_type"), &GLTFAccessor::set_sparse_indices_component_type);
+ ClassDB::bind_method(D_METHOD("get_sparse_values_buffer_view"), &GLTFAccessor::get_sparse_values_buffer_view);
+ ClassDB::bind_method(D_METHOD("set_sparse_values_buffer_view", "sparse_values_buffer_view"), &GLTFAccessor::set_sparse_values_buffer_view);
+ ClassDB::bind_method(D_METHOD("get_sparse_values_byte_offset"), &GLTFAccessor::get_sparse_values_byte_offset);
+ ClassDB::bind_method(D_METHOD("set_sparse_values_byte_offset", "sparse_values_byte_offset"), &GLTFAccessor::set_sparse_values_byte_offset);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "buffer_view"), "set_buffer_view", "get_buffer_view"); // GLTFBufferViewIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "byte_offset"), "set_byte_offset", "get_byte_offset"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "component_type"), "set_component_type", "get_component_type"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "normalized"), "set_normalized", "get_normalized"); // bool
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "count"), "set_count", "get_count"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type"), "set_type", "get_type"); // GLTFDocument::GLTFType
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT64_ARRAY, "min"), "set_min", "get_min"); // Vector<real_t>
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT64_ARRAY, "max"), "set_max", "get_max"); // Vector<real_t>
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_count"), "set_sparse_count", "get_sparse_count"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_buffer_view"), "set_sparse_indices_buffer_view", "get_sparse_indices_buffer_view"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_byte_offset"), "set_sparse_indices_byte_offset", "get_sparse_indices_byte_offset"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_indices_component_type"), "set_sparse_indices_component_type", "get_sparse_indices_component_type"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_values_buffer_view"), "set_sparse_values_buffer_view", "get_sparse_values_buffer_view"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sparse_values_byte_offset"), "set_sparse_values_byte_offset", "get_sparse_values_byte_offset"); // int
+}
+
+GLTFBufferViewIndex GLTFAccessor::get_buffer_view() {
+ return buffer_view;
+}
+
+void GLTFAccessor::set_buffer_view(GLTFBufferViewIndex p_buffer_view) {
+ buffer_view = p_buffer_view;
+}
+
+int GLTFAccessor::get_byte_offset() {
+ return byte_offset;
+}
+
+void GLTFAccessor::set_byte_offset(int p_byte_offset) {
+ byte_offset = p_byte_offset;
+}
+
+int GLTFAccessor::get_component_type() {
+ return component_type;
+}
+
+void GLTFAccessor::set_component_type(int p_component_type) {
+ component_type = p_component_type;
+}
+
+bool GLTFAccessor::get_normalized() {
+ return normalized;
+}
+
+void GLTFAccessor::set_normalized(bool p_normalized) {
+ normalized = p_normalized;
+}
+
+int GLTFAccessor::get_count() {
+ return count;
+}
+
+void GLTFAccessor::set_count(int p_count) {
+ count = p_count;
+}
+
+int GLTFAccessor::get_type() {
+ return (int)type;
+}
+
+void GLTFAccessor::set_type(int p_type) {
+ type = (GLTFDocument::GLTFType)p_type; // TODO: Register enum
+}
+
+Vector<double> GLTFAccessor::get_min() {
+ return min;
+}
+
+void GLTFAccessor::set_min(Vector<double> p_min) {
+ min = p_min;
+}
+
+Vector<double> GLTFAccessor::get_max() {
+ return max;
+}
+
+void GLTFAccessor::set_max(Vector<double> p_max) {
+ max = p_max;
+}
+
+int GLTFAccessor::get_sparse_count() {
+ return sparse_count;
+}
+
+void GLTFAccessor::set_sparse_count(int p_sparse_count) {
+ sparse_count = p_sparse_count;
+}
+
+int GLTFAccessor::get_sparse_indices_buffer_view() {
+ return sparse_indices_buffer_view;
+}
+
+void GLTFAccessor::set_sparse_indices_buffer_view(int p_sparse_indices_buffer_view) {
+ sparse_indices_buffer_view = p_sparse_indices_buffer_view;
+}
+
+int GLTFAccessor::get_sparse_indices_byte_offset() {
+ return sparse_indices_byte_offset;
+}
+
+void GLTFAccessor::set_sparse_indices_byte_offset(int p_sparse_indices_byte_offset) {
+ sparse_indices_byte_offset = p_sparse_indices_byte_offset;
+}
+
+int GLTFAccessor::get_sparse_indices_component_type() {
+ return sparse_indices_component_type;
+}
+
+void GLTFAccessor::set_sparse_indices_component_type(int p_sparse_indices_component_type) {
+ sparse_indices_component_type = p_sparse_indices_component_type;
+}
+
+int GLTFAccessor::get_sparse_values_buffer_view() {
+ return sparse_values_buffer_view;
+}
+
+void GLTFAccessor::set_sparse_values_buffer_view(int p_sparse_values_buffer_view) {
+ sparse_values_buffer_view = p_sparse_values_buffer_view;
+}
+
+int GLTFAccessor::get_sparse_values_byte_offset() {
+ return sparse_values_byte_offset;
+}
+
+void GLTFAccessor::set_sparse_values_byte_offset(int p_sparse_values_byte_offset) {
+ sparse_values_byte_offset = p_sparse_values_byte_offset;
+}
diff --git a/modules/gltf/gltf_accessor.h b/modules/gltf/gltf_accessor.h
new file mode 100644
index 0000000000..949a601730
--- /dev/null
+++ b/modules/gltf/gltf_accessor.h
@@ -0,0 +1,104 @@
+/*************************************************************************/
+/* gltf_accessor.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_ACCESSOR_H
+#define GLTF_ACCESSOR_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+struct GLTFAccessor : public Resource {
+ GDCLASS(GLTFAccessor, Resource);
+ friend class GLTFDocument;
+
+private:
+ GLTFBufferViewIndex buffer_view = 0;
+ int byte_offset = 0;
+ int component_type = 0;
+ bool normalized = false;
+ int count = 0;
+ GLTFDocument::GLTFType
+ type = GLTFDocument::TYPE_SCALAR;
+ Vector<double> min;
+ Vector<double> max;
+ int sparse_count = 0;
+ int sparse_indices_buffer_view = 0;
+ int sparse_indices_byte_offset = 0;
+ int sparse_indices_component_type = 0;
+ int sparse_values_buffer_view = 0;
+ int sparse_values_byte_offset = 0;
+
+protected:
+ static void _bind_methods();
+
+public:
+ GLTFBufferViewIndex get_buffer_view();
+ void set_buffer_view(GLTFBufferViewIndex p_buffer_view);
+
+ int get_byte_offset();
+ void set_byte_offset(int p_byte_offset);
+
+ int get_component_type();
+ void set_component_type(int p_component_type);
+
+ bool get_normalized();
+ void set_normalized(bool p_normalized);
+
+ int get_count();
+ void set_count(int p_count);
+
+ int get_type();
+ void set_type(int p_type);
+
+ Vector<double> get_min();
+ void set_min(Vector<double> p_min);
+
+ Vector<double> get_max();
+ void set_max(Vector<double> p_max);
+
+ int get_sparse_count();
+ void set_sparse_count(int p_sparse_count);
+
+ int get_sparse_indices_buffer_view();
+ void set_sparse_indices_buffer_view(int p_sparse_indices_buffer_view);
+
+ int get_sparse_indices_byte_offset();
+ void set_sparse_indices_byte_offset(int p_sparse_indices_byte_offset);
+
+ int get_sparse_indices_component_type();
+ void set_sparse_indices_component_type(int p_sparse_indices_component_type);
+
+ int get_sparse_values_buffer_view();
+ void set_sparse_values_buffer_view(int p_sparse_values_buffer_view);
+
+ int get_sparse_values_byte_offset();
+ void set_sparse_values_byte_offset(int p_sparse_values_byte_offset);
+};
+#endif // GLTF_ACCESSOR_H
diff --git a/modules/gltf/gltf_animation.cpp b/modules/gltf/gltf_animation.cpp
new file mode 100644
index 0000000000..889a8e8870
--- /dev/null
+++ b/modules/gltf/gltf_animation.cpp
@@ -0,0 +1,53 @@
+/*************************************************************************/
+/* gltf_animation.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_animation.h"
+
+void GLTFAnimation::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_loop"), &GLTFAnimation::get_loop);
+ ClassDB::bind_method(D_METHOD("set_loop", "loop"), &GLTFAnimation::set_loop);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "get_loop"); // bool
+}
+
+bool GLTFAnimation::get_loop() const {
+ return loop;
+}
+
+void GLTFAnimation::set_loop(bool p_val) {
+ loop = p_val;
+}
+
+Map<int, GLTFAnimation::Track> &GLTFAnimation::get_tracks() {
+ return tracks;
+}
+
+GLTFAnimation::GLTFAnimation() {
+}
diff --git a/modules/gltf/gltf_animation.h b/modules/gltf/gltf_animation.h
new file mode 100644
index 0000000000..a494e6bd67
--- /dev/null
+++ b/modules/gltf/gltf_animation.h
@@ -0,0 +1,74 @@
+/*************************************************************************/
+/* gltf_animation.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_ANIMATION_H
+#define GLTF_ANIMATION_H
+
+#include "core/io/resource.h"
+
+class GLTFAnimation : public Resource {
+ GDCLASS(GLTFAnimation, Resource);
+
+protected:
+ static void _bind_methods();
+
+public:
+ enum Interpolation {
+ INTERP_LINEAR,
+ INTERP_STEP,
+ INTERP_CATMULLROMSPLINE,
+ INTERP_CUBIC_SPLINE,
+ };
+
+ template <class T>
+ struct Channel {
+ Interpolation interpolation;
+ Vector<float> times;
+ Vector<T> values;
+ };
+
+ struct Track {
+ Channel<Vector3> translation_track;
+ Channel<Quat> rotation_track;
+ Channel<Vector3> scale_track;
+ Vector<Channel<float>> weight_tracks;
+ };
+
+public:
+ bool get_loop() const;
+ void set_loop(bool p_val);
+ Map<int, GLTFAnimation::Track> &get_tracks();
+ GLTFAnimation();
+
+private:
+ bool loop = false;
+ Map<int, Track> tracks;
+};
+#endif // GLTF_ANIMATION_H
diff --git a/modules/gltf/gltf_buffer_view.cpp b/modules/gltf/gltf_buffer_view.cpp
new file mode 100644
index 0000000000..ba38a11c4c
--- /dev/null
+++ b/modules/gltf/gltf_buffer_view.cpp
@@ -0,0 +1,90 @@
+/*************************************************************************/
+/* gltf_buffer_view.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_buffer_view.h"
+
+void GLTFBufferView::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_buffer"), &GLTFBufferView::get_buffer);
+ ClassDB::bind_method(D_METHOD("set_buffer", "buffer"), &GLTFBufferView::set_buffer);
+ ClassDB::bind_method(D_METHOD("get_byte_offset"), &GLTFBufferView::get_byte_offset);
+ ClassDB::bind_method(D_METHOD("set_byte_offset", "byte_offset"), &GLTFBufferView::set_byte_offset);
+ ClassDB::bind_method(D_METHOD("get_byte_length"), &GLTFBufferView::get_byte_length);
+ ClassDB::bind_method(D_METHOD("set_byte_length", "byte_length"), &GLTFBufferView::set_byte_length);
+ ClassDB::bind_method(D_METHOD("get_byte_stride"), &GLTFBufferView::get_byte_stride);
+ ClassDB::bind_method(D_METHOD("set_byte_stride", "byte_stride"), &GLTFBufferView::set_byte_stride);
+ ClassDB::bind_method(D_METHOD("get_indices"), &GLTFBufferView::get_indices);
+ ClassDB::bind_method(D_METHOD("set_indices", "indices"), &GLTFBufferView::set_indices);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "buffer"), "set_buffer", "get_buffer"); // GLTFBufferIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "byte_offset"), "set_byte_offset", "get_byte_offset"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "byte_length"), "set_byte_length", "get_byte_length"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "byte_stride"), "set_byte_stride", "get_byte_stride"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "indices"), "set_indices", "get_indices"); // bool
+}
+
+GLTFBufferIndex GLTFBufferView::get_buffer() {
+ return buffer;
+}
+
+void GLTFBufferView::set_buffer(GLTFBufferIndex p_buffer) {
+ buffer = p_buffer;
+}
+
+int GLTFBufferView::get_byte_offset() {
+ return byte_offset;
+}
+
+void GLTFBufferView::set_byte_offset(int p_byte_offset) {
+ byte_offset = p_byte_offset;
+}
+
+int GLTFBufferView::get_byte_length() {
+ return byte_length;
+}
+
+void GLTFBufferView::set_byte_length(int p_byte_length) {
+ byte_length = p_byte_length;
+}
+
+int GLTFBufferView::get_byte_stride() {
+ return byte_stride;
+}
+
+void GLTFBufferView::set_byte_stride(int p_byte_stride) {
+ byte_stride = p_byte_stride;
+}
+
+bool GLTFBufferView::get_indices() {
+ return indices;
+}
+
+void GLTFBufferView::set_indices(bool p_indices) {
+ indices = p_indices;
+}
diff --git a/modules/gltf/gltf_buffer_view.h b/modules/gltf/gltf_buffer_view.h
new file mode 100644
index 0000000000..63af5e7c0d
--- /dev/null
+++ b/modules/gltf/gltf_buffer_view.h
@@ -0,0 +1,68 @@
+/*************************************************************************/
+/* gltf_buffer_view.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_BUFFER_VIEW_H
+#define GLTF_BUFFER_VIEW_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+class GLTFBufferView : public Resource {
+ GDCLASS(GLTFBufferView, Resource);
+ friend class GLTFDocument;
+
+private:
+ GLTFBufferIndex buffer = -1;
+ int byte_offset = 0;
+ int byte_length = 0;
+ int byte_stride = -1;
+ bool indices = false;
+
+protected:
+ static void _bind_methods();
+
+public:
+ GLTFBufferIndex get_buffer();
+ void set_buffer(GLTFBufferIndex p_buffer);
+
+ int get_byte_offset();
+ void set_byte_offset(int p_byte_offset);
+
+ int get_byte_length();
+ void set_byte_length(int p_byte_length);
+
+ int get_byte_stride();
+ void set_byte_stride(int p_byte_stride);
+
+ bool get_indices();
+ void set_indices(bool p_indices);
+ // matrices need to be transformed to this
+};
+#endif // GLTF_BUFFER_VIEW_H
diff --git a/modules/gltf/gltf_camera.cpp b/modules/gltf/gltf_camera.cpp
new file mode 100644
index 0000000000..efa7c5d6d7
--- /dev/null
+++ b/modules/gltf/gltf_camera.cpp
@@ -0,0 +1,47 @@
+/*************************************************************************/
+/* gltf_camera.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_camera.h"
+
+void GLTFCamera::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_perspective"), &GLTFCamera::get_perspective);
+ ClassDB::bind_method(D_METHOD("set_perspective", "perspective"), &GLTFCamera::set_perspective);
+ ClassDB::bind_method(D_METHOD("get_fov_size"), &GLTFCamera::get_fov_size);
+ ClassDB::bind_method(D_METHOD("set_fov_size", "fov_size"), &GLTFCamera::set_fov_size);
+ ClassDB::bind_method(D_METHOD("get_zfar"), &GLTFCamera::get_zfar);
+ ClassDB::bind_method(D_METHOD("set_zfar", "zfar"), &GLTFCamera::set_zfar);
+ ClassDB::bind_method(D_METHOD("get_znear"), &GLTFCamera::get_znear);
+ ClassDB::bind_method(D_METHOD("set_znear", "znear"), &GLTFCamera::set_znear);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "perspective"), "set_perspective", "get_perspective"); // bool
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov_size"), "set_fov_size", "get_fov_size"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "zfar"), "set_zfar", "get_zfar"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "znear"), "set_znear", "get_znear"); // float
+}
diff --git a/modules/gltf/gltf_camera.h b/modules/gltf/gltf_camera.h
new file mode 100644
index 0000000000..e5c2041793
--- /dev/null
+++ b/modules/gltf/gltf_camera.h
@@ -0,0 +1,58 @@
+/*************************************************************************/
+/* gltf_camera.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_CAMERA_H
+#define GLTF_CAMERA_H
+
+#include "core/io/resource.h"
+
+class GLTFCamera : public Resource {
+ GDCLASS(GLTFCamera, Resource);
+
+private:
+ bool perspective = true;
+ float fov_size = 75;
+ float zfar = 4000;
+ float znear = 0.05;
+
+protected:
+ static void _bind_methods();
+
+public:
+ bool get_perspective() const { return perspective; }
+ void set_perspective(bool p_val) { perspective = p_val; }
+ float get_fov_size() const { return fov_size; }
+ void set_fov_size(float p_val) { fov_size = p_val; }
+ float get_zfar() const { return zfar; }
+ void set_zfar(float p_val) { zfar = p_val; }
+ float get_znear() const { return znear; }
+ void set_znear(float p_val) { znear = p_val; }
+};
+#endif // GLTF_CAMERA_H
diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp
new file mode 100644
index 0000000000..ebf30b13f2
--- /dev/null
+++ b/modules/gltf/gltf_document.cpp
@@ -0,0 +1,6540 @@
+/*************************************************************************/
+/* gltf_document.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_document.h"
+#include "core/error/error_list.h"
+#include "core/error/error_macros.h"
+#include "core/variant/variant.h"
+#include "gltf_accessor.h"
+#include "gltf_animation.h"
+#include "gltf_camera.h"
+#include "gltf_light.h"
+#include "gltf_mesh.h"
+#include "gltf_node.h"
+#include "gltf_skeleton.h"
+#include "gltf_skin.h"
+#include "gltf_spec_gloss.h"
+#include "gltf_state.h"
+#include "gltf_texture.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "core/core_bind.h"
+#include "core/crypto/crypto_core.h"
+#include "core/io/json.h"
+#include "core/math/disjoint_set.h"
+#include "core/os/file_access.h"
+#include "core/variant/typed_array.h"
+#include "core/version.h"
+#include "core/version_hash.gen.h"
+#include "drivers/png/png_driver_common.h"
+#include "editor/import/resource_importer_scene.h"
+#include "modules/csg/csg_shape.h"
+#include "modules/gridmap/grid_map.h"
+#include "modules/regex/regex.h"
+#include "scene/2d/node_2d.h"
+#include "scene/3d/bone_attachment_3d.h"
+#include "scene/3d/camera_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/3d/multimesh_instance_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/3d/skeleton_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/surface_tool.h"
+#include <limits>
+
+Error GLTFDocument::serialize(Ref<GLTFState> state, Node *p_root, const String &p_path) {
+ uint64_t begin_time = OS::get_singleton()->get_ticks_usec();
+
+ _convert_scene_node(state, p_root, p_root, -1, -1);
+ if (!state->buffers.size()) {
+ state->buffers.push_back(Vector<uint8_t>());
+ }
+
+ /* STEP 1 CONVERT MESH INSTANCES */
+ _convert_mesh_instances(state);
+
+ /* STEP 2 SERIALIZE CAMERAS */
+ Error err = _serialize_cameras(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 3 CREATE SKINS */
+ err = _serialize_skins(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+ /* STEP 4 CREATE BONE ATTACHMENTS */
+ err = _serialize_bone_attachment(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+ /* STEP 5 SERIALIZE MESHES (we have enough info now) */
+ err = _serialize_meshes(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 6 SERIALIZE TEXTURES */
+ err = _serialize_materials(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 7 SERIALIZE IMAGES */
+ err = _serialize_images(state, p_path);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 8 SERIALIZE TEXTURES */
+ err = _serialize_textures(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ // /* STEP 9 SERIALIZE ANIMATIONS */
+ err = _serialize_animations(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 10 SERIALIZE ACCESSORS */
+ err = _encode_accessors(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ for (GLTFBufferViewIndex i = 0; i < state->buffer_views.size(); i++) {
+ state->buffer_views.write[i]->buffer = 0;
+ }
+
+ /* STEP 11 SERIALIZE BUFFER VIEWS */
+ err = _encode_buffer_views(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 12 SERIALIZE NODES */
+ err = _serialize_nodes(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 13 SERIALIZE SCENE */
+ err = _serialize_scenes(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 14 SERIALIZE SCENE */
+ err = _serialize_lights(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 15 SERIALIZE EXTENSIONS */
+ err = _serialize_extensions(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 16 SERIALIZE VERSION */
+ err = _serialize_version(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 17 SERIALIZE FILE */
+ err = _serialize_file(state, p_path);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+ uint64_t elapsed = OS::get_singleton()->get_ticks_usec() - begin_time;
+ float elapsed_sec = double(elapsed) / 1000000.0;
+ elapsed_sec = Math::snapped(elapsed_sec, 0.01f);
+ print_line("glTF: Export time elapsed seconds " + rtos(elapsed_sec).pad_decimals(2));
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const {
+ const String texture_transform = "KHR_texture_transform";
+ const String punctual_lights = "KHR_lights_punctual";
+ Array extensions_used;
+ extensions_used.push_back(punctual_lights);
+ extensions_used.push_back(texture_transform);
+ state->json["extensionsUsed"] = extensions_used;
+ Array extensions_required;
+ extensions_required.push_back(texture_transform);
+ state->json["extensionsRequired"] = extensions_required;
+ return OK;
+}
+
+Error GLTFDocument::_serialize_scenes(Ref<GLTFState> state) {
+ Array scenes;
+ const int loaded_scene = 0;
+ state->json["scene"] = loaded_scene;
+
+ if (state->nodes.size()) {
+ Dictionary s;
+ if (!state->scene_name.is_empty()) {
+ s["name"] = state->scene_name;
+ }
+
+ Array nodes;
+ nodes.push_back(0);
+ s["nodes"] = nodes;
+ scenes.push_back(s);
+ }
+ state->json["scenes"] = scenes;
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> state) {
+ Error err;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (!f) {
+ return err;
+ }
+
+ Vector<uint8_t> array;
+ array.resize(f->get_len());
+ f->get_buffer(array.ptrw(), array.size());
+ String text;
+ text.parse_utf8((const char *)array.ptr(), array.size());
+
+ String err_txt;
+ int err_line;
+ Variant v;
+ err = JSON::parse(text, v, err_txt, err_line);
+ if (err != OK) {
+ _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
+ return err;
+ }
+ state->json = v;
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_bone_attachment(Ref<GLTFState> state) {
+ for (int skeleton_i = 0; skeleton_i < state->skeletons.size(); skeleton_i++) {
+ for (int attachment_i = 0; attachment_i < state->skeletons[skeleton_i]->bone_attachments.size(); attachment_i++) {
+ BoneAttachment3D *bone_attachment = state->skeletons[skeleton_i]->bone_attachments[attachment_i];
+ String bone_name = bone_attachment->get_bone_name();
+ bone_name = _sanitize_bone_name(bone_name);
+ int32_t bone = state->skeletons[skeleton_i]->godot_skeleton->find_bone(bone_name);
+ ERR_CONTINUE(bone == -1);
+ for (int skin_i = 0; skin_i < state->skins.size(); skin_i++) {
+ if (state->skins[skin_i]->skeleton != skeleton_i) {
+ continue;
+ }
+
+ for (int node_i = 0; node_i < bone_attachment->get_child_count(); node_i++) {
+ ERR_CONTINUE(bone >= state->skins[skin_i]->joints.size());
+ _convert_scene_node(state, bone_attachment->get_child(node_i), bone_attachment->get_owner(), state->skins[skin_i]->joints[bone], 0);
+ }
+ break;
+ }
+ }
+ }
+ return OK;
+}
+
+Error GLTFDocument::_parse_glb(const String &p_path, Ref<GLTFState> state) {
+ Error err;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (!f) {
+ return err;
+ }
+
+ uint32_t magic = f->get_32();
+ ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
+ f->get_32(); // version
+ f->get_32(); // length
+
+ uint32_t chunk_length = f->get_32();
+ uint32_t chunk_type = f->get_32();
+
+ ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
+ Vector<uint8_t> json_data;
+ json_data.resize(chunk_length);
+ uint32_t len = f->get_buffer(json_data.ptrw(), chunk_length);
+ ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
+
+ String text;
+ text.parse_utf8((const char *)json_data.ptr(), json_data.size());
+
+ String err_txt;
+ int err_line;
+ Variant v;
+ err = JSON::parse(text, v, err_txt, err_line);
+ if (err != OK) {
+ _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
+ return err;
+ }
+
+ state->json = v;
+
+ //data?
+
+ chunk_length = f->get_32();
+ chunk_type = f->get_32();
+
+ if (f->eof_reached()) {
+ return OK; //all good
+ }
+
+ ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
+
+ state->glb_data.resize(chunk_length);
+ len = f->get_buffer(state->glb_data.ptrw(), chunk_length);
+ ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
+
+ return OK;
+}
+
+static Array _vec3_to_arr(const Vector3 &p_vec3) {
+ Array array;
+ array.resize(3);
+ array[0] = p_vec3.x;
+ array[1] = p_vec3.y;
+ array[2] = p_vec3.z;
+ return array;
+}
+
+static Vector3 _arr_to_vec3(const Array &p_array) {
+ ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
+ return Vector3(p_array[0], p_array[1], p_array[2]);
+}
+
+static Array _quat_to_array(const Quat &p_quat) {
+ Array array;
+ array.resize(4);
+ array[0] = p_quat.x;
+ array[1] = p_quat.y;
+ array[2] = p_quat.z;
+ array[3] = p_quat.w;
+ return array;
+}
+
+static Quat _arr_to_quat(const Array &p_array) {
+ ERR_FAIL_COND_V(p_array.size() != 4, Quat());
+ return Quat(p_array[0], p_array[1], p_array[2], p_array[3]);
+}
+
+static Transform _arr_to_xform(const Array &p_array) {
+ ERR_FAIL_COND_V(p_array.size() != 16, Transform());
+
+ Transform xform;
+ xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
+ xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
+ xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
+ xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
+
+ return xform;
+}
+
+static Vector<real_t> _xform_to_array(const Transform p_transform) {
+ Vector<real_t> array;
+ array.resize(16);
+ Vector3 axis_x = p_transform.get_basis().get_axis(Vector3::AXIS_X);
+ array.write[0] = axis_x.x;
+ array.write[1] = axis_x.y;
+ array.write[2] = axis_x.z;
+ array.write[3] = 0.0f;
+ Vector3 axis_y = p_transform.get_basis().get_axis(Vector3::AXIS_Y);
+ array.write[4] = axis_y.x;
+ array.write[5] = axis_y.y;
+ array.write[6] = axis_y.z;
+ array.write[7] = 0.0f;
+ Vector3 axis_z = p_transform.get_basis().get_axis(Vector3::AXIS_Z);
+ array.write[8] = axis_z.x;
+ array.write[9] = axis_z.y;
+ array.write[10] = axis_z.z;
+ array.write[11] = 0.0f;
+ Vector3 origin = p_transform.get_origin();
+ array.write[12] = origin.x;
+ array.write[13] = origin.y;
+ array.write[14] = origin.z;
+ array.write[15] = 1.0f;
+ return array;
+}
+
+Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) {
+ Array nodes;
+ for (int i = 0; i < state->nodes.size(); i++) {
+ Dictionary node;
+ Ref<GLTFNode> n = state->nodes[i];
+ Dictionary extensions;
+ node["extensions"] = extensions;
+ if (!n->get_name().is_empty()) {
+ node["name"] = n->get_name();
+ }
+ if (n->camera != -1) {
+ node["camera"] = n->camera;
+ }
+ if (n->light != -1) {
+ Dictionary lights_punctual;
+ extensions["KHR_lights_punctual"] = lights_punctual;
+ lights_punctual["light"] = n->light;
+ }
+ if (n->mesh != -1) {
+ node["mesh"] = n->mesh;
+ }
+ if (n->skin != -1) {
+ node["skin"] = n->skin;
+ }
+ if (n->skeleton != -1 && n->skin < 0) {
+ }
+ if (n->xform != Transform()) {
+ node["matrix"] = _xform_to_array(n->xform);
+ }
+
+ if (!n->rotation.is_equal_approx(Quat())) {
+ node["rotation"] = _quat_to_array(n->rotation);
+ }
+
+ if (!n->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) {
+ node["scale"] = _vec3_to_arr(n->scale);
+ }
+
+ if (!n->translation.is_equal_approx(Vector3())) {
+ node["translation"] = _vec3_to_arr(n->translation);
+ }
+ if (n->children.size()) {
+ Array children;
+ for (int j = 0; j < n->children.size(); j++) {
+ children.push_back(n->children[j]);
+ }
+ node["children"] = children;
+ }
+ nodes.push_back(node);
+ }
+ state->json["nodes"] = nodes;
+ return OK;
+}
+
+String GLTFDocument::_sanitize_scene_name(const String &name) {
+ RegEx regex("([^a-zA-Z0-9_ -]+)");
+ String p_name = regex.sub(name, "", true);
+ return p_name;
+}
+
+String GLTFDocument::_gen_unique_name(Ref<GLTFState> state, const String &p_name) {
+ const String s_name = _sanitize_scene_name(p_name);
+
+ String name;
+ int index = 1;
+ while (true) {
+ name = s_name;
+
+ if (index > 1) {
+ name += " " + itos(index);
+ }
+ if (!state->unique_names.has(name)) {
+ break;
+ }
+ index++;
+ }
+
+ state->unique_names.insert(name);
+
+ return name;
+}
+
+String GLTFDocument::_sanitize_bone_name(const String &name) {
+ String p_name = name.camelcase_to_underscore(true);
+
+ RegEx pattern_nocolon(":");
+ p_name = pattern_nocolon.sub(p_name, "_", true);
+
+ RegEx pattern_noslash("/");
+ p_name = pattern_noslash.sub(p_name, "_", true);
+
+ RegEx pattern_nospace(" +");
+ p_name = pattern_nospace.sub(p_name, "_", true);
+
+ RegEx pattern_multiple("_+");
+ p_name = pattern_multiple.sub(p_name, "_", true);
+
+ RegEx pattern_padded("0+(\\d+)");
+ p_name = pattern_padded.sub(p_name, "$1", true);
+
+ return p_name;
+}
+
+String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i, const String &p_name) {
+ String s_name = _sanitize_bone_name(p_name);
+ if (s_name.is_empty()) {
+ s_name = "bone";
+ }
+ String name;
+ int index = 1;
+ while (true) {
+ name = s_name;
+
+ if (index > 1) {
+ name += "_" + itos(index);
+ }
+ if (!state->skeletons[skel_i]->unique_names.has(name)) {
+ break;
+ }
+ index++;
+ }
+
+ state->skeletons.write[skel_i]->unique_names.insert(name);
+
+ return name;
+}
+
+Error GLTFDocument::_parse_scenes(Ref<GLTFState> state) {
+ ERR_FAIL_COND_V(!state->json.has("scenes"), ERR_FILE_CORRUPT);
+ const Array &scenes = state->json["scenes"];
+ int loaded_scene = 0;
+ if (state->json.has("scene")) {
+ loaded_scene = state->json["scene"];
+ } else {
+ WARN_PRINT("The load-time scene is not defined in the glTF2 file. Picking the first scene.");
+ }
+
+ if (scenes.size()) {
+ ERR_FAIL_COND_V(loaded_scene >= scenes.size(), ERR_FILE_CORRUPT);
+ const Dictionary &s = scenes[loaded_scene];
+ ERR_FAIL_COND_V(!s.has("nodes"), ERR_UNAVAILABLE);
+ const Array &nodes = s["nodes"];
+ for (int j = 0; j < nodes.size(); j++) {
+ state->root_nodes.push_back(nodes[j]);
+ }
+
+ if (s.has("name") && s["name"] != "") {
+ state->scene_name = _gen_unique_name(state, s["name"]);
+ } else {
+ state->scene_name = _gen_unique_name(state, "Scene");
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) {
+ ERR_FAIL_COND_V(!state->json.has("nodes"), ERR_FILE_CORRUPT);
+ const Array &nodes = state->json["nodes"];
+ for (int i = 0; i < nodes.size(); i++) {
+ Ref<GLTFNode> node;
+ node.instance();
+ const Dictionary &n = nodes[i];
+
+ if (n.has("name")) {
+ node->set_name(n["name"]);
+ }
+ if (n.has("camera")) {
+ node->camera = n["camera"];
+ }
+ if (n.has("mesh")) {
+ node->mesh = n["mesh"];
+ }
+ if (n.has("skin")) {
+ node->skin = n["skin"];
+ }
+ if (n.has("matrix")) {
+ node->xform = _arr_to_xform(n["matrix"]);
+ } else {
+ if (n.has("translation")) {
+ node->translation = _arr_to_vec3(n["translation"]);
+ }
+ if (n.has("rotation")) {
+ node->rotation = _arr_to_quat(n["rotation"]);
+ }
+ if (n.has("scale")) {
+ node->scale = _arr_to_vec3(n["scale"]);
+ }
+
+ node->xform.basis.set_quat_scale(node->rotation, node->scale);
+ node->xform.origin = node->translation;
+ }
+
+ if (n.has("extensions")) {
+ Dictionary extensions = n["extensions"];
+ if (extensions.has("KHR_lights_punctual")) {
+ Dictionary lights_punctual = extensions["KHR_lights_punctual"];
+ if (lights_punctual.has("light")) {
+ GLTFLightIndex light = lights_punctual["light"];
+ node->light = light;
+ }
+ }
+ }
+
+ if (n.has("children")) {
+ const Array &children = n["children"];
+ for (int j = 0; j < children.size(); j++) {
+ node->children.push_back(children[j]);
+ }
+ }
+
+ state->nodes.push_back(node);
+ }
+
+ // build the hierarchy
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); node_i++) {
+ for (int j = 0; j < state->nodes[node_i]->children.size(); j++) {
+ GLTFNodeIndex child_i = state->nodes[node_i]->children[j];
+
+ ERR_FAIL_INDEX_V(child_i, state->nodes.size(), ERR_FILE_CORRUPT);
+ ERR_CONTINUE(state->nodes[child_i]->parent != -1); //node already has a parent, wtf.
+
+ state->nodes.write[child_i]->parent = node_i;
+ }
+ }
+
+ _compute_node_heights(state);
+
+ return OK;
+}
+
+void GLTFDocument::_compute_node_heights(Ref<GLTFState> state) {
+ state->root_nodes.clear();
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); ++node_i) {
+ Ref<GLTFNode> node = state->nodes[node_i];
+ node->height = 0;
+
+ GLTFNodeIndex current_i = node_i;
+ while (current_i >= 0) {
+ const GLTFNodeIndex parent_i = state->nodes[current_i]->parent;
+ if (parent_i >= 0) {
+ ++node->height;
+ }
+ current_i = parent_i;
+ }
+
+ if (node->height == 0) {
+ state->root_nodes.push_back(node_i);
+ }
+ }
+}
+
+static Vector<uint8_t> _parse_base64_uri(const String &uri) {
+ int start = uri.find(",");
+ ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
+
+ CharString substr = uri.right(start + 1).ascii();
+
+ int strlen = substr.length();
+
+ Vector<uint8_t> buf;
+ buf.resize(strlen / 4 * 3 + 1 + 1);
+
+ size_t len = 0;
+ ERR_FAIL_COND_V(CryptoCore::b64_decode(buf.ptrw(), buf.size(), &len, (unsigned char *)substr.get_data(), strlen) != OK, Vector<uint8_t>());
+
+ buf.resize(len);
+
+ return buf;
+}
+Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> state, const String &p_path) {
+ print_verbose("glTF: Total buffers: " + itos(state->buffers.size()));
+
+ if (!state->buffers.size()) {
+ return OK;
+ }
+ Array buffers;
+ if (state->buffers.size()) {
+ Vector<uint8_t> buffer_data = state->buffers[0];
+ Dictionary gltf_buffer;
+
+ gltf_buffer["byteLength"] = buffer_data.size();
+ buffers.push_back(gltf_buffer);
+ }
+
+ for (GLTFBufferIndex i = 1; i < state->buffers.size() - 1; i++) {
+ Vector<uint8_t> buffer_data = state->buffers[i];
+ Dictionary gltf_buffer;
+ String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
+ String path = p_path.get_base_dir() + "/" + filename;
+ Error err;
+ FileAccessRef f = FileAccess::open(path, FileAccess::WRITE, &err);
+ if (!f) {
+ return err;
+ }
+ if (buffer_data.size() == 0) {
+ return OK;
+ }
+ f->create(FileAccess::ACCESS_RESOURCES);
+ f->store_buffer(buffer_data.ptr(), buffer_data.size());
+ f->close();
+ gltf_buffer["uri"] = filename;
+ gltf_buffer["byteLength"] = buffer_data.size();
+ buffers.push_back(gltf_buffer);
+ }
+ state->json["buffers"] = buffers;
+
+ return OK;
+}
+
+Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> state, const String &p_path) {
+ print_verbose("glTF: Total buffers: " + itos(state->buffers.size()));
+
+ if (!state->buffers.size()) {
+ return OK;
+ }
+ Array buffers;
+
+ for (GLTFBufferIndex i = 0; i < state->buffers.size(); i++) {
+ Vector<uint8_t> buffer_data = state->buffers[i];
+ Dictionary gltf_buffer;
+ String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
+ String path = p_path.get_base_dir() + "/" + filename;
+ Error err;
+ FileAccessRef f = FileAccess::open(path, FileAccess::WRITE, &err);
+ if (!f) {
+ return err;
+ }
+ if (buffer_data.size() == 0) {
+ return OK;
+ }
+ f->create(FileAccess::ACCESS_RESOURCES);
+ f->store_buffer(buffer_data.ptr(), buffer_data.size());
+ f->close();
+ gltf_buffer["uri"] = filename;
+ gltf_buffer["byteLength"] = buffer_data.size();
+ buffers.push_back(gltf_buffer);
+ }
+ state->json["buffers"] = buffers;
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_buffers(Ref<GLTFState> state, const String &p_base_path) {
+ if (!state->json.has("buffers")) {
+ return OK;
+ }
+
+ const Array &buffers = state->json["buffers"];
+ for (GLTFBufferIndex i = 0; i < buffers.size(); i++) {
+ if (i == 0 && state->glb_data.size()) {
+ state->buffers.push_back(state->glb_data);
+
+ } else {
+ const Dictionary &buffer = buffers[i];
+ if (buffer.has("uri")) {
+ Vector<uint8_t> buffer_data;
+ String uri = buffer["uri"];
+
+ if (uri.begins_with("data:")) { // Embedded data using base64.
+ // Validate data MIME types and throw an error if it's one we don't know/support.
+ if (!uri.begins_with("data:application/octet-stream;base64") &&
+ !uri.begins_with("data:application/gltf-buffer;base64")) {
+ ERR_PRINT("glTF: Got buffer with an unknown URI data type: " + uri);
+ }
+ buffer_data = _parse_base64_uri(uri);
+ } else { // Relative path to an external image file.
+ uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows.
+ buffer_data = FileAccess::get_file_as_array(uri);
+ ERR_FAIL_COND_V_MSG(buffer.size() == 0, ERR_PARSE_ERROR, "glTF: Couldn't load binary file as an array: " + uri);
+ }
+
+ ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
+ int byteLength = buffer["byteLength"];
+ ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
+ state->buffers.push_back(buffer_data);
+ }
+ }
+ }
+
+ print_verbose("glTF: Total buffers: " + itos(state->buffers.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_encode_buffer_views(Ref<GLTFState> state) {
+ Array buffers;
+ for (GLTFBufferViewIndex i = 0; i < state->buffer_views.size(); i++) {
+ Dictionary d;
+
+ Ref<GLTFBufferView> buffer_view = state->buffer_views[i];
+
+ d["buffer"] = buffer_view->buffer;
+ d["byteLength"] = buffer_view->byte_length;
+
+ d["byteOffset"] = buffer_view->byte_offset;
+
+ if (buffer_view->byte_stride != -1) {
+ d["byteStride"] = buffer_view->byte_stride;
+ }
+
+ // TODO Sparse
+ // d["target"] = buffer_view->indices;
+
+ ERR_FAIL_COND_V(!d.has("buffer"), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!d.has("byteLength"), ERR_INVALID_DATA);
+ buffers.push_back(d);
+ }
+ print_verbose("glTF: Total buffer views: " + itos(state->buffer_views.size()));
+ state->json["bufferViews"] = buffers;
+ return OK;
+}
+
+Error GLTFDocument::_parse_buffer_views(Ref<GLTFState> state) {
+ if (!state->json.has("bufferViews")) {
+ return OK;
+ }
+ const Array &buffers = state->json["bufferViews"];
+ for (GLTFBufferViewIndex i = 0; i < buffers.size(); i++) {
+ const Dictionary &d = buffers[i];
+
+ Ref<GLTFBufferView> buffer_view;
+ buffer_view.instance();
+
+ ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
+ buffer_view->buffer = d["buffer"];
+ ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
+ buffer_view->byte_length = d["byteLength"];
+
+ if (d.has("byteOffset")) {
+ buffer_view->byte_offset = d["byteOffset"];
+ }
+
+ if (d.has("byteStride")) {
+ buffer_view->byte_stride = d["byteStride"];
+ }
+
+ if (d.has("target")) {
+ const int target = d["target"];
+ buffer_view->indices = target == GLTFDocument::ELEMENT_ARRAY_BUFFER;
+ }
+
+ state->buffer_views.push_back(buffer_view);
+ }
+
+ print_verbose("glTF: Total buffer views: " + itos(state->buffer_views.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_encode_accessors(Ref<GLTFState> state) {
+ Array accessors;
+ for (GLTFAccessorIndex i = 0; i < state->accessors.size(); i++) {
+ Dictionary d;
+
+ Ref<GLTFAccessor> accessor = state->accessors[i];
+ d["componentType"] = accessor->component_type;
+ d["count"] = accessor->count;
+ d["type"] = _get_accessor_type_name(accessor->type);
+ d["byteOffset"] = accessor->byte_offset;
+ d["normalized"] = accessor->normalized;
+ d["max"] = accessor->max;
+ d["min"] = accessor->min;
+ d["bufferView"] = accessor->buffer_view; //optional because it may be sparse...
+
+ // Dictionary s;
+ // s["count"] = accessor->sparse_count;
+ // ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
+
+ // s["indices"] = accessor->sparse_accessors;
+ // ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
+
+ // Dictionary si;
+
+ // si["bufferView"] = accessor->sparse_indices_buffer_view;
+
+ // ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
+ // si["componentType"] = accessor->sparse_indices_component_type;
+
+ // if (si.has("byteOffset")) {
+ // si["byteOffset"] = accessor->sparse_indices_byte_offset;
+ // }
+
+ // ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
+ // s["indices"] = si;
+ // Dictionary sv;
+
+ // sv["bufferView"] = accessor->sparse_values_buffer_view;
+ // if (sv.has("byteOffset")) {
+ // sv["byteOffset"] = accessor->sparse_values_byte_offset;
+ // }
+ // ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
+ // s["values"] = sv;
+ // ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
+ // d["sparse"] = s;
+ accessors.push_back(d);
+ }
+
+ state->json["accessors"] = accessors;
+ ERR_FAIL_COND_V(!state->json.has("accessors"), ERR_FILE_CORRUPT);
+ print_verbose("glTF: Total accessors: " + itos(state->accessors.size()));
+
+ return OK;
+}
+
+String GLTFDocument::_get_accessor_type_name(const GLTFDocument::GLTFType p_type) {
+ if (p_type == GLTFDocument::TYPE_SCALAR) {
+ return "SCALAR";
+ }
+ if (p_type == GLTFDocument::TYPE_VEC2) {
+ return "VEC2";
+ }
+ if (p_type == GLTFDocument::TYPE_VEC3) {
+ return "VEC3";
+ }
+ if (p_type == GLTFDocument::TYPE_VEC4) {
+ return "VEC4";
+ }
+
+ if (p_type == GLTFDocument::TYPE_MAT2) {
+ return "MAT2";
+ }
+ if (p_type == GLTFDocument::TYPE_MAT3) {
+ return "MAT3";
+ }
+ if (p_type == GLTFDocument::TYPE_MAT4) {
+ return "MAT4";
+ }
+ ERR_FAIL_V("SCALAR");
+}
+
+GLTFDocument::GLTFType GLTFDocument::_get_type_from_str(const String &p_string) {
+ if (p_string == "SCALAR")
+ return GLTFDocument::TYPE_SCALAR;
+
+ if (p_string == "VEC2")
+ return GLTFDocument::TYPE_VEC2;
+ if (p_string == "VEC3")
+ return GLTFDocument::TYPE_VEC3;
+ if (p_string == "VEC4")
+ return GLTFDocument::TYPE_VEC4;
+
+ if (p_string == "MAT2")
+ return GLTFDocument::TYPE_MAT2;
+ if (p_string == "MAT3")
+ return GLTFDocument::TYPE_MAT3;
+ if (p_string == "MAT4")
+ return GLTFDocument::TYPE_MAT4;
+
+ ERR_FAIL_V(GLTFDocument::TYPE_SCALAR);
+}
+
+Error GLTFDocument::_parse_accessors(Ref<GLTFState> state) {
+ if (!state->json.has("accessors")) {
+ return OK;
+ }
+ const Array &accessors = state->json["accessors"];
+ for (GLTFAccessorIndex i = 0; i < accessors.size(); i++) {
+ const Dictionary &d = accessors[i];
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+
+ ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
+ accessor->component_type = d["componentType"];
+ ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
+ accessor->count = d["count"];
+ ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
+ accessor->type = _get_type_from_str(d["type"]);
+
+ if (d.has("bufferView")) {
+ accessor->buffer_view = d["bufferView"]; //optional because it may be sparse...
+ }
+
+ if (d.has("byteOffset")) {
+ accessor->byte_offset = d["byteOffset"];
+ }
+
+ if (d.has("normalized")) {
+ accessor->normalized = d["normalized"];
+ }
+
+ if (d.has("max")) {
+ accessor->max = d["max"];
+ }
+
+ if (d.has("min")) {
+ accessor->min = d["min"];
+ }
+
+ if (d.has("sparse")) {
+ //eeh..
+
+ const Dictionary &s = d["sparse"];
+
+ ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
+ accessor->sparse_count = s["count"];
+ ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
+ const Dictionary &si = s["indices"];
+
+ ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
+ accessor->sparse_indices_buffer_view = si["bufferView"];
+ ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
+ accessor->sparse_indices_component_type = si["componentType"];
+
+ if (si.has("byteOffset")) {
+ accessor->sparse_indices_byte_offset = si["byteOffset"];
+ }
+
+ ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
+ const Dictionary &sv = s["values"];
+
+ ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
+ accessor->sparse_values_buffer_view = sv["bufferView"];
+ if (sv.has("byteOffset")) {
+ accessor->sparse_values_byte_offset = sv["byteOffset"];
+ }
+ }
+
+ state->accessors.push_back(accessor);
+ }
+
+ print_verbose("glTF: Total accessors: " + itos(state->accessors.size()));
+
+ return OK;
+}
+
+double GLTFDocument::_filter_number(double p_float) {
+ if (Math::is_nan(p_float)) {
+ return 0.0f;
+ }
+ return p_float;
+}
+
+String GLTFDocument::_get_component_type_name(const uint32_t p_component) {
+ switch (p_component) {
+ case GLTFDocument::COMPONENT_TYPE_BYTE:
+ return "Byte";
+ case GLTFDocument::COMPONENT_TYPE_UNSIGNED_BYTE:
+ return "UByte";
+ case GLTFDocument::COMPONENT_TYPE_SHORT:
+ return "Short";
+ case GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT:
+ return "UShort";
+ case GLTFDocument::COMPONENT_TYPE_INT:
+ return "Int";
+ case GLTFDocument::COMPONENT_TYPE_FLOAT:
+ return "Float";
+ }
+
+ return "<Error>";
+}
+
+String GLTFDocument::_get_type_name(const GLTFType p_component) {
+ static const char *names[] = {
+ "float",
+ "vec2",
+ "vec3",
+ "vec4",
+ "mat2",
+ "mat3",
+ "mat4"
+ };
+
+ return names[p_component];
+}
+
+Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, const int count, const GLTFType type, const int component_type, const bool normalized, const int byte_offset, const bool for_vertex, GLTFBufferViewIndex &r_accessor) {
+ const int component_count_for_type[7] = {
+ 1, 2, 3, 4, 4, 9, 16
+ };
+
+ const int component_count = component_count_for_type[type];
+ const int component_size = _get_component_type_size(component_type);
+ ERR_FAIL_COND_V(component_size == 0, FAILED);
+
+ int skip_every = 0;
+ int skip_bytes = 0;
+ //special case of alignments, as described in spec
+ switch (component_type) {
+ case COMPONENT_TYPE_BYTE:
+ case COMPONENT_TYPE_UNSIGNED_BYTE: {
+ if (type == TYPE_MAT2) {
+ skip_every = 2;
+ skip_bytes = 2;
+ }
+ if (type == TYPE_MAT3) {
+ skip_every = 3;
+ skip_bytes = 1;
+ }
+ } break;
+ case COMPONENT_TYPE_SHORT:
+ case COMPONENT_TYPE_UNSIGNED_SHORT: {
+ if (type == TYPE_MAT3) {
+ skip_every = 6;
+ skip_bytes = 4;
+ }
+ } break;
+ default: {
+ }
+ }
+
+ Ref<GLTFBufferView> bv;
+ bv.instance();
+ const uint32_t offset = bv->byte_offset = byte_offset;
+ Vector<uint8_t> &gltf_buffer = state->buffers.write[0];
+
+ int stride = _get_component_type_size(component_type);
+ if (for_vertex && stride % 4) {
+ stride += 4 - (stride % 4); //according to spec must be multiple of 4
+ }
+ //use to debug
+ print_verbose("glTF: encoding type " + _get_type_name(type) + " component type: " + _get_component_type_name(component_type) + " stride: " + itos(stride) + " amount " + itos(count));
+
+ print_verbose("glTF: encoding accessor offset " + itos(byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(gltf_buffer.size()) + " view len " + itos(bv->byte_length));
+
+ const int buffer_end = (stride * (count - 1)) + _get_component_type_size(component_type);
+ // TODO define bv->byte_stride
+ bv->byte_offset = gltf_buffer.size();
+
+ switch (component_type) {
+ case COMPONENT_TYPE_BYTE: {
+ Vector<int8_t> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ if (normalized) {
+ buffer.write[dst_i] = d * 128.0;
+ } else {
+ buffer.write[dst_i] = d;
+ }
+ src++;
+ dst_i++;
+ }
+ }
+ int64_t old_size = gltf_buffer.size();
+ gltf_buffer.resize(old_size + (buffer.size() * sizeof(int8_t)));
+ copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t));
+ bv->byte_length = buffer.size() * sizeof(int8_t);
+ } break;
+ case COMPONENT_TYPE_UNSIGNED_BYTE: {
+ Vector<uint8_t> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ if (normalized) {
+ buffer.write[dst_i] = d * 255.0;
+ } else {
+ buffer.write[dst_i] = d;
+ }
+ src++;
+ dst_i++;
+ }
+ }
+ gltf_buffer.append_array(buffer);
+ bv->byte_length = buffer.size() * sizeof(uint8_t);
+ } break;
+ case COMPONENT_TYPE_SHORT: {
+ Vector<int16_t> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ if (normalized) {
+ buffer.write[dst_i] = d * 32768.0;
+ } else {
+ buffer.write[dst_i] = d;
+ }
+ src++;
+ dst_i++;
+ }
+ }
+ int64_t old_size = gltf_buffer.size();
+ gltf_buffer.resize(old_size + (buffer.size() * sizeof(int16_t)));
+ copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t));
+ bv->byte_length = buffer.size() * sizeof(int16_t);
+ } break;
+ case COMPONENT_TYPE_UNSIGNED_SHORT: {
+ Vector<uint16_t> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ if (normalized) {
+ buffer.write[dst_i] = d * 65535.0;
+ } else {
+ buffer.write[dst_i] = d;
+ }
+ src++;
+ dst_i++;
+ }
+ }
+ int64_t old_size = gltf_buffer.size();
+ gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint16_t)));
+ copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t));
+ bv->byte_length = buffer.size() * sizeof(uint16_t);
+ } break;
+ case COMPONENT_TYPE_INT: {
+ Vector<int> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ buffer.write[dst_i] = d;
+ src++;
+ dst_i++;
+ }
+ }
+ int64_t old_size = gltf_buffer.size();
+ gltf_buffer.resize(old_size + (buffer.size() * sizeof(int32_t)));
+ copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int32_t));
+ bv->byte_length = buffer.size() * sizeof(int32_t);
+ } break;
+ case COMPONENT_TYPE_FLOAT: {
+ Vector<float> buffer;
+ buffer.resize(count * component_count);
+ int32_t dst_i = 0;
+ for (int i = 0; i < count; i++) {
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ dst_i += skip_bytes;
+ }
+ double d = *src;
+ buffer.write[dst_i] = d;
+ src++;
+ dst_i++;
+ }
+ }
+ int64_t old_size = gltf_buffer.size();
+ gltf_buffer.resize(old_size + (buffer.size() * sizeof(float)));
+ copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float));
+ bv->byte_length = buffer.size() * sizeof(float);
+ } break;
+ }
+ ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_INVALID_DATA);
+
+ ERR_FAIL_COND_V((int)(offset + buffer_end) > gltf_buffer.size(), ERR_INVALID_DATA);
+ r_accessor = bv->buffer = state->buffer_views.size();
+ state->buffer_views.push_back(bv);
+ return OK;
+}
+
+Error GLTFDocument::_decode_buffer_view(Ref<GLTFState> state, double *dst, const GLTFBufferViewIndex p_buffer_view, const int skip_every, const int skip_bytes, const int element_size, const int count, const GLTFType type, const int component_count, const int component_type, const int component_size, const bool normalized, const int byte_offset, const bool for_vertex) {
+ const Ref<GLTFBufferView> bv = state->buffer_views[p_buffer_view];
+
+ int stride = element_size;
+ if (bv->byte_stride != -1) {
+ stride = bv->byte_stride;
+ }
+ if (for_vertex && stride % 4) {
+ stride += 4 - (stride % 4); //according to spec must be multiple of 4
+ }
+
+ ERR_FAIL_INDEX_V(bv->buffer, state->buffers.size(), ERR_PARSE_ERROR);
+
+ const uint32_t offset = bv->byte_offset + byte_offset;
+ Vector<uint8_t> buffer = state->buffers[bv->buffer]; //copy on write, so no performance hit
+ const uint8_t *bufptr = buffer.ptr();
+
+ //use to debug
+ print_verbose("glTF: type " + _get_type_name(type) + " component type: " + _get_component_type_name(component_type) + " stride: " + itos(stride) + " amount " + itos(count));
+ print_verbose("glTF: accessor offset " + itos(byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv->byte_length));
+
+ const int buffer_end = (stride * (count - 1)) + element_size;
+ ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_PARSE_ERROR);
+
+ ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
+
+ //fill everything as doubles
+
+ for (int i = 0; i < count; i++) {
+ const uint8_t *src = &bufptr[offset + i * stride];
+
+ for (int j = 0; j < component_count; j++) {
+ if (skip_every && j > 0 && (j % skip_every) == 0) {
+ src += skip_bytes;
+ }
+
+ double d = 0;
+
+ switch (component_type) {
+ case COMPONENT_TYPE_BYTE: {
+ int8_t b = int8_t(*src);
+ if (normalized) {
+ d = (double(b) / 128.0);
+ } else {
+ d = double(b);
+ }
+ } break;
+ case COMPONENT_TYPE_UNSIGNED_BYTE: {
+ uint8_t b = *src;
+ if (normalized) {
+ d = (double(b) / 255.0);
+ } else {
+ d = double(b);
+ }
+ } break;
+ case COMPONENT_TYPE_SHORT: {
+ int16_t s = *(int16_t *)src;
+ if (normalized) {
+ d = (double(s) / 32768.0);
+ } else {
+ d = double(s);
+ }
+ } break;
+ case COMPONENT_TYPE_UNSIGNED_SHORT: {
+ uint16_t s = *(uint16_t *)src;
+ if (normalized) {
+ d = (double(s) / 65535.0);
+ } else {
+ d = double(s);
+ }
+ } break;
+ case COMPONENT_TYPE_INT: {
+ d = *(int *)src;
+ } break;
+ case COMPONENT_TYPE_FLOAT: {
+ d = *(float *)src;
+ } break;
+ }
+
+ *dst++ = d;
+ src += component_size;
+ }
+ }
+
+ return OK;
+}
+
+int GLTFDocument::_get_component_type_size(const int component_type) {
+ switch (component_type) {
+ case COMPONENT_TYPE_BYTE:
+ case COMPONENT_TYPE_UNSIGNED_BYTE:
+ return 1;
+ break;
+ case COMPONENT_TYPE_SHORT:
+ case COMPONENT_TYPE_UNSIGNED_SHORT:
+ return 2;
+ break;
+ case COMPONENT_TYPE_INT:
+ case COMPONENT_TYPE_FLOAT:
+ return 4;
+ break;
+ default: {
+ ERR_FAIL_V(0);
+ }
+ }
+ return 0;
+}
+
+Vector<double> GLTFDocument::_decode_accessor(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ //spec, for reference:
+ //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
+
+ ERR_FAIL_INDEX_V(p_accessor, state->accessors.size(), Vector<double>());
+
+ const Ref<GLTFAccessor> a = state->accessors[p_accessor];
+
+ const int component_count_for_type[7] = {
+ 1, 2, 3, 4, 4, 9, 16
+ };
+
+ const int component_count = component_count_for_type[a->type];
+ const int component_size = _get_component_type_size(a->component_type);
+ ERR_FAIL_COND_V(component_size == 0, Vector<double>());
+ int element_size = component_count * component_size;
+
+ int skip_every = 0;
+ int skip_bytes = 0;
+ //special case of alignments, as described in spec
+ switch (a->component_type) {
+ case COMPONENT_TYPE_BYTE:
+ case COMPONENT_TYPE_UNSIGNED_BYTE: {
+ if (a->type == TYPE_MAT2) {
+ skip_every = 2;
+ skip_bytes = 2;
+ element_size = 8; //override for this case
+ }
+ if (a->type == TYPE_MAT3) {
+ skip_every = 3;
+ skip_bytes = 1;
+ element_size = 12; //override for this case
+ }
+ } break;
+ case COMPONENT_TYPE_SHORT:
+ case COMPONENT_TYPE_UNSIGNED_SHORT: {
+ if (a->type == TYPE_MAT3) {
+ skip_every = 6;
+ skip_bytes = 4;
+ element_size = 16; //override for this case
+ }
+ } break;
+ default: {
+ }
+ }
+
+ Vector<double> dst_buffer;
+ dst_buffer.resize(component_count * a->count);
+ double *dst = dst_buffer.ptrw();
+
+ if (a->buffer_view >= 0) {
+ ERR_FAIL_INDEX_V(a->buffer_view, state->buffer_views.size(), Vector<double>());
+
+ const Error err = _decode_buffer_view(state, dst, a->buffer_view, skip_every, skip_bytes, element_size, a->count, a->type, component_count, a->component_type, component_size, a->normalized, a->byte_offset, p_for_vertex);
+ if (err != OK)
+ return Vector<double>();
+ } else {
+ //fill with zeros, as bufferview is not defined.
+ for (int i = 0; i < (a->count * component_count); i++) {
+ dst_buffer.write[i] = 0;
+ }
+ }
+
+ if (a->sparse_count > 0) {
+ // I could not find any file using this, so this code is so far untested
+ Vector<double> indices;
+ indices.resize(a->sparse_count);
+ const int indices_component_size = _get_component_type_size(a->sparse_indices_component_type);
+
+ Error err = _decode_buffer_view(state, indices.ptrw(), a->sparse_indices_buffer_view, 0, 0, indices_component_size, a->sparse_count, TYPE_SCALAR, 1, a->sparse_indices_component_type, indices_component_size, false, a->sparse_indices_byte_offset, false);
+ if (err != OK)
+ return Vector<double>();
+
+ Vector<double> data;
+ data.resize(component_count * a->sparse_count);
+ err = _decode_buffer_view(state, data.ptrw(), a->sparse_values_buffer_view, skip_every, skip_bytes, element_size, a->sparse_count, a->type, component_count, a->component_type, component_size, a->normalized, a->sparse_values_byte_offset, p_for_vertex);
+ if (err != OK)
+ return Vector<double>();
+
+ for (int i = 0; i < indices.size(); i++) {
+ const int write_offset = int(indices[i]) * component_count;
+
+ for (int j = 0; j < component_count; j++) {
+ dst[write_offset + j] = data[i * component_count + j];
+ }
+ }
+ }
+
+ return dst_buffer;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_ints(Ref<GLTFState> state, const Vector<int32_t> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 1;
+ const int ret_size = p_attribs.size();
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ attribs.write[i] = Math::snapped(p_attribs[i], 1.0);
+ if (i == 0) {
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = attribs[(i * element_count) + type_i];
+ type_min.write[type_i] = attribs[(i * element_count) + type_i];
+ }
+ }
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
+ type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
+ type_max.write[type_i] = _filter_number(type_max.write[type_i]);
+ type_min.write[type_i] = _filter_number(type_min.write[type_i]);
+ }
+ }
+
+ ERR_FAIL_COND_V(attribs.size() == 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_SCALAR;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_INT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = ret_size;
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+Vector<int> GLTFDocument::_decode_accessor_as_ints(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<int> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size();
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = int(attribs_ptr[i]);
+ }
+ }
+ return ret;
+}
+
+Vector<float> GLTFDocument::_decode_accessor_as_floats(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<float> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size();
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = float(attribs_ptr[i]);
+ }
+ }
+ return ret;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec2(Ref<GLTFState> state, const Vector<Vector2> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 2;
+
+ const int ret_size = p_attribs.size() * element_count;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Vector2 attrib = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(attrib.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(attrib.y, CMP_NORMALIZE_TOLERANCE);
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC2;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_color(Ref<GLTFState> state, const Vector<Color> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+
+ const int ret_size = p_attribs.size() * 4;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ const int element_count = 4;
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Color attrib = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+void GLTFDocument::_calc_accessor_min_max(int i, const int element_count, Vector<double> &type_max, Vector<double> attribs, Vector<double> &type_min) {
+ if (i == 0) {
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = attribs[(i * element_count) + type_i];
+ type_min.write[type_i] = attribs[(i * element_count) + type_i];
+ }
+ }
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
+ type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
+ type_max.write[type_i] = _filter_number(type_max.write[type_i]);
+ type_min.write[type_i] = _filter_number(type_min.write[type_i]);
+ }
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_weights(Ref<GLTFState> state, const Vector<Color> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+
+ const int ret_size = p_attribs.size() * 4;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ const int element_count = 4;
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Color attrib = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> state, const Vector<Color> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+
+ const int element_count = 4;
+ const int ret_size = p_attribs.size() * element_count;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Color attrib = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quats(Ref<GLTFState> state, const Vector<Quat> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 4;
+
+ const int ret_size = p_attribs.size() * element_count;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Quat quat = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(quat.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(quat.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 2] = Math::snapped(quat.z, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 3] = Math::snapped(quat.w, CMP_NORMALIZE_TOLERANCE);
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+Vector<Vector2> GLTFDocument::_decode_accessor_as_vec2(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Vector2> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size() / 2;
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]);
+ }
+ }
+ return ret;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_floats(Ref<GLTFState> state, const Vector<real_t> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 1;
+ const int ret_size = p_attribs.size();
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+
+ for (int i = 0; i < p_attribs.size(); i++) {
+ attribs.write[i] = Math::snapped(p_attribs[i], CMP_NORMALIZE_TOLERANCE);
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+
+ ERR_FAIL_COND_V(!attribs.size(), -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_SCALAR;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = ret_size;
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> state, const Vector<Vector3> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 3;
+ const int ret_size = p_attribs.size() * element_count;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Vector3 attrib = p_attribs[i];
+ attribs.write[(i * element_count) + 0] = Math::snapped(attrib.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 1] = Math::snapped(attrib.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[(i * element_count) + 2] = Math::snapped(attrib.z, CMP_NORMALIZE_TOLERANCE);
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC3;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> state, const Vector<Transform> p_attribs, const bool p_for_vertex) {
+ if (p_attribs.size() == 0) {
+ return -1;
+ }
+ const int element_count = 16;
+ const int ret_size = p_attribs.size() * element_count;
+ Vector<double> attribs;
+ attribs.resize(ret_size);
+
+ Vector<double> type_max;
+ type_max.resize(element_count);
+ Vector<double> type_min;
+ type_min.resize(element_count);
+ for (int i = 0; i < p_attribs.size(); i++) {
+ Transform attrib = p_attribs[i];
+ Basis basis = attrib.get_basis();
+ Vector3 axis_0 = basis.get_axis(Vector3::AXIS_X);
+
+ attribs.write[i * element_count + 0] = Math::snapped(axis_0.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 1] = Math::snapped(axis_0.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 2] = Math::snapped(axis_0.z, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 3] = 0.0;
+
+ Vector3 axis_1 = basis.get_axis(Vector3::AXIS_Y);
+ attribs.write[i * element_count + 4] = Math::snapped(axis_1.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 5] = Math::snapped(axis_1.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 6] = Math::snapped(axis_1.z, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 7] = 0.0;
+
+ Vector3 axis_2 = basis.get_axis(Vector3::AXIS_Z);
+ attribs.write[i * element_count + 8] = Math::snapped(axis_2.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 9] = Math::snapped(axis_2.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 10] = Math::snapped(axis_2.z, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 11] = 0.0;
+
+ Vector3 origin = attrib.get_origin();
+ attribs.write[i * element_count + 12] = Math::snapped(origin.x, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 13] = Math::snapped(origin.y, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 14] = Math::snapped(origin.z, CMP_NORMALIZE_TOLERANCE);
+ attribs.write[i * element_count + 15] = 1.0;
+
+ _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
+ }
+ ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
+
+ Ref<GLTFAccessor> accessor;
+ accessor.instance();
+ GLTFBufferIndex buffer_view_i;
+ int64_t size = state->buffers[0].size();
+ const GLTFDocument::GLTFType type = GLTFDocument::TYPE_MAT4;
+ const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
+
+ accessor->max = type_max;
+ accessor->min = type_min;
+ accessor->normalized = false;
+ accessor->count = p_attribs.size();
+ accessor->type = type;
+ accessor->component_type = component_type;
+ accessor->byte_offset = 0;
+ Error err = _encode_buffer_view(state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
+ if (err != OK) {
+ return -1;
+ }
+ accessor->buffer_view = buffer_view_i;
+ state->accessors.push_back(accessor);
+ return state->accessors.size() - 1;
+}
+
+Vector<Vector3> GLTFDocument::_decode_accessor_as_vec3(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Vector3> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size() / 3;
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]);
+ }
+ }
+ return ret;
+}
+
+Vector<Color> GLTFDocument::_decode_accessor_as_color(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Color> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ const int type = state->accessors[p_accessor]->type;
+ ERR_FAIL_COND_V(!(type == TYPE_VEC3 || type == TYPE_VEC4), ret);
+ int vec_len = 3;
+ if (type == TYPE_VEC4) {
+ vec_len = 4;
+ }
+
+ ERR_FAIL_COND_V(attribs.size() % vec_len != 0, ret);
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size() / vec_len;
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = Color(attribs_ptr[i * vec_len + 0], attribs_ptr[i * vec_len + 1], attribs_ptr[i * vec_len + 2], vec_len == 4 ? attribs_ptr[i * 4 + 3] : 1.0);
+ }
+ }
+ return ret;
+}
+Vector<Quat> GLTFDocument::_decode_accessor_as_quat(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Quat> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
+ const double *attribs_ptr = attribs.ptr();
+ const int ret_size = attribs.size() / 4;
+ ret.resize(ret_size);
+ {
+ for (int i = 0; i < ret_size; i++) {
+ ret.write[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
+ }
+ }
+ return ret;
+}
+Vector<Transform2D> GLTFDocument::_decode_accessor_as_xform2d(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Transform2D> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
+ ret.resize(attribs.size() / 4);
+ for (int i = 0; i < ret.size(); i++) {
+ ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
+ ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
+ }
+ return ret;
+}
+
+Vector<Basis> GLTFDocument::_decode_accessor_as_basis(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Basis> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
+ ret.resize(attribs.size() / 9);
+ for (int i = 0; i < ret.size(); i++) {
+ ret.write[i].set_axis(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
+ ret.write[i].set_axis(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
+ ret.write[i].set_axis(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
+ }
+ return ret;
+}
+
+Vector<Transform> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
+ const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
+ Vector<Transform> ret;
+
+ if (attribs.size() == 0)
+ return ret;
+
+ ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
+ ret.resize(attribs.size() / 16);
+ for (int i = 0; i < ret.size(); i++) {
+ ret.write[i].basis.set_axis(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
+ ret.write[i].basis.set_axis(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
+ ret.write[i].basis.set_axis(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
+ ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
+ }
+ return ret;
+}
+
+Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) {
+ Array meshes;
+ for (GLTFMeshIndex gltf_mesh_i = 0; gltf_mesh_i < state->meshes.size(); gltf_mesh_i++) {
+ print_verbose("glTF: Serializing mesh: " + itos(gltf_mesh_i));
+ Ref<EditorSceneImporterMesh> import_mesh = state->meshes.write[gltf_mesh_i]->get_mesh();
+ if (import_mesh.is_null()) {
+ continue;
+ }
+ Array primitives;
+ Array targets;
+ Dictionary gltf_mesh;
+ Array target_names;
+ Array weights;
+ for (int surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) {
+ Dictionary primitive;
+ Mesh::PrimitiveType primitive_type = import_mesh->get_surface_primitive_type(surface_i);
+ switch (primitive_type) {
+ case Mesh::PRIMITIVE_POINTS: {
+ primitive["mode"] = 0;
+ break;
+ }
+ case Mesh::PRIMITIVE_LINES: {
+ primitive["mode"] = 1;
+ break;
+ }
+ // case Mesh::PRIMITIVE_LINE_LOOP: {
+ // primitive["mode"] = 2;
+ // break;
+ // }
+ case Mesh::PRIMITIVE_LINE_STRIP: {
+ primitive["mode"] = 3;
+ break;
+ }
+ case Mesh::PRIMITIVE_TRIANGLES: {
+ primitive["mode"] = 4;
+ break;
+ }
+ case Mesh::PRIMITIVE_TRIANGLE_STRIP: {
+ primitive["mode"] = 5;
+ break;
+ }
+ // case Mesh::PRIMITIVE_TRIANGLE_FAN: {
+ // primitive["mode"] = 6;
+ // break;
+ // }
+ default: {
+ ERR_FAIL_V(FAILED);
+ }
+ }
+
+ Array array = import_mesh->get_surface_arrays(surface_i);
+ Dictionary attributes;
+ {
+ Vector<Vector3> a = array[Mesh::ARRAY_VERTEX];
+ ERR_FAIL_COND_V(!a.size(), ERR_INVALID_DATA);
+ attributes["POSITION"] = _encode_accessor_as_vec3(state, a, true);
+ }
+ {
+ Vector<real_t> a = array[Mesh::ARRAY_TANGENT];
+ if (a.size()) {
+ const int ret_size = a.size() / 4;
+ Vector<Color> attribs;
+ attribs.resize(ret_size);
+ for (int i = 0; i < ret_size; i++) {
+ Color out;
+ out.r = a[(i * 4) + 0];
+ out.g = a[(i * 4) + 1];
+ out.b = a[(i * 4) + 2];
+ out.a = a[(i * 4) + 3];
+ attribs.write[i] = out;
+ }
+ attributes["TANGENT"] = _encode_accessor_as_color(state, attribs, true);
+ }
+ }
+ {
+ Vector<Vector3> a = array[Mesh::ARRAY_NORMAL];
+ if (a.size()) {
+ const int ret_size = a.size();
+ Vector<Vector3> attribs;
+ attribs.resize(ret_size);
+ for (int i = 0; i < ret_size; i++) {
+ attribs.write[i] = Vector3(a[i]).normalized();
+ }
+ attributes["NORMAL"] = _encode_accessor_as_vec3(state, attribs, true);
+ }
+ }
+ {
+ Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV];
+ if (a.size()) {
+ attributes["TEXCOORD_0"] = _encode_accessor_as_vec2(state, a, true);
+ }
+ }
+ {
+ Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV2];
+ if (a.size()) {
+ attributes["TEXCOORD_1"] = _encode_accessor_as_vec2(state, a, true);
+ }
+ }
+ {
+ Vector<Color> a = array[Mesh::ARRAY_COLOR];
+ if (a.size()) {
+ attributes["COLOR_0"] = _encode_accessor_as_color(state, a, true);
+ }
+ }
+ Map<int, int> joint_i_to_bone_i;
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); node_i++) {
+ GLTFSkinIndex skin_i = -1;
+ if (state->nodes[node_i]->mesh == gltf_mesh_i) {
+ skin_i = state->nodes[node_i]->skin;
+ }
+ if (skin_i != -1) {
+ joint_i_to_bone_i = state->skins[skin_i]->joint_i_to_bone_i;
+ break;
+ }
+ }
+ {
+ const Array &a = array[Mesh::ARRAY_BONES];
+ const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
+ if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
+ const int ret_size = a.size() / JOINT_GROUP_SIZE;
+ Vector<Color> attribs;
+ attribs.resize(ret_size);
+ {
+ for (int array_i = 0; array_i < attribs.size(); array_i++) {
+ int32_t joint_0 = a[(array_i * JOINT_GROUP_SIZE) + 0];
+ int32_t joint_1 = a[(array_i * JOINT_GROUP_SIZE) + 1];
+ int32_t joint_2 = a[(array_i * JOINT_GROUP_SIZE) + 2];
+ int32_t joint_3 = a[(array_i * JOINT_GROUP_SIZE) + 3];
+ attribs.write[array_i] = Color(joint_0, joint_1, joint_2, joint_3);
+ }
+ }
+ attributes["JOINTS_0"] = _encode_accessor_as_joints(state, attribs, true);
+ } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
+ int32_t vertex_count = vertex_array.size();
+ Vector<Color> joints_0;
+ joints_0.resize(vertex_count);
+ Vector<Color> joints_1;
+ joints_1.resize(vertex_count);
+ int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
+ for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ Color joint_0;
+ joint_0.r = a[vertex_i * weights_8_count + 0];
+ joint_0.g = a[vertex_i * weights_8_count + 1];
+ joint_0.b = a[vertex_i * weights_8_count + 2];
+ joint_0.a = a[vertex_i * weights_8_count + 3];
+ joints_0.write[vertex_i] = joint_0;
+ Color joint_1;
+ joint_1.r = a[vertex_i * weights_8_count + 4];
+ joint_1.g = a[vertex_i * weights_8_count + 5];
+ joint_1.b = a[vertex_i * weights_8_count + 6];
+ joint_1.a = a[vertex_i * weights_8_count + 7];
+ joints_1.write[vertex_i] = joint_1;
+ }
+ attributes["JOINTS_0"] = _encode_accessor_as_joints(state, joints_0, true);
+ attributes["JOINTS_1"] = _encode_accessor_as_joints(state, joints_1, true);
+ }
+ }
+ {
+ const Array &a = array[Mesh::ARRAY_WEIGHTS];
+ const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
+ if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
+ const int ret_size = a.size() / JOINT_GROUP_SIZE;
+ Vector<Color> attribs;
+ attribs.resize(ret_size);
+ for (int i = 0; i < ret_size; i++) {
+ attribs.write[i] = Color(a[(i * JOINT_GROUP_SIZE) + 0], a[(i * JOINT_GROUP_SIZE) + 1], a[(i * JOINT_GROUP_SIZE) + 2], a[(i * JOINT_GROUP_SIZE) + 3]);
+ }
+ attributes["WEIGHTS_0"] = _encode_accessor_as_weights(state, attribs, true);
+ } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
+ int32_t vertex_count = vertex_array.size();
+ Vector<Color> weights_0;
+ weights_0.resize(vertex_count);
+ Vector<Color> weights_1;
+ weights_1.resize(vertex_count);
+ int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
+ for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ Color weight_0;
+ weight_0.r = a[vertex_i * weights_8_count + 0];
+ weight_0.g = a[vertex_i * weights_8_count + 1];
+ weight_0.b = a[vertex_i * weights_8_count + 2];
+ weight_0.a = a[vertex_i * weights_8_count + 3];
+ weights_0.write[vertex_i] = weight_0;
+ Color weight_1;
+ weight_1.r = a[vertex_i * weights_8_count + 4];
+ weight_1.g = a[vertex_i * weights_8_count + 5];
+ weight_1.b = a[vertex_i * weights_8_count + 6];
+ weight_1.a = a[vertex_i * weights_8_count + 7];
+ weights_1.write[vertex_i] = weight_1;
+ }
+ attributes["WEIGHTS_0"] = _encode_accessor_as_weights(state, weights_0, true);
+ attributes["WEIGHTS_1"] = _encode_accessor_as_weights(state, weights_1, true);
+ }
+ }
+ {
+ Vector<int32_t> mesh_indices = array[Mesh::ARRAY_INDEX];
+ if (mesh_indices.size()) {
+ if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
+ //swap around indices, convert ccw to cw for front face
+ const int is = mesh_indices.size();
+ for (int k = 0; k < is; k += 3) {
+ SWAP(mesh_indices.write[k + 0], mesh_indices.write[k + 2]);
+ }
+ }
+ primitive["indices"] = _encode_accessor_as_ints(state, mesh_indices, true);
+ } else {
+ if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
+ //generate indices because they need to be swapped for CW/CCW
+ const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
+ Ref<SurfaceTool> st;
+ st.instance();
+ st->create_from_triangle_arrays(array);
+ st->index();
+ Vector<int32_t> generated_indices = st->commit_to_arrays()[Mesh::ARRAY_INDEX];
+ const int vs = vertices.size();
+ generated_indices.resize(vs);
+ {
+ for (int k = 0; k < vs; k += 3) {
+ generated_indices.write[k] = k;
+ generated_indices.write[k + 1] = k + 2;
+ generated_indices.write[k + 2] = k + 1;
+ }
+ }
+ primitive["indices"] = _encode_accessor_as_ints(state, generated_indices, true);
+ }
+ }
+ }
+
+ primitive["attributes"] = attributes;
+
+ //blend shapes
+ print_verbose("glTF: Mesh has targets");
+ if (import_mesh->get_blend_shape_count()) {
+ ArrayMesh::BlendShapeMode shape_mode = import_mesh->get_blend_shape_mode();
+ for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
+ Array array_morph = import_mesh->get_surface_blend_shape_arrays(surface_i, morph_i);
+ target_names.push_back(import_mesh->get_blend_shape_name(morph_i));
+ Dictionary t;
+ Vector<Vector3> varr = array_morph[Mesh::ARRAY_VERTEX];
+ Array mesh_arrays = import_mesh->get_surface_arrays(surface_i);
+ if (varr.size()) {
+ Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
+ if (shape_mode == ArrayMesh::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED) {
+ const int max_idx = src_varr.size();
+ for (int blend_i = 0; blend_i < max_idx; blend_i++) {
+ varr.write[blend_i] = Vector3(varr[blend_i]) - src_varr[blend_i];
+ }
+ }
+
+ t["POSITION"] = _encode_accessor_as_vec3(state, varr, true);
+ }
+
+ Vector<Vector3> narr = array_morph[Mesh::ARRAY_NORMAL];
+ if (varr.size()) {
+ t["NORMAL"] = _encode_accessor_as_vec3(state, narr, true);
+ }
+ Vector<real_t> tarr = array_morph[Mesh::ARRAY_TANGENT];
+ if (tarr.size()) {
+ const int ret_size = tarr.size() / 4;
+ Vector<Color> attribs;
+ attribs.resize(ret_size);
+ for (int i = 0; i < ret_size; i++) {
+ Color tangent;
+ tangent.r = tarr[(i * 4) + 0];
+ tangent.r = tarr[(i * 4) + 1];
+ tangent.r = tarr[(i * 4) + 2];
+ tangent.r = tarr[(i * 4) + 3];
+ }
+ t["TANGENT"] = _encode_accessor_as_color(state, attribs, true);
+ }
+ targets.push_back(t);
+ }
+ }
+
+ Ref<BaseMaterial3D> mat = import_mesh->get_surface_material(surface_i);
+ if (mat.is_valid()) {
+ Map<Ref<BaseMaterial3D>, GLTFMaterialIndex>::Element *material_cache_i = state->material_cache.find(mat);
+ if (material_cache_i && material_cache_i->get() != -1) {
+ primitive["material"] = material_cache_i->get();
+ } else {
+ GLTFMaterialIndex mat_i = state->materials.size();
+ state->materials.push_back(mat);
+ primitive["material"] = mat_i;
+ state->material_cache.insert(mat, mat_i);
+ }
+ }
+
+ if (targets.size()) {
+ primitive["targets"] = targets;
+ }
+
+ primitives.push_back(primitive);
+ }
+
+ Dictionary e;
+ e["targetNames"] = target_names;
+
+ for (int j = 0; j < target_names.size(); j++) {
+ real_t weight = 0;
+ if (j < state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) {
+ weight = state->meshes.write[gltf_mesh_i]->get_blend_weights()[j];
+ }
+ weights.push_back(weight);
+ }
+ if (weights.size()) {
+ gltf_mesh["weights"] = weights;
+ }
+
+ ERR_FAIL_COND_V(target_names.size() != weights.size(), FAILED);
+
+ gltf_mesh["extras"] = e;
+
+ gltf_mesh["primitives"] = primitives;
+
+ meshes.push_back(gltf_mesh);
+ }
+
+ state->json["meshes"] = meshes;
+ print_verbose("glTF: Total meshes: " + itos(meshes.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) {
+ if (!state->json.has("meshes")) {
+ return OK;
+ }
+
+ Array meshes = state->json["meshes"];
+ for (GLTFMeshIndex i = 0; i < meshes.size(); i++) {
+ print_verbose("glTF: Parsing mesh: " + itos(i));
+ Dictionary d = meshes[i];
+
+ Ref<GLTFMesh> mesh;
+ mesh.instance();
+ bool has_vertex_color = false;
+
+ ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
+
+ Array primitives = d["primitives"];
+ const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
+ Ref<EditorSceneImporterMesh> import_mesh;
+ import_mesh.instance();
+ for (int j = 0; j < primitives.size(); j++) {
+ Dictionary p = primitives[j];
+
+ Array array;
+ array.resize(Mesh::ARRAY_MAX);
+
+ ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR);
+
+ Dictionary a = p["attributes"];
+
+ Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
+ if (p.has("mode")) {
+ const int mode = p["mode"];
+ ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
+ static const Mesh::PrimitiveType primitives2[7] = {
+ Mesh::PRIMITIVE_POINTS,
+ Mesh::PRIMITIVE_LINES,
+ Mesh::PRIMITIVE_LINES, //loop not supported, should ce converted
+ Mesh::PRIMITIVE_LINES,
+ Mesh::PRIMITIVE_TRIANGLES,
+ Mesh::PRIMITIVE_TRIANGLE_STRIP,
+ Mesh::PRIMITIVE_TRIANGLES, //fan not supported, should be converted
+#ifndef _MSC_VER
+#warning line loop and triangle fan are not supported and need to be converted to lines and triangles
+#endif
+
+ };
+
+ primitive = primitives2[mode];
+ }
+
+ ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
+ if (a.has("POSITION")) {
+ array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true);
+ }
+ if (a.has("NORMAL")) {
+ array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true);
+ }
+ if (a.has("TANGENT")) {
+ array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(state, a["TANGENT"], true);
+ }
+ if (a.has("TEXCOORD_0")) {
+ array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(state, a["TEXCOORD_0"], true);
+ }
+ if (a.has("TEXCOORD_1")) {
+ array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true);
+ }
+ if (a.has("COLOR_0")) {
+ array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true);
+ has_vertex_color = true;
+ }
+ if (a.has("JOINTS_0") && !a.has("JOINTS_1")) {
+ array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(state, a["JOINTS_0"], true);
+ } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
+ PackedInt32Array joints_0 = _decode_accessor_as_ints(state, a["JOINTS_0"], true);
+ PackedInt32Array joints_1 = _decode_accessor_as_ints(state, a["JOINTS_1"], true);
+ ERR_FAIL_COND_V(joints_0.size() != joints_0.size(), ERR_INVALID_DATA);
+ int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
+ int32_t vertex_count = joints_0.size() / JOINT_GROUP_SIZE;
+ Vector<int> joints;
+ joints.resize(vertex_count * weight_8_count);
+ for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ joints.write[vertex_i * weight_8_count + 0] = joints_0[vertex_i * JOINT_GROUP_SIZE + 0];
+ joints.write[vertex_i * weight_8_count + 1] = joints_0[vertex_i * JOINT_GROUP_SIZE + 1];
+ joints.write[vertex_i * weight_8_count + 2] = joints_0[vertex_i * JOINT_GROUP_SIZE + 2];
+ joints.write[vertex_i * weight_8_count + 3] = joints_0[vertex_i * JOINT_GROUP_SIZE + 3];
+ joints.write[vertex_i * weight_8_count + 4] = joints_1[vertex_i * JOINT_GROUP_SIZE + 0];
+ joints.write[vertex_i * weight_8_count + 5] = joints_1[vertex_i * JOINT_GROUP_SIZE + 1];
+ joints.write[vertex_i * weight_8_count + 6] = joints_1[vertex_i * JOINT_GROUP_SIZE + 2];
+ joints.write[vertex_i * weight_8_count + 7] = joints_1[vertex_i * JOINT_GROUP_SIZE + 3];
+ }
+ array[Mesh::ARRAY_BONES] = joints;
+ }
+ if (a.has("WEIGHTS_0") && !a.has("WEIGHTS_1")) {
+ Vector<float> weights = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true);
+ { //gltf does not seem to normalize the weights for some reason..
+ int wc = weights.size();
+ float *w = weights.ptrw();
+
+ for (int k = 0; k < wc; k += 4) {
+ float total = 0.0;
+ total += w[k + 0];
+ total += w[k + 1];
+ total += w[k + 2];
+ total += w[k + 3];
+ if (total > 0.0) {
+ w[k + 0] /= total;
+ w[k + 1] /= total;
+ w[k + 2] /= total;
+ w[k + 3] /= total;
+ }
+ }
+ }
+ array[Mesh::ARRAY_WEIGHTS] = weights;
+ } else if (a.has("WEIGHTS_0") && a.has("WEIGHTS_1")) {
+ Vector<float> weights_0 = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true);
+ Vector<float> weights_1 = _decode_accessor_as_floats(state, a["WEIGHTS_1"], true);
+ Vector<float> weights;
+ ERR_FAIL_COND_V(weights_0.size() != weights_1.size(), ERR_INVALID_DATA);
+ int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
+ int32_t vertex_count = weights_0.size() / JOINT_GROUP_SIZE;
+ weights.resize(vertex_count * weight_8_count);
+ for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
+ weights.write[vertex_i * weight_8_count + 0] = weights_0[vertex_i * JOINT_GROUP_SIZE + 0];
+ weights.write[vertex_i * weight_8_count + 1] = weights_0[vertex_i * JOINT_GROUP_SIZE + 1];
+ weights.write[vertex_i * weight_8_count + 2] = weights_0[vertex_i * JOINT_GROUP_SIZE + 2];
+ weights.write[vertex_i * weight_8_count + 3] = weights_0[vertex_i * JOINT_GROUP_SIZE + 3];
+ weights.write[vertex_i * weight_8_count + 4] = weights_1[vertex_i * JOINT_GROUP_SIZE + 0];
+ weights.write[vertex_i * weight_8_count + 5] = weights_1[vertex_i * JOINT_GROUP_SIZE + 1];
+ weights.write[vertex_i * weight_8_count + 6] = weights_1[vertex_i * JOINT_GROUP_SIZE + 2];
+ weights.write[vertex_i * weight_8_count + 7] = weights_1[vertex_i * JOINT_GROUP_SIZE + 3];
+ }
+ { //gltf does not seem to normalize the weights for some reason..
+ int wc = weights.size();
+ float *w = weights.ptrw();
+
+ for (int k = 0; k < wc; k += weight_8_count) {
+ float total = 0.0;
+ total += w[k + 0];
+ total += w[k + 1];
+ total += w[k + 2];
+ total += w[k + 3];
+ total += w[k + 4];
+ total += w[k + 5];
+ total += w[k + 6];
+ total += w[k + 7];
+ if (total > 0.0) {
+ w[k + 0] /= total;
+ w[k + 1] /= total;
+ w[k + 2] /= total;
+ w[k + 3] /= total;
+ w[k + 4] /= total;
+ w[k + 5] /= total;
+ w[k + 6] /= total;
+ w[k + 7] /= total;
+ }
+ }
+ }
+ array[Mesh::ARRAY_WEIGHTS] = weights;
+ }
+
+ if (p.has("indices")) {
+ Vector<int> indices = _decode_accessor_as_ints(state, p["indices"], false);
+
+ if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
+ //swap around indices, convert ccw to cw for front face
+
+ const int is = indices.size();
+ int *w = indices.ptrw();
+ for (int k = 0; k < is; k += 3) {
+ SWAP(w[k + 1], w[k + 2]);
+ }
+ }
+ array[Mesh::ARRAY_INDEX] = indices;
+
+ } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
+ //generate indices because they need to be swapped for CW/CCW
+ const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
+ ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR);
+ Vector<int> indices;
+ const int vs = vertices.size();
+ indices.resize(vs);
+ {
+ int *w = indices.ptrw();
+ for (int k = 0; k < vs; k += 3) {
+ w[k] = k;
+ w[k + 1] = k + 2;
+ w[k + 2] = k + 1;
+ }
+ }
+ array[Mesh::ARRAY_INDEX] = indices;
+ }
+
+ bool generate_tangents = (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL"));
+
+ if (generate_tangents) {
+ //must generate mikktspace tangents.. ergh..
+ Ref<SurfaceTool> st;
+ st.instance();
+ if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
+ st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
+ }
+ st->create_from_triangle_arrays(array);
+ st->generate_tangents();
+ array = st->commit_to_arrays();
+ }
+
+ Array morphs;
+ //blend shapes
+ if (p.has("targets")) {
+ print_verbose("glTF: Mesh has targets");
+ const Array &targets = p["targets"];
+
+ //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
+ //but it could require a larger refactor?
+ import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
+
+ if (j == 0) {
+ const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
+ for (int k = 0; k < targets.size(); k++) {
+ const String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k);
+ import_mesh->add_blend_shape(name);
+ }
+ }
+
+ for (int k = 0; k < targets.size(); k++) {
+ const Dictionary &t = targets[k];
+
+ Array array_copy;
+ array_copy.resize(Mesh::ARRAY_MAX);
+
+ for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
+ array_copy[l] = array[l];
+ }
+
+ array_copy[Mesh::ARRAY_INDEX] = Variant();
+
+ if (t.has("POSITION")) {
+ Vector<Vector3> varr = _decode_accessor_as_vec3(state, t["POSITION"], true);
+ const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
+ const int size = src_varr.size();
+ ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
+ {
+ const int max_idx = varr.size();
+ varr.resize(size);
+
+ Vector3 *w_varr = varr.ptrw();
+ const Vector3 *r_varr = varr.ptr();
+ const Vector3 *r_src_varr = src_varr.ptr();
+ for (int l = 0; l < size; l++) {
+ if (l < max_idx) {
+ w_varr[l] = r_varr[l] + r_src_varr[l];
+ } else {
+ w_varr[l] = r_src_varr[l];
+ }
+ }
+ }
+ array_copy[Mesh::ARRAY_VERTEX] = varr;
+ }
+ if (t.has("NORMAL")) {
+ Vector<Vector3> narr = _decode_accessor_as_vec3(state, t["NORMAL"], true);
+ const Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
+ int size = src_narr.size();
+ ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
+ {
+ int max_idx = narr.size();
+ narr.resize(size);
+
+ Vector3 *w_narr = narr.ptrw();
+ const Vector3 *r_narr = narr.ptr();
+ const Vector3 *r_src_narr = src_narr.ptr();
+ for (int l = 0; l < size; l++) {
+ if (l < max_idx) {
+ w_narr[l] = r_narr[l] + r_src_narr[l];
+ } else {
+ w_narr[l] = r_src_narr[l];
+ }
+ }
+ }
+ array_copy[Mesh::ARRAY_NORMAL] = narr;
+ }
+ if (t.has("TANGENT")) {
+ const Vector<Vector3> tangents_v3 = _decode_accessor_as_vec3(state, t["TANGENT"], true);
+ const Vector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
+ ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR);
+
+ Vector<float> tangents_v4;
+
+ {
+ int max_idx = tangents_v3.size();
+
+ int size4 = src_tangents.size();
+ tangents_v4.resize(size4);
+ float *w4 = tangents_v4.ptrw();
+
+ const Vector3 *r3 = tangents_v3.ptr();
+ const float *r4 = src_tangents.ptr();
+
+ for (int l = 0; l < size4 / 4; l++) {
+ if (l < max_idx) {
+ w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
+ w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
+ w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
+ } else {
+ w4[l * 4 + 0] = r4[l * 4 + 0];
+ w4[l * 4 + 1] = r4[l * 4 + 1];
+ w4[l * 4 + 2] = r4[l * 4 + 2];
+ }
+ w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
+ }
+ }
+
+ array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
+ }
+
+ if (generate_tangents) {
+ Ref<SurfaceTool> st;
+ st.instance();
+ if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
+ st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
+ }
+ st->create_from_triangle_arrays(array_copy);
+ st->deindex();
+ st->generate_tangents();
+ array_copy = st->commit_to_arrays();
+ }
+
+ morphs.push_back(array_copy);
+ }
+ }
+
+ //just add it
+
+ Ref<BaseMaterial3D> mat;
+ if (p.has("material")) {
+ const int material = p["material"];
+ ERR_FAIL_INDEX_V(material, state->materials.size(), ERR_FILE_CORRUPT);
+ Ref<BaseMaterial3D> mat3d = state->materials[material];
+ if (has_vertex_color) {
+ mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ }
+ mat = mat3d;
+
+ } else if (has_vertex_color) {
+ Ref<StandardMaterial3D> mat3d;
+ mat3d.instance();
+ mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ mat = mat3d;
+ }
+
+ import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat);
+ }
+
+ Vector<float> blend_weights;
+ blend_weights.resize(import_mesh->get_blend_shape_count());
+ for (int32_t weight_i = 0; weight_i < blend_weights.size(); weight_i++) {
+ blend_weights.write[weight_i] = 0.0f;
+ }
+
+ if (d.has("weights")) {
+ const Array &weights = d["weights"];
+ for (int j = 0; j < weights.size(); j++) {
+ if (j >= blend_weights.size()) {
+ break;
+ }
+ blend_weights.write[j] = weights[j];
+ }
+ mesh->set_blend_weights(blend_weights);
+ }
+ mesh->set_mesh(import_mesh);
+
+ state->meshes.push_back(mesh);
+ }
+
+ print_verbose("glTF: Total meshes: " + itos(state->meshes.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path) {
+ Array images;
+ for (int i = 0; i < state->images.size(); i++) {
+ Dictionary d;
+
+ ERR_CONTINUE(state->images[i].is_null());
+
+ Ref<Image> image = state->images[i]->get_data();
+ ERR_CONTINUE(image.is_null());
+
+ if (p_path.to_lower().ends_with("glb")) {
+ GLTFBufferViewIndex bvi;
+
+ Ref<GLTFBufferView> bv;
+ bv.instance();
+
+ const GLTFBufferIndex bi = 0;
+ bv->buffer = bi;
+ bv->byte_offset = state->buffers[bi].size();
+ ERR_FAIL_INDEX_V(bi, state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
+
+ Vector<uint8_t> buffer;
+ Ref<ImageTexture> img_tex = image;
+ if (img_tex.is_valid()) {
+ image = img_tex->get_data();
+ }
+ Error err = PNGDriverCommon::image_to_png(image, buffer);
+ ERR_FAIL_COND_V_MSG(err, err, "Can't convert image to PNG.");
+
+ bv->byte_length = buffer.size();
+ state->buffers.write[bi].resize(state->buffers[bi].size() + bv->byte_length);
+ copymem(&state->buffers.write[bi].write[bv->byte_offset], buffer.ptr(), buffer.size());
+ ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > state->buffers[bi].size(), ERR_FILE_CORRUPT);
+
+ state->buffer_views.push_back(bv);
+ bvi = state->buffer_views.size() - 1;
+ d["bufferView"] = bvi;
+ d["mimeType"] = "image/png";
+ } else {
+ String name = state->images[i]->get_name();
+ if (name.is_empty()) {
+ name = itos(i);
+ }
+ name = _gen_unique_name(state, name);
+ name = name.pad_zeros(3);
+ Ref<_Directory> dir;
+ dir.instance();
+ String texture_dir = "textures";
+ String new_texture_dir = p_path.get_base_dir() + "/" + texture_dir;
+ dir->open(p_path.get_base_dir());
+ if (!dir->dir_exists(new_texture_dir)) {
+ dir->make_dir(new_texture_dir);
+ }
+ name = name + ".png";
+ image->save_png(new_texture_dir.plus_file(name));
+ d["uri"] = texture_dir.plus_file(name);
+ }
+ images.push_back(d);
+ }
+
+ print_verbose("Total images: " + itos(state->images.size()));
+
+ if (!images.size()) {
+ return OK;
+ }
+ state->json["images"] = images;
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_images(Ref<GLTFState> state, const String &p_base_path) {
+ if (!state->json.has("images")) {
+ return OK;
+ }
+
+ // Ref: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#images
+
+ const Array &images = state->json["images"];
+ for (int i = 0; i < images.size(); i++) {
+ const Dictionary &d = images[i];
+
+ // glTF 2.0 supports PNG and JPEG types, which can be specified as (from spec):
+ // "- a URI to an external file in one of the supported images formats, or
+ // - a URI with embedded base64-encoded data, or
+ // - a reference to a bufferView; in that case mimeType must be defined."
+ // Since mimeType is optional for external files and base64 data, we'll have to
+ // fall back on letting Godot parse the data to figure out if it's PNG or JPEG.
+
+ // We'll assume that we use either URI or bufferView, so let's warn the user
+ // if their image somehow uses both. And fail if it has neither.
+ ERR_CONTINUE_MSG(!d.has("uri") && !d.has("bufferView"), "Invalid image definition in glTF file, it should specific an 'uri' or 'bufferView'.");
+ if (d.has("uri") && d.has("bufferView")) {
+ WARN_PRINT("Invalid image definition in glTF file using both 'uri' and 'bufferView'. 'bufferView' will take precedence.");
+ }
+
+ String mimetype;
+ if (d.has("mimeType")) { // Should be "image/png" or "image/jpeg".
+ mimetype = d["mimeType"];
+ }
+
+ Vector<uint8_t> data;
+ const uint8_t *data_ptr = nullptr;
+ int data_size = 0;
+
+ if (d.has("uri")) {
+ // Handles the first two bullet points from the spec (embedded data, or external file).
+ String uri = d["uri"];
+
+ if (uri.begins_with("data:")) { // Embedded data using base64.
+ // Validate data MIME types and throw a warning if it's one we don't know/support.
+ if (!uri.begins_with("data:application/octet-stream;base64") &&
+ !uri.begins_with("data:application/gltf-buffer;base64") &&
+ !uri.begins_with("data:image/png;base64") &&
+ !uri.begins_with("data:image/jpeg;base64")) {
+ WARN_PRINT(vformat("glTF: Image index '%d' uses an unsupported URI data type: %s. Skipping it.", i, uri));
+ state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
+ continue;
+ }
+ data = _parse_base64_uri(uri);
+ data_ptr = data.ptr();
+ data_size = data.size();
+ // mimeType is optional, but if we have it defined in the URI, let's use it.
+ if (mimetype.is_empty()) {
+ if (uri.begins_with("data:image/png;base64")) {
+ mimetype = "image/png";
+ } else if (uri.begins_with("data:image/jpeg;base64")) {
+ mimetype = "image/jpeg";
+ }
+ }
+ } else { // Relative path to an external image file.
+ uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows.
+ // ResourceLoader will rely on the file extension to use the relevant loader.
+ // The spec says that if mimeType is defined, it should take precedence (e.g.
+ // there could be a `.png` image which is actually JPEG), but there's no easy
+ // API for that in Godot, so we'd have to load as a buffer (i.e. embedded in
+ // the material), so we do this only as fallback.
+ Ref<Texture2D> texture = ResourceLoader::load(uri);
+ if (texture.is_valid()) {
+ state->images.push_back(texture);
+ continue;
+ } else if (mimetype == "image/png" || mimetype == "image/jpeg") {
+ // Fallback to loading as byte array.
+ // This enables us to support the spec's requirement that we honor mimetype
+ // regardless of file URI.
+ data = FileAccess::get_file_as_array(uri);
+ if (data.size() == 0) {
+ WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded as a buffer of MIME type '%s' from URI: %s. Skipping it.", i, mimetype, uri));
+ state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
+ continue;
+ }
+ data_ptr = data.ptr();
+ data_size = data.size();
+ } else {
+ WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded from URI: %s. Skipping it.", i, uri));
+ state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
+ continue;
+ }
+ }
+ } else if (d.has("bufferView")) {
+ // Handles the third bullet point from the spec (bufferView).
+ ERR_FAIL_COND_V_MSG(mimetype.is_empty(), ERR_FILE_CORRUPT,
+ vformat("glTF: Image index '%d' specifies 'bufferView' but no 'mimeType', which is invalid.", i));
+
+ const GLTFBufferViewIndex bvi = d["bufferView"];
+
+ ERR_FAIL_INDEX_V(bvi, state->buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
+
+ Ref<GLTFBufferView> bv = state->buffer_views[bvi];
+
+ const GLTFBufferIndex bi = bv->buffer;
+ ERR_FAIL_INDEX_V(bi, state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
+
+ ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > state->buffers[bi].size(), ERR_FILE_CORRUPT);
+
+ data_ptr = &state->buffers[bi][bv->byte_offset];
+ data_size = bv->byte_length;
+ }
+
+ Ref<Image> img;
+
+ if (mimetype == "image/png") { // Load buffer as PNG.
+ ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE);
+ img = Image::_png_mem_loader_func(data_ptr, data_size);
+ } else if (mimetype == "image/jpeg") { // Loader buffer as JPEG.
+ ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE);
+ img = Image::_jpg_mem_loader_func(data_ptr, data_size);
+ } else {
+ // We can land here if we got an URI with base64-encoded data with application/* MIME type,
+ // and the optional mimeType property was not defined to tell us how to handle this data (or was invalid).
+ // So let's try PNG first, then JPEG.
+ ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE);
+ img = Image::_png_mem_loader_func(data_ptr, data_size);
+ if (img.is_null()) {
+ ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE);
+ img = Image::_jpg_mem_loader_func(data_ptr, data_size);
+ }
+ }
+
+ ERR_FAIL_COND_V_MSG(img.is_null(), ERR_FILE_CORRUPT,
+ vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", i, mimetype));
+
+ Ref<ImageTexture> t;
+ t.instance();
+ t->create_from_image(img);
+
+ state->images.push_back(t);
+ }
+
+ print_verbose("glTF: Total images: " + itos(state->images.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_textures(Ref<GLTFState> state) {
+ if (!state->textures.size()) {
+ return OK;
+ }
+
+ Array textures;
+ for (int32_t i = 0; i < state->textures.size(); i++) {
+ Dictionary d;
+ Ref<GLTFTexture> t = state->textures[i];
+ ERR_CONTINUE(t->get_src_image() == -1);
+ d["source"] = t->get_src_image();
+ textures.push_back(d);
+ }
+ state->json["textures"] = textures;
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_textures(Ref<GLTFState> state) {
+ if (!state->json.has("textures"))
+ return OK;
+
+ const Array &textures = state->json["textures"];
+ for (GLTFTextureIndex i = 0; i < textures.size(); i++) {
+ const Dictionary &d = textures[i];
+
+ ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR);
+
+ Ref<GLTFTexture> t;
+ t.instance();
+ t->set_src_image(d["source"]);
+ state->textures.push_back(t);
+ }
+
+ return OK;
+}
+
+GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture) {
+ ERR_FAIL_COND_V(p_texture.is_null(), -1);
+ Ref<GLTFTexture> gltf_texture;
+ gltf_texture.instance();
+ ERR_FAIL_COND_V(p_texture->get_data().is_null(), -1);
+ GLTFImageIndex gltf_src_image_i = state->images.size();
+ state->images.push_back(p_texture);
+ gltf_texture->set_src_image(gltf_src_image_i);
+ GLTFTextureIndex gltf_texture_i = state->textures.size();
+ state->textures.push_back(gltf_texture);
+ return gltf_texture_i;
+}
+
+Ref<Texture2D> GLTFDocument::_get_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture) {
+ ERR_FAIL_INDEX_V(p_texture, state->textures.size(), Ref<Texture2D>());
+ const GLTFImageIndex image = state->textures[p_texture]->get_src_image();
+
+ ERR_FAIL_INDEX_V(image, state->images.size(), Ref<Texture2D>());
+
+ return state->images[image];
+}
+
+Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) {
+ Array materials;
+ for (int32_t i = 0; i < state->materials.size(); i++) {
+ Dictionary d;
+
+ Ref<BaseMaterial3D> material = state->materials[i];
+ if (material.is_null()) {
+ materials.push_back(d);
+ continue;
+ }
+ if (!material->get_name().is_empty()) {
+ d["name"] = _gen_unique_name(state, material->get_name());
+ }
+ {
+ Dictionary mr;
+ {
+ Array arr;
+ const Color c = material->get_albedo().to_linear();
+ arr.push_back(c.r);
+ arr.push_back(c.g);
+ arr.push_back(c.b);
+ arr.push_back(c.a);
+ mr["baseColorFactor"] = arr;
+ }
+ {
+ Dictionary bct;
+ Ref<Texture2D> albedo_texture = material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
+ GLTFTextureIndex gltf_texture_index = -1;
+
+ if (albedo_texture.is_valid() && albedo_texture->get_data().is_valid()) {
+ albedo_texture->set_name(material->get_name() + "_albedo");
+ gltf_texture_index = _set_texture(state, albedo_texture);
+ }
+ if (gltf_texture_index != -1) {
+ bct["index"] = gltf_texture_index;
+ bct["extensions"] = _serialize_texture_transform_uv1(material);
+ mr["baseColorTexture"] = bct;
+ }
+ }
+
+ mr["metallicFactor"] = material->get_metallic();
+ mr["roughnessFactor"] = material->get_roughness();
+ bool has_roughness = material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS).is_valid() && material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS)->get_data().is_valid();
+ bool has_ao = material->get_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION) && material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION).is_valid();
+ bool has_metalness = material->get_texture(BaseMaterial3D::TEXTURE_METALLIC).is_valid() && material->get_texture(BaseMaterial3D::TEXTURE_METALLIC)->get_data().is_valid();
+ if (has_ao || has_roughness || has_metalness) {
+ Dictionary mrt;
+ Ref<Texture2D> roughness_texture = material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS);
+ BaseMaterial3D::TextureChannel roughness_channel = material->get_roughness_texture_channel();
+ Ref<Texture2D> metallic_texture = material->get_texture(BaseMaterial3D::TEXTURE_METALLIC);
+ BaseMaterial3D::TextureChannel metalness_channel = material->get_metallic_texture_channel();
+ Ref<Texture2D> ao_texture = material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION);
+ BaseMaterial3D::TextureChannel ao_channel = material->get_ao_texture_channel();
+ Ref<ImageTexture> orm_texture;
+ orm_texture.instance();
+ Ref<Image> orm_image;
+ orm_image.instance();
+ int32_t height = 0;
+ int32_t width = 0;
+ Ref<Image> ao_image;
+ if (has_ao) {
+ height = ao_texture->get_height();
+ width = ao_texture->get_width();
+ ao_image = ao_texture->get_data();
+ Ref<ImageTexture> img_tex = ao_image;
+ if (img_tex.is_valid()) {
+ ao_image = img_tex->get_data();
+ }
+ if (ao_image->is_compressed()) {
+ ao_image->decompress();
+ }
+ }
+ Ref<Image> roughness_image;
+ if (has_roughness) {
+ height = roughness_texture->get_height();
+ width = roughness_texture->get_width();
+ roughness_image = roughness_texture->get_data();
+ Ref<ImageTexture> img_tex = roughness_image;
+ if (img_tex.is_valid()) {
+ roughness_image = img_tex->get_data();
+ }
+ if (roughness_image->is_compressed()) {
+ roughness_image->decompress();
+ }
+ }
+ Ref<Image> metallness_image;
+ if (has_metalness) {
+ height = metallic_texture->get_height();
+ width = metallic_texture->get_width();
+ metallness_image = metallic_texture->get_data();
+ Ref<ImageTexture> img_tex = metallness_image;
+ if (img_tex.is_valid()) {
+ metallness_image = img_tex->get_data();
+ }
+ if (metallness_image->is_compressed()) {
+ metallness_image->decompress();
+ }
+ }
+ Ref<Texture2D> albedo_texture = material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
+ if (albedo_texture.is_valid() && albedo_texture->get_data().is_valid()) {
+ height = albedo_texture->get_height();
+ width = albedo_texture->get_width();
+ }
+ orm_image->create(width, height, false, Image::FORMAT_RGBA8);
+ if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) {
+ ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
+ }
+ if (roughness_image.is_valid() && roughness_image->get_size() != Vector2(width, height)) {
+ roughness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
+ }
+ if (metallness_image.is_valid() && metallness_image->get_size() != Vector2(width, height)) {
+ metallness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
+ }
+ for (int32_t h = 0; h < height; h++) {
+ for (int32_t w = 0; w < width; w++) {
+ Color c = Color(1.0f, 1.0f, 1.0f);
+ if (has_ao) {
+ if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == ao_channel) {
+ c.r = ao_image->get_pixel(w, h).r;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == ao_channel) {
+ c.r = ao_image->get_pixel(w, h).g;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == ao_channel) {
+ c.r = ao_image->get_pixel(w, h).b;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == ao_channel) {
+ c.r = ao_image->get_pixel(w, h).a;
+ }
+ }
+ if (has_roughness) {
+ if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == roughness_channel) {
+ c.g = roughness_image->get_pixel(w, h).r;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == roughness_channel) {
+ c.g = roughness_image->get_pixel(w, h).g;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == roughness_channel) {
+ c.g = roughness_image->get_pixel(w, h).b;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == roughness_channel) {
+ c.g = roughness_image->get_pixel(w, h).a;
+ }
+ }
+ if (has_metalness) {
+ if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == metalness_channel) {
+ c.b = metallness_image->get_pixel(w, h).r;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == metalness_channel) {
+ c.b = metallness_image->get_pixel(w, h).g;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == metalness_channel) {
+ c.b = metallness_image->get_pixel(w, h).b;
+ } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == metalness_channel) {
+ c.b = metallness_image->get_pixel(w, h).a;
+ }
+ }
+ orm_image->set_pixel(w, h, c);
+ }
+ }
+ orm_image->generate_mipmaps();
+ orm_texture->create_from_image(orm_image);
+ GLTFTextureIndex orm_texture_index = -1;
+ if (has_ao || has_roughness || has_metalness) {
+ orm_texture->set_name(material->get_name() + "_orm");
+ orm_texture_index = _set_texture(state, orm_texture);
+ }
+ if (has_ao) {
+ Dictionary ot;
+ ot["index"] = orm_texture_index;
+ d["occlusionTexture"] = ot;
+ }
+ if (has_roughness || has_metalness) {
+ mrt["index"] = orm_texture_index;
+ mrt["extensions"] = _serialize_texture_transform_uv1(material);
+ mr["metallicRoughnessTexture"] = mrt;
+ }
+ }
+ d["pbrMetallicRoughness"] = mr;
+ }
+
+ if (material->get_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING)) {
+ Dictionary nt;
+ Ref<ImageTexture> tex;
+ tex.instance();
+ {
+ Ref<Texture2D> normal_texture = material->get_texture(BaseMaterial3D::TEXTURE_NORMAL);
+ // Code for uncompressing RG normal maps
+ Ref<Image> img = normal_texture->get_data();
+ Ref<ImageTexture> img_tex = img;
+ if (img_tex.is_valid()) {
+ img = img_tex->get_data();
+ }
+ img->decompress();
+ img->convert(Image::FORMAT_RGBA8);
+ for (int32_t y = 0; y < img->get_height(); y++) {
+ for (int32_t x = 0; x < img->get_width(); x++) {
+ Color c = img->get_pixel(x, y);
+ Vector2 red_green = Vector2(c.r, c.g);
+ red_green = red_green * Vector2(2.0f, 2.0f) - Vector2(1.0f, 1.0f);
+ float blue = 1.0f - red_green.dot(red_green);
+ blue = MAX(0.0f, blue);
+ c.b = Math::sqrt(blue);
+ img->set_pixel(x, y, c);
+ }
+ }
+ tex->create_from_image(img);
+ }
+ Ref<Texture2D> normal_texture = material->get_texture(BaseMaterial3D::TEXTURE_NORMAL);
+ GLTFTextureIndex gltf_texture_index = -1;
+ if (tex.is_valid() && tex->get_data().is_valid()) {
+ tex->set_name(material->get_name() + "_normal");
+ gltf_texture_index = _set_texture(state, tex);
+ }
+ nt["scale"] = material->get_normal_scale();
+ if (gltf_texture_index != -1) {
+ nt["index"] = gltf_texture_index;
+ d["normalTexture"] = nt;
+ }
+ }
+
+ if (material->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
+ const Color c = material->get_emission().to_srgb();
+ Array arr;
+ arr.push_back(c.r);
+ arr.push_back(c.g);
+ arr.push_back(c.b);
+ d["emissiveFactor"] = arr;
+ }
+ if (material->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
+ Dictionary et;
+ Ref<Texture2D> emission_texture = material->get_texture(BaseMaterial3D::TEXTURE_EMISSION);
+ GLTFTextureIndex gltf_texture_index = -1;
+ if (emission_texture.is_valid() && emission_texture->get_data().is_valid()) {
+ emission_texture->set_name(material->get_name() + "_emission");
+ gltf_texture_index = _set_texture(state, emission_texture);
+ }
+
+ if (gltf_texture_index != -1) {
+ et["index"] = gltf_texture_index;
+ d["emissiveTexture"] = et;
+ }
+ }
+ const bool ds = material->get_cull_mode() == BaseMaterial3D::CULL_DISABLED;
+ if (ds) {
+ d["doubleSided"] = ds;
+ }
+ if (material->get_transparency() == BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR) {
+ d["alphaMode"] = "MASK";
+ d["alphaCutoff"] = material->get_alpha_scissor_threshold();
+ } else if (material->get_transparency() != BaseMaterial3D::TRANSPARENCY_DISABLED) {
+ d["alphaMode"] = "BLEND";
+ }
+ materials.push_back(d);
+ }
+ state->json["materials"] = materials;
+ print_verbose("Total materials: " + itos(state->materials.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_materials(Ref<GLTFState> state) {
+ if (!state->json.has("materials"))
+ return OK;
+
+ const Array &materials = state->json["materials"];
+ for (GLTFMaterialIndex i = 0; i < materials.size(); i++) {
+ const Dictionary &d = materials[i];
+
+ Ref<StandardMaterial3D> material;
+ material.instance();
+ if (d.has("name")) {
+ material->set_name(d["name"]);
+ }
+ material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ Dictionary pbr_spec_gloss_extensions;
+ if (d.has("extensions")) {
+ pbr_spec_gloss_extensions = d["extensions"];
+ }
+ if (pbr_spec_gloss_extensions.has("KHR_materials_pbrSpecularGlossiness")) {
+ WARN_PRINT("Material uses a specular and glossiness workflow. Textures will be converted to roughness and metallic workflow, which may not be 100% accurate.");
+ Dictionary sgm = pbr_spec_gloss_extensions["KHR_materials_pbrSpecularGlossiness"];
+
+ Ref<GLTFSpecGloss> spec_gloss;
+ spec_gloss.instance();
+ if (sgm.has("diffuseTexture")) {
+ const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"];
+ if (diffuse_texture_dict.has("index")) {
+ Ref<Texture2D> diffuse_texture = _get_texture(state, diffuse_texture_dict["index"]);
+ if (diffuse_texture.is_valid()) {
+ spec_gloss->diffuse_img = diffuse_texture->get_data();
+ material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, diffuse_texture);
+ }
+ }
+ }
+ if (sgm.has("diffuseFactor")) {
+ const Array &arr = sgm["diffuseFactor"];
+ ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
+ const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
+ spec_gloss->diffuse_factor = c;
+ material->set_albedo(spec_gloss->diffuse_factor);
+ }
+
+ if (sgm.has("specularFactor")) {
+ const Array &arr = sgm["specularFactor"];
+ ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
+ spec_gloss->specular_factor = Color(arr[0], arr[1], arr[2]);
+ }
+
+ if (sgm.has("glossinessFactor")) {
+ spec_gloss->gloss_factor = sgm["glossinessFactor"];
+ material->set_roughness(1.0f - CLAMP(spec_gloss->gloss_factor, 0.0f, 1.0f));
+ }
+ if (sgm.has("specularGlossinessTexture")) {
+ const Dictionary &spec_gloss_texture = sgm["specularGlossinessTexture"];
+ if (spec_gloss_texture.has("index")) {
+ const Ref<Texture2D> orig_texture = _get_texture(state, spec_gloss_texture["index"]);
+ if (orig_texture.is_valid()) {
+ spec_gloss->spec_gloss_img = orig_texture->get_data();
+ }
+ }
+ }
+ spec_gloss_to_rough_metal(spec_gloss, material);
+
+ } else if (d.has("pbrMetallicRoughness")) {
+ const Dictionary &mr = d["pbrMetallicRoughness"];
+ if (mr.has("baseColorFactor")) {
+ const Array &arr = mr["baseColorFactor"];
+ ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
+ const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
+ material->set_albedo(c);
+ }
+
+ if (mr.has("baseColorTexture")) {
+ const Dictionary &bct = mr["baseColorTexture"];
+ if (bct.has("index")) {
+ material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, _get_texture(state, bct["index"]));
+ }
+ if (!mr.has("baseColorFactor")) {
+ material->set_albedo(Color(1, 1, 1));
+ }
+ _set_texture_transform_uv1(bct, material);
+ }
+
+ if (mr.has("metallicFactor")) {
+ material->set_metallic(mr["metallicFactor"]);
+ } else {
+ material->set_metallic(1.0);
+ }
+
+ if (mr.has("roughnessFactor")) {
+ material->set_roughness(mr["roughnessFactor"]);
+ } else {
+ material->set_roughness(1.0);
+ }
+
+ if (mr.has("metallicRoughnessTexture")) {
+ const Dictionary &bct = mr["metallicRoughnessTexture"];
+ if (bct.has("index")) {
+ const Ref<Texture2D> t = _get_texture(state, bct["index"]);
+ material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, t);
+ material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
+ material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, t);
+ material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
+ if (!mr.has("metallicFactor")) {
+ material->set_metallic(1);
+ }
+ if (!mr.has("roughnessFactor")) {
+ material->set_roughness(1);
+ }
+ }
+ }
+ }
+
+ if (d.has("normalTexture")) {
+ const Dictionary &bct = d["normalTexture"];
+ if (bct.has("index")) {
+ material->set_texture(BaseMaterial3D::TEXTURE_NORMAL, _get_texture(state, bct["index"]));
+ material->set_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING, true);
+ }
+ if (bct.has("scale")) {
+ material->set_normal_scale(bct["scale"]);
+ }
+ }
+ if (d.has("occlusionTexture")) {
+ const Dictionary &bct = d["occlusionTexture"];
+ if (bct.has("index")) {
+ material->set_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION, _get_texture(state, bct["index"]));
+ material->set_ao_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
+ material->set_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
+ }
+ }
+
+ if (d.has("emissiveFactor")) {
+ const Array &arr = d["emissiveFactor"];
+ ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
+ const Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
+ material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
+
+ material->set_emission(c);
+ }
+
+ if (d.has("emissiveTexture")) {
+ const Dictionary &bct = d["emissiveTexture"];
+ if (bct.has("index")) {
+ material->set_texture(BaseMaterial3D::TEXTURE_EMISSION, _get_texture(state, bct["index"]));
+ material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
+ material->set_emission(Color(0, 0, 0));
+ }
+ }
+
+ if (d.has("doubleSided")) {
+ const bool ds = d["doubleSided"];
+ if (ds) {
+ material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
+ }
+ }
+
+ if (d.has("alphaMode")) {
+ const String &am = d["alphaMode"];
+ if (am == "BLEND") {
+ material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
+ } else if (am == "MASK") {
+ material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR);
+ if (d.has("alphaCutoff")) {
+ material->set_alpha_scissor_threshold(d["alphaCutoff"]);
+ } else {
+ material->set_alpha_scissor_threshold(0.5f);
+ }
+ }
+ }
+ state->materials.push_back(material);
+ }
+
+ print_verbose("Total materials: " + itos(state->materials.size()));
+
+ return OK;
+}
+
+void GLTFDocument::_set_texture_transform_uv1(const Dictionary &d, Ref<BaseMaterial3D> material) {
+ if (d.has("extensions")) {
+ const Dictionary &extensions = d["extensions"];
+ if (extensions.has("KHR_texture_transform")) {
+ const Dictionary &texture_transform = extensions["KHR_texture_transform"];
+ const Array &offset_arr = texture_transform["offset"];
+ if (offset_arr.size() == 2) {
+ const Vector3 offset_vector3 = Vector3(offset_arr[0], offset_arr[1], 0.0f);
+ material->set_uv1_offset(offset_vector3);
+ }
+
+ const Array &scale_arr = texture_transform["scale"];
+ if (scale_arr.size() == 2) {
+ const Vector3 scale_vector3 = Vector3(scale_arr[0], scale_arr[1], 1.0f);
+ material->set_uv1_scale(scale_vector3);
+ }
+ }
+ }
+}
+
+void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Ref<BaseMaterial3D> p_material) {
+ if (r_spec_gloss->spec_gloss_img.is_null()) {
+ return;
+ }
+ if (r_spec_gloss->diffuse_img.is_null()) {
+ return;
+ }
+ Ref<Image> rm_img;
+ rm_img.instance();
+ bool has_roughness = false;
+ bool has_metal = false;
+ p_material->set_roughness(1.0f);
+ p_material->set_metallic(1.0f);
+ rm_img->create(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
+ r_spec_gloss->spec_gloss_img->decompress();
+ if (r_spec_gloss->diffuse_img.is_valid()) {
+ r_spec_gloss->diffuse_img->decompress();
+ r_spec_gloss->diffuse_img->resize(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), Image::INTERPOLATE_LANCZOS);
+ r_spec_gloss->spec_gloss_img->resize(r_spec_gloss->diffuse_img->get_width(), r_spec_gloss->diffuse_img->get_height(), Image::INTERPOLATE_LANCZOS);
+ }
+ for (int32_t y = 0; y < r_spec_gloss->spec_gloss_img->get_height(); y++) {
+ for (int32_t x = 0; x < r_spec_gloss->spec_gloss_img->get_width(); x++) {
+ const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).to_linear();
+ Color specular = Color(specular_pixel.r, specular_pixel.g, specular_pixel.b);
+ specular *= r_spec_gloss->specular_factor;
+ Color diffuse = Color(1.0f, 1.0f, 1.0f);
+ diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).to_linear();
+ float metallic = 0.0f;
+ Color base_color;
+ spec_gloss_to_metal_base_color(specular, diffuse, base_color, metallic);
+ Color mr = Color(1.0f, 1.0f, 1.0f);
+ mr.g = specular_pixel.a;
+ mr.b = metallic;
+ if (!Math::is_equal_approx(mr.g, 1.0f)) {
+ has_roughness = true;
+ }
+ if (!Math::is_equal_approx(mr.b, 0.0f)) {
+ has_metal = true;
+ }
+ mr.g *= r_spec_gloss->gloss_factor;
+ mr.g = 1.0f - mr.g;
+ rm_img->set_pixel(x, y, mr);
+ if (r_spec_gloss->diffuse_img.is_valid()) {
+ r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.to_srgb());
+ }
+ }
+ }
+ rm_img->generate_mipmaps();
+ r_spec_gloss->diffuse_img->generate_mipmaps();
+ Ref<ImageTexture> diffuse_image_texture;
+ diffuse_image_texture.instance();
+ diffuse_image_texture->create_from_image(r_spec_gloss->diffuse_img);
+ p_material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, diffuse_image_texture);
+ Ref<ImageTexture> rm_image_texture;
+ rm_image_texture.instance();
+ rm_image_texture->create_from_image(rm_img);
+ if (has_roughness) {
+ p_material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, rm_image_texture);
+ p_material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
+ }
+
+ if (has_metal) {
+ p_material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, rm_image_texture);
+ p_material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
+ }
+}
+
+void GLTFDocument::spec_gloss_to_metal_base_color(const Color &p_specular_factor, const Color &p_diffuse, Color &r_base_color, float &r_metallic) {
+ const Color DIELECTRIC_SPECULAR = Color(0.04f, 0.04f, 0.04f);
+ Color specular = Color(p_specular_factor.r, p_specular_factor.g, p_specular_factor.b);
+ const float one_minus_specular_strength = 1.0f - get_max_component(specular);
+ const float dielectric_specular_red = DIELECTRIC_SPECULAR.r;
+ float brightness_diffuse = get_perceived_brightness(p_diffuse);
+ const float brightness_specular = get_perceived_brightness(specular);
+ r_metallic = solve_metallic(dielectric_specular_red, brightness_diffuse, brightness_specular, one_minus_specular_strength);
+ const float one_minus_metallic = 1.0f - r_metallic;
+ const Color base_color_from_diffuse = p_diffuse * (one_minus_specular_strength / (1.0f - dielectric_specular_red) / MAX(one_minus_metallic, CMP_EPSILON));
+ const Color base_color_from_specular = (specular - (DIELECTRIC_SPECULAR * (one_minus_metallic))) * (1.0f / MAX(r_metallic, CMP_EPSILON));
+ r_base_color.r = Math::lerp(base_color_from_diffuse.r, base_color_from_specular.r, r_metallic * r_metallic);
+ r_base_color.g = Math::lerp(base_color_from_diffuse.g, base_color_from_specular.g, r_metallic * r_metallic);
+ r_base_color.b = Math::lerp(base_color_from_diffuse.b, base_color_from_specular.b, r_metallic * r_metallic);
+ r_base_color.a = p_diffuse.a;
+ r_base_color.r = CLAMP(r_base_color.r, 0.0f, 1.0f);
+ r_base_color.g = CLAMP(r_base_color.g, 0.0f, 1.0f);
+ r_base_color.b = CLAMP(r_base_color.b, 0.0f, 1.0f);
+ r_base_color.a = CLAMP(r_base_color.a, 0.0f, 1.0f);
+}
+
+GLTFNodeIndex GLTFDocument::_find_highest_node(Ref<GLTFState> state, const Vector<GLTFNodeIndex> &subset) {
+ int highest = -1;
+ GLTFNodeIndex best_node = -1;
+
+ for (int i = 0; i < subset.size(); ++i) {
+ const GLTFNodeIndex node_i = subset[i];
+ const Ref<GLTFNode> node = state->nodes[node_i];
+
+ if (highest == -1 || node->height < highest) {
+ highest = node->height;
+ best_node = node_i;
+ }
+ }
+
+ return best_node;
+}
+
+bool GLTFDocument::_capture_nodes_in_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin, const GLTFNodeIndex node_index) {
+ bool found_joint = false;
+
+ for (int i = 0; i < state->nodes[node_index]->children.size(); ++i) {
+ found_joint |= _capture_nodes_in_skin(state, skin, state->nodes[node_index]->children[i]);
+ }
+
+ if (found_joint) {
+ // Mark it if we happen to find another skins joint...
+ if (state->nodes[node_index]->joint && skin->joints.find(node_index) < 0) {
+ skin->joints.push_back(node_index);
+ } else if (skin->non_joints.find(node_index) < 0) {
+ skin->non_joints.push_back(node_index);
+ }
+ }
+
+ if (skin->joints.find(node_index) > 0) {
+ return true;
+ }
+
+ return false;
+}
+
+void GLTFDocument::_capture_nodes_for_multirooted_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin) {
+ DisjointSet<GLTFNodeIndex> disjoint_set;
+
+ for (int i = 0; i < skin->joints.size(); ++i) {
+ const GLTFNodeIndex node_index = skin->joints[i];
+ const GLTFNodeIndex parent = state->nodes[node_index]->parent;
+ disjoint_set.insert(node_index);
+
+ if (skin->joints.find(parent) >= 0) {
+ disjoint_set.create_union(parent, node_index);
+ }
+ }
+
+ Vector<GLTFNodeIndex> roots;
+ disjoint_set.get_representatives(roots);
+
+ if (roots.size() <= 1) {
+ return;
+ }
+
+ int maxHeight = -1;
+
+ // Determine the max height rooted tree
+ for (int i = 0; i < roots.size(); ++i) {
+ const GLTFNodeIndex root = roots[i];
+
+ if (maxHeight == -1 || state->nodes[root]->height < maxHeight) {
+ maxHeight = state->nodes[root]->height;
+ }
+ }
+
+ // Go up the tree till all of the multiple roots of the skin are at the same hierarchy level.
+ // This sucks, but 99% of all game engines (not just Godot) would have this same issue.
+ for (int i = 0; i < roots.size(); ++i) {
+ GLTFNodeIndex current_node = roots[i];
+ while (state->nodes[current_node]->height > maxHeight) {
+ GLTFNodeIndex parent = state->nodes[current_node]->parent;
+
+ if (state->nodes[parent]->joint && skin->joints.find(parent) < 0) {
+ skin->joints.push_back(parent);
+ } else if (skin->non_joints.find(parent) < 0) {
+ skin->non_joints.push_back(parent);
+ }
+
+ current_node = parent;
+ }
+
+ // replace the roots
+ roots.write[i] = current_node;
+ }
+
+ // Climb up the tree until they all have the same parent
+ bool all_same;
+
+ do {
+ all_same = true;
+ const GLTFNodeIndex first_parent = state->nodes[roots[0]]->parent;
+
+ for (int i = 1; i < roots.size(); ++i) {
+ all_same &= (first_parent == state->nodes[roots[i]]->parent);
+ }
+
+ if (!all_same) {
+ for (int i = 0; i < roots.size(); ++i) {
+ const GLTFNodeIndex current_node = roots[i];
+ const GLTFNodeIndex parent = state->nodes[current_node]->parent;
+
+ if (state->nodes[parent]->joint && skin->joints.find(parent) < 0) {
+ skin->joints.push_back(parent);
+ } else if (skin->non_joints.find(parent) < 0) {
+ skin->non_joints.push_back(parent);
+ }
+
+ roots.write[i] = parent;
+ }
+ }
+
+ } while (!all_same);
+}
+
+Error GLTFDocument::_expand_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin) {
+ _capture_nodes_for_multirooted_skin(state, skin);
+
+ // Grab all nodes that lay in between skin joints/nodes
+ DisjointSet<GLTFNodeIndex> disjoint_set;
+
+ Vector<GLTFNodeIndex> all_skin_nodes;
+ all_skin_nodes.append_array(skin->joints);
+ all_skin_nodes.append_array(skin->non_joints);
+
+ for (int i = 0; i < all_skin_nodes.size(); ++i) {
+ const GLTFNodeIndex node_index = all_skin_nodes[i];
+ const GLTFNodeIndex parent = state->nodes[node_index]->parent;
+ disjoint_set.insert(node_index);
+
+ if (all_skin_nodes.find(parent) >= 0) {
+ disjoint_set.create_union(parent, node_index);
+ }
+ }
+
+ Vector<GLTFNodeIndex> out_owners;
+ disjoint_set.get_representatives(out_owners);
+
+ Vector<GLTFNodeIndex> out_roots;
+
+ for (int i = 0; i < out_owners.size(); ++i) {
+ Vector<GLTFNodeIndex> set;
+ disjoint_set.get_members(set, out_owners[i]);
+
+ const GLTFNodeIndex root = _find_highest_node(state, set);
+ ERR_FAIL_COND_V(root < 0, FAILED);
+ out_roots.push_back(root);
+ }
+
+ out_roots.sort();
+
+ for (int i = 0; i < out_roots.size(); ++i) {
+ _capture_nodes_in_skin(state, skin, out_roots[i]);
+ }
+
+ skin->roots = out_roots;
+
+ return OK;
+}
+
+Error GLTFDocument::_verify_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin) {
+ // This may seem duplicated from expand_skins, but this is really a sanity check! (so it kinda is)
+ // In case additional interpolating logic is added to the skins, this will help ensure that you
+ // do not cause it to self implode into a fiery blaze
+
+ // We are going to re-calculate the root nodes and compare them to the ones saved in the skin,
+ // then ensure the multiple trees (if they exist) are on the same sublevel
+
+ // Grab all nodes that lay in between skin joints/nodes
+ DisjointSet<GLTFNodeIndex> disjoint_set;
+
+ Vector<GLTFNodeIndex> all_skin_nodes;
+ all_skin_nodes.append_array(skin->joints);
+ all_skin_nodes.append_array(skin->non_joints);
+
+ for (int i = 0; i < all_skin_nodes.size(); ++i) {
+ const GLTFNodeIndex node_index = all_skin_nodes[i];
+ const GLTFNodeIndex parent = state->nodes[node_index]->parent;
+ disjoint_set.insert(node_index);
+
+ if (all_skin_nodes.find(parent) >= 0) {
+ disjoint_set.create_union(parent, node_index);
+ }
+ }
+
+ Vector<GLTFNodeIndex> out_owners;
+ disjoint_set.get_representatives(out_owners);
+
+ Vector<GLTFNodeIndex> out_roots;
+
+ for (int i = 0; i < out_owners.size(); ++i) {
+ Vector<GLTFNodeIndex> set;
+ disjoint_set.get_members(set, out_owners[i]);
+
+ const GLTFNodeIndex root = _find_highest_node(state, set);
+ ERR_FAIL_COND_V(root < 0, FAILED);
+ out_roots.push_back(root);
+ }
+
+ out_roots.sort();
+
+ ERR_FAIL_COND_V(out_roots.size() == 0, FAILED);
+
+ // Make sure the roots are the exact same (they better be)
+ ERR_FAIL_COND_V(out_roots.size() != skin->roots.size(), FAILED);
+ for (int i = 0; i < out_roots.size(); ++i) {
+ ERR_FAIL_COND_V(out_roots[i] != skin->roots[i], FAILED);
+ }
+
+ // Single rooted skin? Perfectly ok!
+ if (out_roots.size() == 1) {
+ return OK;
+ }
+
+ // Make sure all parents of a multi-rooted skin are the SAME
+ const GLTFNodeIndex parent = state->nodes[out_roots[0]]->parent;
+ for (int i = 1; i < out_roots.size(); ++i) {
+ if (state->nodes[out_roots[i]]->parent != parent) {
+ return FAILED;
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_skins(Ref<GLTFState> state) {
+ if (!state->json.has("skins"))
+ return OK;
+
+ const Array &skins = state->json["skins"];
+
+ // Create the base skins, and mark nodes that are joints
+ for (int i = 0; i < skins.size(); i++) {
+ const Dictionary &d = skins[i];
+
+ Ref<GLTFSkin> skin;
+ skin.instance();
+
+ ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
+
+ const Array &joints = d["joints"];
+
+ if (d.has("inverseBindMatrices")) {
+ skin->inverse_binds = _decode_accessor_as_xform(state, d["inverseBindMatrices"], false);
+ ERR_FAIL_COND_V(skin->inverse_binds.size() != joints.size(), ERR_PARSE_ERROR);
+ }
+
+ for (int j = 0; j < joints.size(); j++) {
+ const GLTFNodeIndex node = joints[j];
+ ERR_FAIL_INDEX_V(node, state->nodes.size(), ERR_PARSE_ERROR);
+
+ skin->joints.push_back(node);
+ skin->joints_original.push_back(node);
+
+ state->nodes.write[node]->joint = true;
+ }
+
+ if (d.has("name")) {
+ skin->set_name(d["name"]);
+ }
+
+ if (d.has("skeleton")) {
+ skin->skin_root = d["skeleton"];
+ }
+
+ state->skins.push_back(skin);
+ }
+
+ for (GLTFSkinIndex i = 0; i < state->skins.size(); ++i) {
+ Ref<GLTFSkin> skin = state->skins.write[i];
+
+ // Expand the skin to capture all the extra non-joints that lie in between the actual joints,
+ // and expand the hierarchy to ensure multi-rooted trees lie on the same height level
+ ERR_FAIL_COND_V(_expand_skin(state, skin), ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(_verify_skin(state, skin), ERR_PARSE_ERROR);
+ }
+
+ print_verbose("glTF: Total skins: " + itos(state->skins.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_determine_skeletons(Ref<GLTFState> state) {
+ // Using a disjoint set, we are going to potentially combine all skins that are actually branches
+ // of a main skeleton, or treat skins defining the same set of nodes as ONE skeleton.
+ // This is another unclear issue caused by the current glTF specification.
+
+ DisjointSet<GLTFNodeIndex> skeleton_sets;
+
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ const Ref<GLTFSkin> skin = state->skins[skin_i];
+
+ Vector<GLTFNodeIndex> all_skin_nodes;
+ all_skin_nodes.append_array(skin->joints);
+ all_skin_nodes.append_array(skin->non_joints);
+
+ for (int i = 0; i < all_skin_nodes.size(); ++i) {
+ const GLTFNodeIndex node_index = all_skin_nodes[i];
+ const GLTFNodeIndex parent = state->nodes[node_index]->parent;
+ skeleton_sets.insert(node_index);
+
+ if (all_skin_nodes.find(parent) >= 0) {
+ skeleton_sets.create_union(parent, node_index);
+ }
+ }
+
+ // We are going to connect the separate skin subtrees in each skin together
+ // so that the final roots are entire sets of valid skin trees
+ for (int i = 1; i < skin->roots.size(); ++i) {
+ skeleton_sets.create_union(skin->roots[0], skin->roots[i]);
+ }
+ }
+
+ { // attempt to joint all touching subsets (siblings/parent are part of another skin)
+ Vector<GLTFNodeIndex> groups_representatives;
+ skeleton_sets.get_representatives(groups_representatives);
+
+ Vector<GLTFNodeIndex> highest_group_members;
+ Vector<Vector<GLTFNodeIndex>> groups;
+ for (int i = 0; i < groups_representatives.size(); ++i) {
+ Vector<GLTFNodeIndex> group;
+ skeleton_sets.get_members(group, groups_representatives[i]);
+ highest_group_members.push_back(_find_highest_node(state, group));
+ groups.push_back(group);
+ }
+
+ for (int i = 0; i < highest_group_members.size(); ++i) {
+ const GLTFNodeIndex node_i = highest_group_members[i];
+
+ // Attach any siblings together (this needs to be done n^2/2 times)
+ for (int j = i + 1; j < highest_group_members.size(); ++j) {
+ const GLTFNodeIndex node_j = highest_group_members[j];
+
+ // Even if they are siblings under the root! :)
+ if (state->nodes[node_i]->parent == state->nodes[node_j]->parent) {
+ skeleton_sets.create_union(node_i, node_j);
+ }
+ }
+
+ // Attach any parenting going on together (we need to do this n^2 times)
+ const GLTFNodeIndex node_i_parent = state->nodes[node_i]->parent;
+ if (node_i_parent >= 0) {
+ for (int j = 0; j < groups.size() && i != j; ++j) {
+ const Vector<GLTFNodeIndex> &group = groups[j];
+
+ if (group.find(node_i_parent) >= 0) {
+ const GLTFNodeIndex node_j = highest_group_members[j];
+ skeleton_sets.create_union(node_i, node_j);
+ }
+ }
+ }
+ }
+ }
+
+ // At this point, the skeleton groups should be finalized
+ Vector<GLTFNodeIndex> skeleton_owners;
+ skeleton_sets.get_representatives(skeleton_owners);
+
+ // Mark all the skins actual skeletons, after we have merged them
+ for (GLTFSkeletonIndex skel_i = 0; skel_i < skeleton_owners.size(); ++skel_i) {
+ const GLTFNodeIndex skeleton_owner = skeleton_owners[skel_i];
+ Ref<GLTFSkeleton> skeleton;
+ skeleton.instance();
+
+ Vector<GLTFNodeIndex> skeleton_nodes;
+ skeleton_sets.get_members(skeleton_nodes, skeleton_owner);
+
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ Ref<GLTFSkin> skin = state->skins.write[skin_i];
+
+ // If any of the the skeletons nodes exist in a skin, that skin now maps to the skeleton
+ for (int i = 0; i < skeleton_nodes.size(); ++i) {
+ GLTFNodeIndex skel_node_i = skeleton_nodes[i];
+ if (skin->joints.find(skel_node_i) >= 0 || skin->non_joints.find(skel_node_i) >= 0) {
+ skin->skeleton = skel_i;
+ continue;
+ }
+ }
+ }
+
+ Vector<GLTFNodeIndex> non_joints;
+ for (int i = 0; i < skeleton_nodes.size(); ++i) {
+ const GLTFNodeIndex node_i = skeleton_nodes[i];
+
+ if (state->nodes[node_i]->joint) {
+ skeleton->joints.push_back(node_i);
+ } else {
+ non_joints.push_back(node_i);
+ }
+ }
+
+ state->skeletons.push_back(skeleton);
+
+ _reparent_non_joint_skeleton_subtrees(state, state->skeletons.write[skel_i], non_joints);
+ }
+
+ for (GLTFSkeletonIndex skel_i = 0; skel_i < state->skeletons.size(); ++skel_i) {
+ Ref<GLTFSkeleton> skeleton = state->skeletons.write[skel_i];
+
+ for (int i = 0; i < skeleton->joints.size(); ++i) {
+ const GLTFNodeIndex node_i = skeleton->joints[i];
+ Ref<GLTFNode> node = state->nodes[node_i];
+
+ ERR_FAIL_COND_V(!node->joint, ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(node->skeleton >= 0, ERR_PARSE_ERROR);
+ node->skeleton = skel_i;
+ }
+
+ ERR_FAIL_COND_V(_determine_skeleton_roots(state, skel_i), ERR_PARSE_ERROR);
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_reparent_non_joint_skeleton_subtrees(Ref<GLTFState> state, Ref<GLTFSkeleton> skeleton, const Vector<GLTFNodeIndex> &non_joints) {
+ DisjointSet<GLTFNodeIndex> subtree_set;
+
+ // Populate the disjoint set with ONLY non joints that are in the skeleton hierarchy (non_joints vector)
+ // This way we can find any joints that lie in between joints, as the current glTF specification
+ // mentions nothing about non-joints being in between joints of the same skin. Hopefully one day we
+ // can remove this code.
+
+ // skinD depicted here explains this issue:
+ // https://github.com/KhronosGroup/glTF-Asset-Generator/blob/master/Output/Positive/Animation_Skin
+
+ for (int i = 0; i < non_joints.size(); ++i) {
+ const GLTFNodeIndex node_i = non_joints[i];
+
+ subtree_set.insert(node_i);
+
+ const GLTFNodeIndex parent_i = state->nodes[node_i]->parent;
+ if (parent_i >= 0 && non_joints.find(parent_i) >= 0 && !state->nodes[parent_i]->joint) {
+ subtree_set.create_union(parent_i, node_i);
+ }
+ }
+
+ // Find all the non joint subtrees and re-parent them to a new "fake" joint
+
+ Vector<GLTFNodeIndex> non_joint_subtree_roots;
+ subtree_set.get_representatives(non_joint_subtree_roots);
+
+ for (int root_i = 0; root_i < non_joint_subtree_roots.size(); ++root_i) {
+ const GLTFNodeIndex subtree_root = non_joint_subtree_roots[root_i];
+
+ Vector<GLTFNodeIndex> subtree_nodes;
+ subtree_set.get_members(subtree_nodes, subtree_root);
+
+ for (int subtree_i = 0; subtree_i < subtree_nodes.size(); ++subtree_i) {
+ ERR_FAIL_COND_V(_reparent_to_fake_joint(state, skeleton, subtree_nodes[subtree_i]), FAILED);
+
+ // We modified the tree, recompute all the heights
+ _compute_node_heights(state);
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_reparent_to_fake_joint(Ref<GLTFState> state, Ref<GLTFSkeleton> skeleton, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> node = state->nodes[node_index];
+
+ // Can we just "steal" this joint if it is just a spatial node?
+ if (node->skin < 0 && node->mesh < 0 && node->camera < 0) {
+ node->joint = true;
+ // Add the joint to the skeletons joints
+ skeleton->joints.push_back(node_index);
+ return OK;
+ }
+
+ GLTFNode *fake_joint = memnew(GLTFNode);
+ const GLTFNodeIndex fake_joint_index = state->nodes.size();
+ state->nodes.push_back(fake_joint);
+
+ // We better not be a joint, or we messed up in our logic
+ if (node->joint)
+ return FAILED;
+
+ fake_joint->translation = node->translation;
+ fake_joint->rotation = node->rotation;
+ fake_joint->scale = node->scale;
+ fake_joint->xform = node->xform;
+ fake_joint->joint = true;
+
+ // We can use the exact same name here, because the joint will be inside a skeleton and not the scene
+ fake_joint->set_name(node->get_name());
+
+ // Clear the nodes transforms, since it will be parented to the fake joint
+ node->translation = Vector3(0, 0, 0);
+ node->rotation = Quat();
+ node->scale = Vector3(1, 1, 1);
+ node->xform = Transform();
+
+ // Transfer the node children to the fake joint
+ for (int child_i = 0; child_i < node->children.size(); ++child_i) {
+ Ref<GLTFNode> child = state->nodes[node->children[child_i]];
+ child->parent = fake_joint_index;
+ }
+
+ fake_joint->children = node->children;
+ node->children.clear();
+
+ // add the fake joint to the parent and remove the original joint
+ if (node->parent >= 0) {
+ Ref<GLTFNode> parent = state->nodes[node->parent];
+ parent->children.erase(node_index);
+ parent->children.push_back(fake_joint_index);
+ fake_joint->parent = node->parent;
+ }
+
+ // Add the node to the fake joint
+ fake_joint->children.push_back(node_index);
+ node->parent = fake_joint_index;
+ node->fake_joint_parent = fake_joint_index;
+
+ // Add the fake joint to the skeletons joints
+ skeleton->joints.push_back(fake_joint_index);
+
+ // Replace skin_skeletons with fake joints if we must.
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ Ref<GLTFSkin> skin = state->skins.write[skin_i];
+ if (skin->skin_root == node_index) {
+ skin->skin_root = fake_joint_index;
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_determine_skeleton_roots(Ref<GLTFState> state, const GLTFSkeletonIndex skel_i) {
+ DisjointSet<GLTFNodeIndex> disjoint_set;
+
+ for (GLTFNodeIndex i = 0; i < state->nodes.size(); ++i) {
+ const Ref<GLTFNode> node = state->nodes[i];
+
+ if (node->skeleton != skel_i) {
+ continue;
+ }
+
+ disjoint_set.insert(i);
+
+ if (node->parent >= 0 && state->nodes[node->parent]->skeleton == skel_i) {
+ disjoint_set.create_union(node->parent, i);
+ }
+ }
+
+ Ref<GLTFSkeleton> skeleton = state->skeletons.write[skel_i];
+
+ Vector<GLTFNodeIndex> owners;
+ disjoint_set.get_representatives(owners);
+
+ Vector<GLTFNodeIndex> roots;
+
+ for (int i = 0; i < owners.size(); ++i) {
+ Vector<GLTFNodeIndex> set;
+ disjoint_set.get_members(set, owners[i]);
+ const GLTFNodeIndex root = _find_highest_node(state, set);
+ ERR_FAIL_COND_V(root < 0, FAILED);
+ roots.push_back(root);
+ }
+
+ roots.sort();
+
+ skeleton->roots = roots;
+
+ if (roots.size() == 0) {
+ return FAILED;
+ } else if (roots.size() == 1) {
+ return OK;
+ }
+
+ // Check that the subtrees have the same parent root
+ const GLTFNodeIndex parent = state->nodes[roots[0]]->parent;
+ for (int i = 1; i < roots.size(); ++i) {
+ if (state->nodes[roots[i]]->parent != parent) {
+ return FAILED;
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_create_skeletons(Ref<GLTFState> state) {
+ for (GLTFSkeletonIndex skel_i = 0; skel_i < state->skeletons.size(); ++skel_i) {
+ Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skel_i];
+
+ Skeleton3D *skeleton = memnew(Skeleton3D);
+ gltf_skeleton->godot_skeleton = skeleton;
+
+ // Make a unique name, no gltf node represents this skeleton
+ skeleton->set_name(_gen_unique_name(state, "Skeleton3D"));
+
+ List<GLTFNodeIndex> bones;
+
+ for (int i = 0; i < gltf_skeleton->roots.size(); ++i) {
+ bones.push_back(gltf_skeleton->roots[i]);
+ }
+
+ // Make the skeleton creation deterministic by going through the roots in
+ // a sorted order, and DEPTH FIRST
+ bones.sort();
+
+ while (!bones.is_empty()) {
+ const GLTFNodeIndex node_i = bones.front()->get();
+ bones.pop_front();
+
+ Ref<GLTFNode> node = state->nodes[node_i];
+ ERR_FAIL_COND_V(node->skeleton != skel_i, FAILED);
+
+ { // Add all child nodes to the stack (deterministically)
+ Vector<GLTFNodeIndex> child_nodes;
+ for (int i = 0; i < node->children.size(); ++i) {
+ const GLTFNodeIndex child_i = node->children[i];
+ if (state->nodes[child_i]->skeleton == skel_i) {
+ child_nodes.push_back(child_i);
+ }
+ }
+
+ // Depth first insertion
+ child_nodes.sort();
+ for (int i = child_nodes.size() - 1; i >= 0; --i) {
+ bones.push_front(child_nodes[i]);
+ }
+ }
+
+ const int bone_index = skeleton->get_bone_count();
+
+ if (node->get_name().is_empty()) {
+ node->set_name("bone");
+ }
+
+ node->set_name(_gen_unique_bone_name(state, skel_i, node->get_name()));
+
+ skeleton->add_bone(node->get_name());
+ skeleton->set_bone_rest(bone_index, node->xform);
+
+ if (node->parent >= 0 && state->nodes[node->parent]->skeleton == skel_i) {
+ const int bone_parent = skeleton->find_bone(state->nodes[node->parent]->get_name());
+ ERR_FAIL_COND_V(bone_parent < 0, FAILED);
+ skeleton->set_bone_parent(bone_index, skeleton->find_bone(state->nodes[node->parent]->get_name()));
+ }
+
+ state->scene_nodes.insert(node_i, skeleton);
+ }
+ }
+
+ ERR_FAIL_COND_V(_map_skin_joints_indices_to_skeleton_bone_indices(state), ERR_PARSE_ERROR);
+
+ return OK;
+}
+
+Error GLTFDocument::_map_skin_joints_indices_to_skeleton_bone_indices(Ref<GLTFState> state) {
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ Ref<GLTFSkin> skin = state->skins.write[skin_i];
+
+ Ref<GLTFSkeleton> skeleton = state->skeletons[skin->skeleton];
+
+ for (int joint_index = 0; joint_index < skin->joints_original.size(); ++joint_index) {
+ const GLTFNodeIndex node_i = skin->joints_original[joint_index];
+ const Ref<GLTFNode> node = state->nodes[node_i];
+
+ const int bone_index = skeleton->godot_skeleton->find_bone(node->get_name());
+ ERR_FAIL_COND_V(bone_index < 0, FAILED);
+
+ skin->joint_i_to_bone_i.insert(joint_index, bone_index);
+ }
+ }
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_skins(Ref<GLTFState> state) {
+ _remove_duplicate_skins(state);
+ return OK;
+}
+
+Error GLTFDocument::_create_skins(Ref<GLTFState> state) {
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ Ref<GLTFSkin> gltf_skin = state->skins.write[skin_i];
+
+ Ref<Skin> skin;
+ skin.instance();
+
+ // Some skins don't have IBM's! What absolute monsters!
+ const bool has_ibms = !gltf_skin->inverse_binds.is_empty();
+
+ for (int joint_i = 0; joint_i < gltf_skin->joints_original.size(); ++joint_i) {
+ GLTFNodeIndex node = gltf_skin->joints_original[joint_i];
+ String bone_name = state->nodes[node]->get_name();
+
+ Transform xform;
+ if (has_ibms) {
+ xform = gltf_skin->inverse_binds[joint_i];
+ }
+
+ if (state->use_named_skin_binds) {
+ skin->add_named_bind(bone_name, xform);
+ } else {
+ int32_t bone_i = gltf_skin->joint_i_to_bone_i[joint_i];
+ skin->add_bind(bone_i, xform);
+ }
+ }
+
+ gltf_skin->godot_skin = skin;
+ }
+
+ // Purge the duplicates!
+ _remove_duplicate_skins(state);
+
+ // Create unique names now, after removing duplicates
+ for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) {
+ Ref<Skin> skin = state->skins.write[skin_i]->godot_skin;
+ if (skin->get_name().is_empty()) {
+ // Make a unique name, no gltf node represents this skin
+ skin->set_name(_gen_unique_name(state, "Skin"));
+ }
+ }
+
+ return OK;
+}
+
+bool GLTFDocument::_skins_are_same(const Ref<Skin> skin_a, const Ref<Skin> skin_b) {
+ if (skin_a->get_bind_count() != skin_b->get_bind_count()) {
+ return false;
+ }
+
+ for (int i = 0; i < skin_a->get_bind_count(); ++i) {
+ if (skin_a->get_bind_bone(i) != skin_b->get_bind_bone(i)) {
+ return false;
+ }
+
+ Transform a_xform = skin_a->get_bind_pose(i);
+ Transform b_xform = skin_b->get_bind_pose(i);
+
+ if (a_xform != b_xform) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+void GLTFDocument::_remove_duplicate_skins(Ref<GLTFState> state) {
+ for (int i = 0; i < state->skins.size(); ++i) {
+ for (int j = i + 1; j < state->skins.size(); ++j) {
+ const Ref<Skin> skin_i = state->skins[i]->godot_skin;
+ const Ref<Skin> skin_j = state->skins[j]->godot_skin;
+
+ if (_skins_are_same(skin_i, skin_j)) {
+ // replace it and delete the old
+ state->skins.write[j]->godot_skin = skin_i;
+ }
+ }
+ }
+}
+
+Error GLTFDocument::_serialize_lights(Ref<GLTFState> state) {
+ Array lights;
+ for (GLTFLightIndex i = 0; i < state->lights.size(); i++) {
+ Dictionary d;
+ Ref<GLTFLight> light = state->lights[i];
+ Array color;
+ color.resize(3);
+ color[0] = light->color.r;
+ color[1] = light->color.g;
+ color[2] = light->color.b;
+ d["color"] = color;
+ d["type"] = light->type;
+ if (light->type == "spot") {
+ Dictionary s;
+ float inner_cone_angle = light->inner_cone_angle;
+ s["innerConeAngle"] = inner_cone_angle;
+ float outer_cone_angle = light->outer_cone_angle;
+ s["outerConeAngle"] = outer_cone_angle;
+ d["spot"] = s;
+ }
+ float intensity = light->intensity;
+ d["intensity"] = intensity;
+ float range = light->range;
+ d["range"] = range;
+ lights.push_back(d);
+ }
+
+ if (!state->lights.size()) {
+ return OK;
+ }
+
+ Dictionary extensions;
+ if (state->json.has("extensions")) {
+ extensions = state->json["extensions"];
+ } else {
+ state->json["extensions"] = extensions;
+ }
+ Dictionary lights_punctual;
+ extensions["KHR_lights_punctual"] = lights_punctual;
+ lights_punctual["lights"] = lights;
+
+ print_verbose("glTF: Total lights: " + itos(state->lights.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_serialize_cameras(Ref<GLTFState> state) {
+ Array cameras;
+ cameras.resize(state->cameras.size());
+ for (GLTFCameraIndex i = 0; i < state->cameras.size(); i++) {
+ Dictionary d;
+
+ Ref<GLTFCamera> camera = state->cameras[i];
+
+ if (camera->get_perspective() == false) {
+ Dictionary og;
+ og["ymag"] = Math::deg2rad(camera->get_fov_size());
+ og["xmag"] = Math::deg2rad(camera->get_fov_size());
+ og["zfar"] = camera->get_zfar();
+ og["znear"] = camera->get_znear();
+ d["orthographic"] = og;
+ d["type"] = "orthographic";
+ } else if (camera->get_perspective()) {
+ Dictionary ppt;
+ // GLTF spec is in radians, Godot's camera is in degrees.
+ ppt["yfov"] = Math::deg2rad(camera->get_fov_size());
+ ppt["zfar"] = camera->get_zfar();
+ ppt["znear"] = camera->get_znear();
+ d["perspective"] = ppt;
+ d["type"] = "perspective";
+ }
+ cameras[i] = d;
+ }
+
+ if (!state->cameras.size()) {
+ return OK;
+ }
+
+ state->json["cameras"] = cameras;
+
+ print_verbose("glTF: Total cameras: " + itos(state->cameras.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_lights(Ref<GLTFState> state) {
+ if (!state->json.has("extensions")) {
+ return OK;
+ }
+ Dictionary extensions = state->json["extensions"];
+ if (!extensions.has("KHR_lights_punctual")) {
+ return OK;
+ }
+ Dictionary lights_punctual = extensions["KHR_lights_punctual"];
+ if (!lights_punctual.has("lights")) {
+ return OK;
+ }
+
+ const Array &lights = lights_punctual["lights"];
+
+ for (GLTFLightIndex light_i = 0; light_i < lights.size(); light_i++) {
+ const Dictionary &d = lights[light_i];
+
+ Ref<GLTFLight> light;
+ light.instance();
+ ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
+ const String &type = d["type"];
+ light->type = type;
+
+ if (d.has("color")) {
+ const Array &arr = d["color"];
+ ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
+ const Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
+ light->color = c;
+ }
+ if (d.has("intensity")) {
+ light->intensity = d["intensity"];
+ }
+ if (d.has("range")) {
+ light->range = d["range"];
+ }
+ if (type == "spot") {
+ const Dictionary &spot = d["spot"];
+ light->inner_cone_angle = spot["innerConeAngle"];
+ light->outer_cone_angle = spot["outerConeAngle"];
+ ERR_FAIL_COND_V_MSG(light->inner_cone_angle >= light->outer_cone_angle, ERR_PARSE_ERROR, "The inner angle must be smaller than the outer angle.");
+ } else if (type != "point" && type != "directional") {
+ ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Light type is unknown.");
+ }
+
+ state->lights.push_back(light);
+ }
+
+ print_verbose("glTF: Total lights: " + itos(state->lights.size()));
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) {
+ if (!state->json.has("cameras"))
+ return OK;
+
+ const Array cameras = state->json["cameras"];
+
+ for (GLTFCameraIndex i = 0; i < cameras.size(); i++) {
+ const Dictionary &d = cameras[i];
+
+ Ref<GLTFCamera> camera;
+ camera.instance();
+ ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
+ const String &type = d["type"];
+ if (type == "orthographic") {
+ camera->set_perspective(false);
+ if (d.has("orthographic")) {
+ const Dictionary &og = d["orthographic"];
+ // GLTF spec is in radians, Godot's camera is in degrees.
+ camera->set_fov_size(Math::rad2deg(real_t(og["ymag"])));
+ camera->set_zfar(og["zfar"]);
+ camera->set_znear(og["znear"]);
+ } else {
+ camera->set_fov_size(10);
+ }
+ } else if (type == "perspective") {
+ camera->set_perspective(true);
+ if (d.has("perspective")) {
+ const Dictionary &ppt = d["perspective"];
+ // GLTF spec is in radians, Godot's camera is in degrees.
+ camera->set_fov_size(Math::rad2deg(real_t(ppt["yfov"])));
+ camera->set_zfar(ppt["zfar"]);
+ camera->set_znear(ppt["znear"]);
+ } else {
+ camera->set_fov_size(10);
+ }
+ } else {
+ ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Camera3D should be in 'orthographic' or 'perspective'");
+ }
+
+ state->cameras.push_back(camera);
+ }
+
+ print_verbose("glTF: Total cameras: " + itos(state->cameras.size()));
+
+ return OK;
+}
+
+String GLTFDocument::interpolation_to_string(const GLTFAnimation::Interpolation p_interp) {
+ String interp = "LINEAR";
+ if (p_interp == GLTFAnimation::INTERP_STEP) {
+ interp = "STEP";
+ } else if (p_interp == GLTFAnimation::INTERP_LINEAR) {
+ interp = "LINEAR";
+ } else if (p_interp == GLTFAnimation::INTERP_CATMULLROMSPLINE) {
+ interp = "CATMULLROMSPLINE";
+ } else if (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE) {
+ interp = "CUBICSPLINE";
+ }
+
+ return interp;
+}
+
+Error GLTFDocument::_serialize_animations(Ref<GLTFState> state) {
+ if (!state->animation_players.size()) {
+ return OK;
+ }
+ for (int32_t player_i = 0; player_i < state->animation_players.size(); player_i++) {
+ List<StringName> animation_names;
+ AnimationPlayer *animation_player = state->animation_players[player_i];
+ animation_player->get_animation_list(&animation_names);
+ if (animation_names.size()) {
+ for (int animation_name_i = 0; animation_name_i < animation_names.size(); animation_name_i++) {
+ _convert_animation(state, animation_player, animation_names[animation_name_i]);
+ }
+ }
+ }
+ Array animations;
+ for (GLTFAnimationIndex animation_i = 0; animation_i < state->animations.size(); animation_i++) {
+ Dictionary d;
+ Ref<GLTFAnimation> gltf_animation = state->animations[animation_i];
+ if (!gltf_animation->get_tracks().size()) {
+ continue;
+ }
+
+ if (!gltf_animation->get_name().is_empty()) {
+ d["name"] = gltf_animation->get_name();
+ }
+ Array channels;
+ Array samplers;
+
+ for (Map<int, GLTFAnimation::Track>::Element *track_i = gltf_animation->get_tracks().front(); track_i; track_i = track_i->next()) {
+ GLTFAnimation::Track track = track_i->get();
+ if (track.translation_track.times.size()) {
+ Dictionary t;
+ t["sampler"] = samplers.size();
+ Dictionary s;
+
+ s["interpolation"] = interpolation_to_string(track.translation_track.interpolation);
+ Vector<real_t> times = Variant(track.translation_track.times);
+ s["input"] = _encode_accessor_as_floats(state, times, false);
+ Vector<Vector3> values = Variant(track.translation_track.values);
+ s["output"] = _encode_accessor_as_vec3(state, values, false);
+
+ samplers.push_back(s);
+
+ Dictionary target;
+ target["path"] = "translation";
+ target["node"] = track_i->key();
+
+ t["target"] = target;
+ channels.push_back(t);
+ }
+ if (track.rotation_track.times.size()) {
+ Dictionary t;
+ t["sampler"] = samplers.size();
+ Dictionary s;
+
+ s["interpolation"] = interpolation_to_string(track.rotation_track.interpolation);
+ Vector<real_t> times = Variant(track.rotation_track.times);
+ s["input"] = _encode_accessor_as_floats(state, times, false);
+ Vector<Quat> values = track.rotation_track.values;
+ s["output"] = _encode_accessor_as_quats(state, values, false);
+
+ samplers.push_back(s);
+
+ Dictionary target;
+ target["path"] = "rotation";
+ target["node"] = track_i->key();
+
+ t["target"] = target;
+ channels.push_back(t);
+ }
+ if (track.scale_track.times.size()) {
+ Dictionary t;
+ t["sampler"] = samplers.size();
+ Dictionary s;
+
+ s["interpolation"] = interpolation_to_string(track.scale_track.interpolation);
+ Vector<real_t> times = Variant(track.scale_track.times);
+ s["input"] = _encode_accessor_as_floats(state, times, false);
+ Vector<Vector3> values = Variant(track.scale_track.values);
+ s["output"] = _encode_accessor_as_vec3(state, values, false);
+
+ samplers.push_back(s);
+
+ Dictionary target;
+ target["path"] = "scale";
+ target["node"] = track_i->key();
+
+ t["target"] = target;
+ channels.push_back(t);
+ }
+ if (track.weight_tracks.size()) {
+ Dictionary t;
+ t["sampler"] = samplers.size();
+ Dictionary s;
+
+ Vector<real_t> times;
+ Vector<real_t> values;
+
+ for (int32_t times_i = 0; times_i < track.weight_tracks[0].times.size(); times_i++) {
+ real_t time = track.weight_tracks[0].times[times_i];
+ times.push_back(time);
+ }
+
+ values.resize(times.size() * track.weight_tracks.size());
+ // TODO Sort by order in blend shapes
+ for (int k = 0; k < track.weight_tracks.size(); k++) {
+ Vector<float> wdata = track.weight_tracks[k].values;
+ for (int l = 0; l < wdata.size(); l++) {
+ values.write[l * track.weight_tracks.size() + k] = wdata.write[l];
+ }
+ }
+
+ s["interpolation"] = interpolation_to_string(track.weight_tracks[track.weight_tracks.size() - 1].interpolation);
+ s["input"] = _encode_accessor_as_floats(state, times, false);
+ s["output"] = _encode_accessor_as_floats(state, values, false);
+
+ samplers.push_back(s);
+
+ Dictionary target;
+ target["path"] = "weights";
+ target["node"] = track_i->key();
+
+ t["target"] = target;
+ channels.push_back(t);
+ }
+ }
+ if (channels.size() && samplers.size()) {
+ d["channels"] = channels;
+ d["samplers"] = samplers;
+ animations.push_back(d);
+ }
+ }
+
+ state->json["animations"] = animations;
+
+ print_verbose("glTF: Total animations '" + itos(state->animations.size()) + "'.");
+
+ return OK;
+}
+
+Error GLTFDocument::_parse_animations(Ref<GLTFState> state) {
+ if (!state->json.has("animations"))
+ return OK;
+
+ const Array &animations = state->json["animations"];
+
+ for (GLTFAnimationIndex i = 0; i < animations.size(); i++) {
+ const Dictionary &d = animations[i];
+
+ Ref<GLTFAnimation> animation;
+ animation.instance();
+
+ if (!d.has("channels") || !d.has("samplers"))
+ continue;
+
+ Array channels = d["channels"];
+ Array samplers = d["samplers"];
+
+ if (d.has("name")) {
+ const String name = d["name"];
+ if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
+ animation->set_loop(true);
+ }
+ animation->set_name(_sanitize_scene_name(name));
+ }
+
+ for (int j = 0; j < channels.size(); j++) {
+ const Dictionary &c = channels[j];
+ if (!c.has("target"))
+ continue;
+
+ const Dictionary &t = c["target"];
+ if (!t.has("node") || !t.has("path")) {
+ continue;
+ }
+
+ ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
+ const int sampler = c["sampler"];
+ ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
+
+ GLTFNodeIndex node = t["node"];
+ String path = t["path"];
+
+ ERR_FAIL_INDEX_V(node, state->nodes.size(), ERR_PARSE_ERROR);
+
+ GLTFAnimation::Track *track = nullptr;
+
+ if (!animation->get_tracks().has(node)) {
+ animation->get_tracks()[node] = GLTFAnimation::Track();
+ }
+
+ track = &animation->get_tracks()[node];
+
+ const Dictionary &s = samplers[sampler];
+
+ ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
+
+ const int input = s["input"];
+ const int output = s["output"];
+
+ GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
+ int output_count = 1;
+ if (s.has("interpolation")) {
+ const String &in = s["interpolation"];
+ if (in == "STEP") {
+ interp = GLTFAnimation::INTERP_STEP;
+ } else if (in == "LINEAR") {
+ interp = GLTFAnimation::INTERP_LINEAR;
+ } else if (in == "CATMULLROMSPLINE") {
+ interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
+ output_count = 3;
+ } else if (in == "CUBICSPLINE") {
+ interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
+ output_count = 3;
+ }
+ }
+
+ const Vector<float> times = _decode_accessor_as_floats(state, input, false);
+ if (path == "translation") {
+ const Vector<Vector3> translations = _decode_accessor_as_vec3(state, output, false);
+ track->translation_track.interpolation = interp;
+ track->translation_track.times = Variant(times); //convert via variant
+ track->translation_track.values = Variant(translations); //convert via variant
+ } else if (path == "rotation") {
+ const Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false);
+ track->rotation_track.interpolation = interp;
+ track->rotation_track.times = Variant(times); //convert via variant
+ track->rotation_track.values = rotations;
+ } else if (path == "scale") {
+ const Vector<Vector3> scales = _decode_accessor_as_vec3(state, output, false);
+ track->scale_track.interpolation = interp;
+ track->scale_track.times = Variant(times); //convert via variant
+ track->scale_track.values = Variant(scales); //convert via variant
+ } else if (path == "weights") {
+ const Vector<float> weights = _decode_accessor_as_floats(state, output, false);
+
+ ERR_FAIL_INDEX_V(state->nodes[node]->mesh, state->meshes.size(), ERR_PARSE_ERROR);
+ Ref<GLTFMesh> mesh = state->meshes[state->nodes[node]->mesh];
+ ERR_CONTINUE(!mesh->get_blend_weights().size());
+ const int wc = mesh->get_blend_weights().size();
+
+ track->weight_tracks.resize(wc);
+
+ const int expected_value_count = times.size() * output_count * wc;
+ ERR_FAIL_COND_V_MSG(weights.size() != expected_value_count, ERR_PARSE_ERROR, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead.");
+
+ const int wlen = weights.size() / wc;
+ for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
+ GLTFAnimation::Channel<float> cf;
+ cf.interpolation = interp;
+ cf.times = Variant(times);
+ Vector<float> wdata;
+ wdata.resize(wlen);
+ for (int l = 0; l < wlen; l++) {
+ wdata.write[l] = weights[l * wc + k];
+ }
+
+ cf.values = wdata;
+ track->weight_tracks.write[k] = cf;
+ }
+ } else {
+ WARN_PRINT("Invalid path '" + path + "'.");
+ }
+ }
+
+ state->animations.push_back(animation);
+ }
+
+ print_verbose("glTF: Total animations '" + itos(state->animations.size()) + "'.");
+
+ return OK;
+}
+
+void GLTFDocument::_assign_scene_names(Ref<GLTFState> state) {
+ for (int i = 0; i < state->nodes.size(); i++) {
+ Ref<GLTFNode> n = state->nodes[i];
+
+ // Any joints get unique names generated when the skeleton is made, unique to the skeleton
+ if (n->skeleton >= 0)
+ continue;
+
+ if (n->get_name().is_empty()) {
+ if (n->mesh >= 0) {
+ n->set_name(_gen_unique_name(state, "Mesh"));
+ } else if (n->camera >= 0) {
+ n->set_name(_gen_unique_name(state, "Camera3D"));
+ } else {
+ n->set_name(_gen_unique_name(state, "Node"));
+ }
+ }
+
+ n->set_name(_gen_unique_name(state, n->get_name()));
+ }
+}
+
+BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> state, Skeleton3D *skeleton, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+ Ref<GLTFNode> bone_node = state->nodes[gltf_node->parent];
+
+ BoneAttachment3D *bone_attachment = memnew(BoneAttachment3D);
+ print_verbose("glTF: Creating bone attachment for: " + gltf_node->get_name());
+
+ ERR_FAIL_COND_V(!bone_node->joint, nullptr);
+
+ bone_attachment->set_bone_name(bone_node->get_name());
+
+ return bone_attachment;
+}
+
+GLTFMeshIndex GLTFDocument::_convert_mesh_instance(Ref<GLTFState> state, MeshInstance3D *p_mesh_instance) {
+ ERR_FAIL_NULL_V(p_mesh_instance, -1);
+ if (p_mesh_instance->get_mesh().is_null()) {
+ return -1;
+ }
+ Ref<EditorSceneImporterMesh> import_mesh;
+ import_mesh.instance();
+ Ref<Mesh> godot_mesh = p_mesh_instance->get_mesh();
+ if (godot_mesh.is_null()) {
+ return -1;
+ }
+ Vector<float> blend_weights;
+ Vector<String> blend_names;
+ int32_t blend_count = godot_mesh->get_blend_shape_count();
+ blend_names.resize(blend_count);
+ blend_weights.resize(blend_count);
+ for (int32_t blend_i = 0; blend_i < godot_mesh->get_blend_shape_count(); blend_i++) {
+ String blend_name = godot_mesh->get_blend_shape_name(blend_i);
+ blend_names.write[blend_i] = blend_name;
+ import_mesh->add_blend_shape(blend_name);
+ }
+ for (int32_t surface_i = 0; surface_i < godot_mesh->get_surface_count(); surface_i++) {
+ Mesh::PrimitiveType primitive_type = godot_mesh->surface_get_primitive_type(surface_i);
+ Array arrays = godot_mesh->surface_get_arrays(surface_i);
+ Array blend_shape_arrays = godot_mesh->surface_get_blend_shape_arrays(surface_i);
+ Ref<Material> mat = godot_mesh->surface_get_material(surface_i);
+ Ref<ArrayMesh> godot_array_mesh = godot_mesh;
+ String surface_name;
+ if (godot_array_mesh.is_valid()) {
+ surface_name = godot_array_mesh->surface_get_name(surface_i);
+ }
+ if (p_mesh_instance->get_surface_material(surface_i).is_valid()) {
+ mat = p_mesh_instance->get_surface_material(surface_i);
+ }
+ if (p_mesh_instance->get_material_override().is_valid()) {
+ mat = p_mesh_instance->get_material_override();
+ }
+ import_mesh->add_surface(primitive_type, arrays, blend_shape_arrays, Dictionary(), mat, surface_name);
+ }
+ for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) {
+ blend_weights.write[blend_i] = 0.0f;
+ }
+ Ref<GLTFMesh> gltf_mesh;
+ gltf_mesh.instance();
+ gltf_mesh->set_mesh(import_mesh);
+ gltf_mesh->set_blend_weights(blend_weights);
+ GLTFMeshIndex mesh_i = state->meshes.size();
+ state->meshes.push_back(gltf_mesh);
+ return mesh_i;
+}
+
+EditorSceneImporterMeshNode3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+
+ ERR_FAIL_INDEX_V(gltf_node->mesh, state->meshes.size(), nullptr);
+
+ EditorSceneImporterMeshNode3D *mi = memnew(EditorSceneImporterMeshNode3D);
+ print_verbose("glTF: Creating mesh for: " + gltf_node->get_name());
+
+ Ref<GLTFMesh> mesh = state->meshes.write[gltf_node->mesh];
+ if (mesh.is_null()) {
+ return mi;
+ }
+ Ref<EditorSceneImporterMesh> import_mesh = mesh->get_mesh();
+ if (import_mesh.is_null()) {
+ return mi;
+ }
+ mi->set_mesh(import_mesh);
+ for (int i = 0; i < mesh->get_blend_weights().size(); i++) {
+ mi->set("blend_shapes/" + mesh->get_mesh()->get_blend_shape_name(i), mesh->get_blend_weights()[i]);
+ }
+ return mi;
+}
+
+Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+
+ ERR_FAIL_INDEX_V(gltf_node->light, state->lights.size(), nullptr);
+
+ print_verbose("glTF: Creating light for: " + gltf_node->get_name());
+
+ Ref<GLTFLight> l = state->lights[gltf_node->light];
+
+ float intensity = l->intensity;
+ if (intensity > 10) {
+ // GLTF spec has the default around 1, but Blender defaults lights to 100.
+ // The only sane way to handle this is to check where it came from and
+ // handle it accordingly. If it's over 10, it probably came from Blender.
+ intensity /= 100;
+ }
+
+ if (l->type == "directional") {
+ DirectionalLight3D *light = memnew(DirectionalLight3D);
+ light->set_param(Light3D::PARAM_ENERGY, intensity);
+ light->set_color(l->color);
+ return light;
+ }
+
+ const float range = CLAMP(l->range, 0, 4096);
+ // Doubling the range will double the effective brightness, so we need double attenuation (half brightness).
+ // We want to have double intensity give double brightness, so we need half the attenuation.
+ const float attenuation = range / intensity;
+ if (l->type == "point") {
+ OmniLight3D *light = memnew(OmniLight3D);
+ light->set_param(OmniLight3D::PARAM_ATTENUATION, attenuation);
+ light->set_param(OmniLight3D::PARAM_RANGE, range);
+ light->set_color(l->color);
+ return light;
+ }
+ if (l->type == "spot") {
+ SpotLight3D *light = memnew(SpotLight3D);
+ light->set_param(SpotLight3D::PARAM_ATTENUATION, attenuation);
+ light->set_param(SpotLight3D::PARAM_RANGE, range);
+ light->set_param(SpotLight3D::PARAM_SPOT_ANGLE, Math::rad2deg(l->outer_cone_angle));
+ light->set_color(l->color);
+
+ // Line of best fit derived from guessing, see https://www.desmos.com/calculator/biiflubp8b
+ // The points in desmos are not exact, except for (1, infinity).
+ float angle_ratio = l->inner_cone_angle / l->outer_cone_angle;
+ float angle_attenuation = 0.2 / (1 - angle_ratio) - 0.1;
+ light->set_param(SpotLight3D::PARAM_SPOT_ATTENUATION, angle_attenuation);
+ return light;
+ }
+ return nullptr;
+}
+
+Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+
+ ERR_FAIL_INDEX_V(gltf_node->camera, state->cameras.size(), nullptr);
+
+ Camera3D *camera = memnew(Camera3D);
+ print_verbose("glTF: Creating camera for: " + gltf_node->get_name());
+
+ Ref<GLTFCamera> c = state->cameras[gltf_node->camera];
+ if (c->get_perspective()) {
+ camera->set_perspective(c->get_fov_size(), c->get_znear(), c->get_zfar());
+ } else {
+ camera->set_orthogonal(c->get_fov_size(), c->get_znear(), c->get_zfar());
+ }
+
+ return camera;
+}
+
+GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_camera) {
+ print_verbose("glTF: Converting camera: " + p_camera->get_name());
+
+ Ref<GLTFCamera> c;
+ c.instance();
+
+ if (p_camera->get_projection() == Camera3D::Projection::PROJECTION_PERSPECTIVE) {
+ c->set_perspective(true);
+ c->set_fov_size(p_camera->get_fov());
+ c->set_zfar(p_camera->get_far());
+ c->set_znear(p_camera->get_near());
+ } else {
+ c->set_fov_size(p_camera->get_fov());
+ c->set_zfar(p_camera->get_far());
+ c->set_znear(p_camera->get_near());
+ }
+ GLTFCameraIndex camera_index = state->cameras.size();
+ state->cameras.push_back(c);
+ return camera_index;
+}
+
+GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_light) {
+ print_verbose("glTF: Converting light: " + p_light->get_name());
+
+ Ref<GLTFLight> l;
+ l.instance();
+ l->color = p_light->get_color();
+ if (cast_to<DirectionalLight3D>(p_light)) {
+ l->type = "directional";
+ DirectionalLight3D *light = cast_to<DirectionalLight3D>(p_light);
+ l->intensity = light->get_param(DirectionalLight3D::PARAM_ENERGY);
+ l->range = FLT_MAX; // Range for directional lights is infinite in Godot.
+ } else if (cast_to<OmniLight3D>(p_light)) {
+ l->type = "point";
+ OmniLight3D *light = cast_to<OmniLight3D>(p_light);
+ l->range = light->get_param(OmniLight3D::PARAM_RANGE);
+ float attenuation = p_light->get_param(OmniLight3D::PARAM_ATTENUATION);
+ l->intensity = l->range / attenuation;
+ } else if (cast_to<SpotLight3D>(p_light)) {
+ l->type = "spot";
+ SpotLight3D *light = cast_to<SpotLight3D>(p_light);
+ l->range = light->get_param(SpotLight3D::PARAM_RANGE);
+ float attenuation = light->get_param(SpotLight3D::PARAM_ATTENUATION);
+ l->intensity = l->range / attenuation;
+ l->outer_cone_angle = Math::deg2rad(light->get_param(SpotLight3D::PARAM_SPOT_ANGLE));
+
+ // This equation is the inverse of the import equation (which has a desmos link).
+ float angle_ratio = 1 - (0.2 / (0.1 + light->get_param(SpotLight3D::PARAM_SPOT_ATTENUATION)));
+ angle_ratio = MAX(0, angle_ratio);
+ l->inner_cone_angle = l->outer_cone_angle * angle_ratio;
+ }
+
+ GLTFLightIndex light_index = state->lights.size();
+ state->lights.push_back(l);
+ return light_index;
+}
+
+GLTFSkeletonIndex GLTFDocument::_convert_skeleton(Ref<GLTFState> state, Skeleton3D *p_skeleton) {
+ print_verbose("glTF: Converting skeleton: " + p_skeleton->get_name());
+ Ref<GLTFSkeleton> gltf_skeleton;
+ gltf_skeleton.instance();
+ gltf_skeleton->set_name(_gen_unique_name(state, p_skeleton->get_name()));
+ gltf_skeleton->godot_skeleton = p_skeleton;
+ GLTFSkeletonIndex skeleton_i = state->skeletons.size();
+ state->skeletons.push_back(gltf_skeleton);
+ return skeleton_i;
+}
+
+void GLTFDocument::_convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref<GLTFNode> p_node) {
+ Transform xform = p_spatial->get_transform();
+ p_node->scale = xform.basis.get_scale();
+ p_node->rotation = xform.basis.get_rotation_quat();
+ p_node->translation = xform.origin;
+}
+
+Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+
+ Node3D *spatial = memnew(Node3D);
+ print_verbose("glTF: Converting spatial: " + gltf_node->get_name());
+
+ return spatial;
+}
+void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, Node *p_root, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
+ bool retflag = true;
+ Node3D *spatial = cast_to<Node3D>(p_current);
+ _check_visibility(p_current, retflag);
+ if (retflag) {
+ return;
+ }
+ Ref<GLTFNode> gltf_node;
+ gltf_node.instance();
+ gltf_node->set_name(_gen_unique_name(state, p_current->get_name()));
+ if (cast_to<Node3D>(p_current)) {
+ _convert_spatial(state, spatial, gltf_node);
+ }
+ if (cast_to<MeshInstance3D>(p_current)) {
+ _convert_mesh_to_gltf(p_current, state, spatial, gltf_node);
+ } else if (cast_to<BoneAttachment3D>(p_current)) {
+ _convert_bone_attachment_to_gltf(p_current, state, gltf_node, retflag);
+ // TODO 2020-12-21 iFire Handle the case of objects under the bone attachment.
+ return;
+ } else if (cast_to<Skeleton3D>(p_current)) {
+ _convert_skeleton_to_gltf(p_current, state, p_gltf_parent, p_gltf_root, gltf_node, p_root);
+ // We ignore the Godot Engine node that is the skeleton.
+ return;
+ } else if (cast_to<MultiMeshInstance3D>(p_current)) {
+ _convert_mult_mesh_instance_to_gltf(p_current, p_gltf_parent, p_gltf_root, gltf_node, state, p_root);
+ } else if (cast_to<CSGShape3D>(p_current)) {
+ if (p_current->get_parent() && cast_to<CSGShape3D>(p_current)->is_root_shape()) {
+ _convert_csg_shape_to_gltf(p_current, p_gltf_parent, gltf_node, state);
+ }
+ } else if (cast_to<GridMap>(p_current)) {
+ _convert_grid_map_to_gltf(p_current, p_gltf_parent, p_gltf_root, gltf_node, state, p_root);
+ } else if (cast_to<Camera3D>(p_current)) {
+ Camera3D *camera = Object::cast_to<Camera3D>(p_current);
+ _convert_camera_to_gltf(camera, state, spatial, gltf_node);
+ } else if (cast_to<Light3D>(p_current)) {
+ Light3D *light = Object::cast_to<Light3D>(p_current);
+ _convert_light_to_gltf(light, state, spatial, gltf_node);
+ } else if (cast_to<AnimationPlayer>(p_current)) {
+ AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current);
+ _convert_animation_player_to_gltf(animation_player, state, p_gltf_parent, p_gltf_root, gltf_node, p_current, p_root);
+ }
+ GLTFNodeIndex current_node_i = state->nodes.size();
+ GLTFNodeIndex gltf_root = p_gltf_root;
+ if (gltf_root == -1) {
+ gltf_root = current_node_i;
+ Array scenes;
+ scenes.push_back(gltf_root);
+ state->json["scene"] = scenes;
+ }
+ _create_gltf_node(state, p_current, current_node_i, p_gltf_parent, gltf_root, gltf_node);
+ for (int node_i = 0; node_i < p_current->get_child_count(); node_i++) {
+ _convert_scene_node(state, p_current->get_child(node_i), p_root, current_node_i, gltf_root);
+ }
+}
+
+void GLTFDocument::_convert_csg_shape_to_gltf(Node *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state) {
+ CSGShape3D *csg = Object::cast_to<CSGShape3D>(p_current);
+ csg->call("_update_shape");
+ Array meshes = csg->get_meshes();
+ if (meshes.size() != 2) {
+ return;
+ }
+ Ref<Material> mat;
+ if (csg->get_material_override().is_valid()) {
+ mat = csg->get_material_override();
+ }
+ Ref<GLTFMesh> gltf_mesh;
+ gltf_mesh.instance();
+ Ref<EditorSceneImporterMesh> import_mesh;
+ import_mesh.instance();
+ Ref<ArrayMesh> array_mesh = csg->get_meshes()[1];
+ for (int32_t surface_i = 0; surface_i < array_mesh->get_surface_count(); surface_i++) {
+ import_mesh->add_surface(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, array_mesh->surface_get_arrays(surface_i), Array(), Dictionary(), mat, array_mesh->surface_get_name(surface_i));
+ }
+ gltf_mesh->set_mesh(import_mesh);
+ GLTFMeshIndex mesh_i = state->meshes.size();
+ state->meshes.push_back(gltf_mesh);
+ gltf_node->mesh = mesh_i;
+ gltf_node->xform = csg->get_meshes()[0];
+ gltf_node->set_name(_gen_unique_name(state, csg->get_name()));
+}
+
+void GLTFDocument::_create_gltf_node(Ref<GLTFState> state, Node *p_scene_parent, GLTFNodeIndex current_node_i,
+ GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_gltf_node, Ref<GLTFNode> gltf_node) {
+ state->scene_nodes.insert(current_node_i, p_scene_parent);
+ state->nodes.push_back(gltf_node);
+ if (current_node_i == p_parent_node_index) {
+ return;
+ }
+ if (p_parent_node_index == -1) {
+ return;
+ }
+ state->nodes.write[p_parent_node_index]->children.push_back(current_node_i);
+}
+
+void GLTFDocument::_convert_animation_player_to_gltf(AnimationPlayer *animation_player, Ref<GLTFState> state, const GLTFNodeIndex &p_gltf_current, const GLTFNodeIndex &p_gltf_root_index, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent, Node *p_root) {
+ ERR_FAIL_COND(!animation_player);
+ state->animation_players.push_back(animation_player);
+ print_verbose(String("glTF: Converting animation player: ") + animation_player->get_name());
+}
+
+void GLTFDocument::_check_visibility(Node *p_node, bool &retflag) {
+ retflag = true;
+ Node3D *spatial = Object::cast_to<Node3D>(p_node);
+ Node2D *node_2d = Object::cast_to<Node2D>(p_node);
+ if (node_2d && !node_2d->is_visible()) {
+ return;
+ }
+ if (spatial && !spatial->is_visible()) {
+ return;
+ }
+ retflag = false;
+}
+
+void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) {
+ ERR_FAIL_COND(!camera);
+ GLTFCameraIndex camera_index = _convert_camera(state, camera);
+ if (camera_index != -1) {
+ gltf_node->camera = camera_index;
+ }
+}
+
+void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) {
+ ERR_FAIL_COND(!light);
+ GLTFLightIndex light_index = _convert_light(state, light);
+ if (light_index != -1) {
+ gltf_node->light = light_index;
+ }
+}
+
+void GLTFDocument::_convert_grid_map_to_gltf(Node *p_scene_parent, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state, Node *p_root_node) {
+ GridMap *grid_map = Object::cast_to<GridMap>(p_scene_parent);
+ ERR_FAIL_COND(!grid_map);
+ Array cells = grid_map->get_used_cells();
+ for (int32_t k = 0; k < cells.size(); k++) {
+ GLTFNode *new_gltf_node = memnew(GLTFNode);
+ gltf_node->children.push_back(state->nodes.size());
+ state->nodes.push_back(new_gltf_node);
+ Vector3 cell_location = cells[k];
+ int32_t cell = grid_map->get_cell_item(
+ Vector3(cell_location.x, cell_location.y, cell_location.z));
+ EditorSceneImporterMeshNode3D *import_mesh_node = memnew(EditorSceneImporterMeshNode3D);
+ import_mesh_node->set_mesh(grid_map->get_mesh_library()->get_item_mesh(cell));
+ Transform cell_xform;
+ cell_xform.basis.set_orthogonal_index(
+ grid_map->get_cell_item_orientation(
+ Vector3(cell_location.x, cell_location.y, cell_location.z)));
+ cell_xform.basis.scale(Vector3(grid_map->get_cell_scale(),
+ grid_map->get_cell_scale(),
+ grid_map->get_cell_scale()));
+ cell_xform.set_origin(grid_map->map_to_world(
+ Vector3(cell_location.x, cell_location.y, cell_location.z)));
+ Ref<GLTFMesh> gltf_mesh;
+ gltf_mesh.instance();
+ gltf_mesh = import_mesh_node;
+ new_gltf_node->mesh = state->meshes.size();
+ state->meshes.push_back(gltf_mesh);
+ new_gltf_node->xform = cell_xform * grid_map->get_transform();
+ new_gltf_node->set_name(_gen_unique_name(state, grid_map->get_mesh_library()->get_item_name(cell)));
+ }
+}
+
+void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Ref<GLTFState> state, Node *p_root_node) {
+ MultiMeshInstance3D *multi_mesh_instance = Object::cast_to<MultiMeshInstance3D>(p_scene_parent);
+ ERR_FAIL_COND(!multi_mesh_instance);
+ Ref<MultiMesh> multi_mesh = multi_mesh_instance->get_multimesh();
+ if (multi_mesh.is_valid()) {
+ for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count();
+ instance_i++) {
+ GLTFNode *new_gltf_node = memnew(GLTFNode);
+ Transform transform;
+ if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) {
+ Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i);
+ transform.origin =
+ Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y);
+ real_t rotation = xform_2d.get_rotation();
+ Quat quat;
+ quat.set_axis_angle(Vector3(0, 1, 0), rotation);
+ Size2 scale = xform_2d.get_scale();
+ transform.basis.set_quat_scale(quat,
+ Vector3(scale.x, 0, scale.y));
+ transform =
+ multi_mesh_instance->get_transform() * transform;
+ } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) {
+ transform = multi_mesh_instance->get_transform() *
+ multi_mesh->get_instance_transform(instance_i);
+ }
+ Ref<ArrayMesh> mm = multi_mesh->get_mesh();
+ if (mm.is_valid()) {
+ Ref<EditorSceneImporterMesh> mesh;
+ mesh.instance();
+ for (int32_t surface_i = 0; surface_i < mm->get_surface_count(); surface_i++) {
+ Array surface = mm->surface_get_arrays(surface_i);
+ mesh->add_surface(mm->surface_get_primitive_type(surface_i), surface, Array(), Dictionary(),
+ mm->surface_get_material(surface_i), mm->get_name());
+ }
+ Ref<GLTFMesh> gltf_mesh;
+ gltf_mesh.instance();
+ gltf_mesh->set_name(multi_mesh->get_name());
+ gltf_mesh->set_mesh(mesh);
+ new_gltf_node->mesh = state->meshes.size();
+ state->meshes.push_back(gltf_mesh);
+ }
+ new_gltf_node->xform = transform;
+ new_gltf_node->set_name(_gen_unique_name(state, multi_mesh_instance->get_name()));
+ gltf_node->children.push_back(state->nodes.size());
+ state->nodes.push_back(new_gltf_node);
+ }
+ }
+}
+
+void GLTFDocument::_convert_skeleton_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, const GLTFNodeIndex &p_parent_node_index, const GLTFNodeIndex &p_root_node_index, Ref<GLTFNode> gltf_node, Node *p_root_node) {
+ Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
+ if (skeleton) {
+ // Remove placeholder skeleton3d node by not creating the gltf node
+ // Skins are per mesh
+ for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) {
+ _convert_scene_node(state, skeleton->get_child(node_i), p_root_node, p_parent_node_index, p_root_node_index);
+ }
+ }
+}
+
+void GLTFDocument::_convert_bone_attachment_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, Ref<GLTFNode> gltf_node, bool &retflag) {
+ retflag = true;
+ BoneAttachment3D *bone_attachment = Object::cast_to<BoneAttachment3D>(p_scene_parent);
+ if (bone_attachment) {
+ Node *node = bone_attachment->get_parent();
+ while (node) {
+ Skeleton3D *bone_attachment_skeleton = Object::cast_to<Skeleton3D>(node);
+ if (bone_attachment_skeleton) {
+ for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < state->skeletons.size(); skeleton_i++) {
+ if (state->skeletons[skeleton_i]->godot_skeleton != bone_attachment_skeleton) {
+ continue;
+ }
+ state->skeletons.write[skeleton_i]->bone_attachments.push_back(bone_attachment);
+ break;
+ }
+ break;
+ }
+ node = node->get_parent();
+ }
+ gltf_node.unref();
+ return;
+ }
+ retflag = false;
+}
+
+void GLTFDocument::_convert_mesh_to_gltf(Node *p_scene_parent, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node) {
+ MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_scene_parent);
+ if (mi) {
+ GLTFMeshIndex gltf_mesh_index = _convert_mesh_instance(state, mi);
+ if (gltf_mesh_index != -1) {
+ gltf_node->mesh = gltf_mesh_index;
+ }
+ }
+}
+
+void GLTFDocument::_generate_scene_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index) {
+ Ref<GLTFNode> gltf_node = state->nodes[node_index];
+
+ Node3D *current_node = nullptr;
+
+ // Is our parent a skeleton
+ Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(scene_parent);
+
+ if (gltf_node->skeleton >= 0) {
+ Skeleton3D *skeleton = state->skeletons[gltf_node->skeleton]->godot_skeleton;
+
+ if (active_skeleton != skeleton) {
+ ERR_FAIL_COND_MSG(active_skeleton != nullptr, "glTF: Generating scene detected direct parented Skeletons");
+
+ // Add it to the scene if it has not already been added
+ if (skeleton->get_parent() == nullptr) {
+ scene_parent->add_child(skeleton);
+ skeleton->set_owner(scene_root);
+ }
+ }
+
+ active_skeleton = skeleton;
+ current_node = skeleton;
+ }
+
+ // If we have an active skeleton, and the node is node skinned, we need to create a bone attachment
+ if (current_node == nullptr && active_skeleton != nullptr && gltf_node->skin < 0) {
+ BoneAttachment3D *bone_attachment = _generate_bone_attachment(state, active_skeleton, node_index);
+
+ scene_parent->add_child(bone_attachment);
+ bone_attachment->set_owner(scene_root);
+
+ // There is no gltf_node that represent this, so just directly create a unique name
+ bone_attachment->set_name(_gen_unique_name(state, "BoneAttachment3D"));
+
+ // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
+ // and attach it to the bone_attachment
+ scene_parent = bone_attachment;
+ }
+
+ // We still have not managed to make a node
+ if (current_node == nullptr) {
+ if (gltf_node->mesh >= 0) {
+ current_node = _generate_mesh_instance(state, scene_parent, node_index);
+ } else if (gltf_node->camera >= 0) {
+ current_node = _generate_camera(state, scene_parent, node_index);
+ } else if (gltf_node->light >= 0) {
+ current_node = _generate_light(state, scene_parent, node_index);
+ }
+
+ if (!current_node) {
+ current_node = _generate_spatial(state, scene_parent, node_index);
+ }
+
+ scene_parent->add_child(current_node);
+ if (current_node != scene_root) {
+ current_node->set_owner(scene_root);
+ }
+ current_node->set_transform(gltf_node->xform);
+ current_node->set_name(gltf_node->get_name());
+ }
+
+ state->scene_nodes.insert(node_index, current_node);
+
+ for (int i = 0; i < gltf_node->children.size(); ++i) {
+ _generate_scene_node(state, current_node, scene_root, gltf_node->children[i]);
+ }
+}
+
+template <class T>
+struct EditorSceneImporterGLTFInterpolate {
+ T lerp(const T &a, const T &b, float c) const {
+ return a + (b - a) * c;
+ }
+
+ T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
+ const float t2 = t * t;
+ const float t3 = t2 * t;
+
+ return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
+ }
+
+ T bezier(T start, T control_1, T control_2, T end, float t) {
+ /* Formula from Wikipedia article on Bezier curves. */
+ const real_t omt = (1.0 - t);
+ const real_t omt2 = omt * omt;
+ const real_t omt3 = omt2 * omt;
+ const real_t t2 = t * t;
+ const real_t t3 = t2 * t;
+
+ return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
+ }
+};
+
+// thank you for existing, partial specialization
+template <>
+struct EditorSceneImporterGLTFInterpolate<Quat> {
+ Quat lerp(const Quat &a, const Quat &b, const float c) const {
+ ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized.");
+ ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized.");
+
+ return a.slerp(b, c).normalized();
+ }
+
+ Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, const float c) {
+ ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized.");
+ ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized.");
+
+ return p1.slerp(p2, c).normalized();
+ }
+
+ Quat bezier(const Quat start, const Quat control_1, const Quat control_2, const Quat end, const float t) {
+ ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized.");
+ ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized.");
+
+ return start.slerp(end, t).normalized();
+ }
+};
+
+template <class T>
+T GLTFDocument::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp) {
+ //could use binary search, worth it?
+ int idx = -1;
+ for (int i = 0; i < p_times.size(); i++) {
+ if (p_times[i] > p_time)
+ break;
+ idx++;
+ }
+
+ EditorSceneImporterGLTFInterpolate<T> interp;
+
+ switch (p_interp) {
+ case GLTFAnimation::INTERP_LINEAR: {
+ if (idx == -1) {
+ return p_values[0];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[p_times.size() - 1];
+ }
+
+ const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ return interp.lerp(p_values[idx], p_values[idx + 1], c);
+ } break;
+ case GLTFAnimation::INTERP_STEP: {
+ if (idx == -1) {
+ return p_values[0];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[p_times.size() - 1];
+ }
+
+ return p_values[idx];
+ } break;
+ case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
+ if (idx == -1) {
+ return p_values[1];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[1 + p_times.size() - 1];
+ }
+
+ const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
+ } break;
+ case GLTFAnimation::INTERP_CUBIC_SPLINE: {
+ if (idx == -1) {
+ return p_values[1];
+ } else if (idx >= p_times.size() - 1) {
+ return p_values[(p_times.size() - 1) * 3 + 1];
+ }
+
+ const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
+
+ const T from = p_values[idx * 3 + 1];
+ const T c1 = from + p_values[idx * 3 + 2];
+ const T to = p_values[idx * 3 + 4];
+ const T c2 = to + p_values[idx * 3 + 3];
+
+ return interp.bezier(from, c1, c2, to, c);
+ } break;
+ }
+
+ ERR_FAIL_V(p_values[0]);
+}
+
+void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, const GLTFAnimationIndex index, const int bake_fps) {
+ Ref<GLTFAnimation> anim = state->animations[index];
+
+ String name = anim->get_name();
+ if (name.is_empty()) {
+ // No node represent these, and they are not in the hierarchy, so just make a unique name
+ name = _gen_unique_name(state, "Animation");
+ }
+
+ Ref<Animation> animation;
+ animation.instance();
+ animation->set_name(name);
+
+ if (anim->get_loop()) {
+ animation->set_loop(true);
+ }
+
+ float length = 0;
+
+ for (Map<int, GLTFAnimation::Track>::Element *track_i = anim->get_tracks().front(); track_i; track_i = track_i->next()) {
+ const GLTFAnimation::Track &track = track_i->get();
+ //need to find the path
+ NodePath node_path;
+
+ GLTFNodeIndex node_index = track_i->key();
+ if (state->nodes[node_index]->fake_joint_parent >= 0) {
+ // Should be same as parent
+ node_index = state->nodes[node_index]->fake_joint_parent;
+ }
+
+ const Ref<GLTFNode> gltf_node = state->nodes[track_i->key()];
+
+ if (gltf_node->skeleton >= 0) {
+ const Skeleton3D *sk = Object::cast_to<Skeleton3D>(state->scene_nodes.find(node_index)->get());
+ ERR_FAIL_COND(sk == nullptr);
+
+ const String path = ap->get_parent()->get_path_to(sk);
+ const String bone = gltf_node->get_name();
+ node_path = path + ":" + bone;
+ } else {
+ Node *root = ap->get_parent();
+ Node *godot_node = state->scene_nodes.find(node_index)->get();
+ node_path = root->get_path_to(godot_node);
+ }
+
+ for (int i = 0; i < track.rotation_track.times.size(); i++) {
+ length = MAX(length, track.rotation_track.times[i]);
+ }
+ for (int i = 0; i < track.translation_track.times.size(); i++) {
+ length = MAX(length, track.translation_track.times[i]);
+ }
+ for (int i = 0; i < track.scale_track.times.size(); i++) {
+ length = MAX(length, track.scale_track.times[i]);
+ }
+
+ for (int i = 0; i < track.weight_tracks.size(); i++) {
+ for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
+ length = MAX(length, track.weight_tracks[i].times[j]);
+ }
+ }
+
+ if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) {
+ //make transform track
+ int track_idx = animation->get_track_count();
+ animation->add_track(Animation::TYPE_TRANSFORM);
+ animation->track_set_path(track_idx, node_path);
+ //first determine animation length
+
+ const float increment = 1.0 / float(bake_fps);
+ float time = 0.0;
+
+ Vector3 base_pos;
+ Quat base_rot;
+ Vector3 base_scale = Vector3(1, 1, 1);
+
+ if (!track.rotation_track.values.size()) {
+ base_rot = state->nodes[track_i->key()]->rotation.normalized();
+ }
+
+ if (!track.translation_track.values.size()) {
+ base_pos = state->nodes[track_i->key()]->translation;
+ }
+
+ if (!track.scale_track.values.size()) {
+ base_scale = state->nodes[track_i->key()]->scale;
+ }
+
+ bool last = false;
+ while (true) {
+ Vector3 pos = base_pos;
+ Quat rot = base_rot;
+ Vector3 scale = base_scale;
+
+ if (track.translation_track.times.size()) {
+ pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
+ }
+
+ if (track.rotation_track.times.size()) {
+ rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
+ }
+
+ if (track.scale_track.times.size()) {
+ scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
+ }
+
+ if (gltf_node->skeleton >= 0) {
+ Transform xform;
+ xform.basis.set_quat_scale(rot, scale);
+ xform.origin = pos;
+
+ const Skeleton3D *skeleton = state->skeletons[gltf_node->skeleton]->godot_skeleton;
+ const int bone_idx = skeleton->find_bone(gltf_node->get_name());
+ xform = skeleton->get_bone_rest(bone_idx).affine_inverse() * xform;
+
+ rot = xform.basis.get_rotation_quat();
+ rot.normalize();
+ scale = xform.basis.get_scale();
+ pos = xform.origin;
+ }
+
+ animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
+
+ if (last) {
+ break;
+ }
+ time += increment;
+ if (time >= length) {
+ last = true;
+ time = length;
+ }
+ }
+ }
+
+ for (int i = 0; i < track.weight_tracks.size(); i++) {
+ ERR_CONTINUE(gltf_node->mesh < 0 || gltf_node->mesh >= state->meshes.size());
+ Ref<GLTFMesh> mesh = state->meshes[gltf_node->mesh];
+ ERR_CONTINUE(mesh.is_null());
+ ERR_CONTINUE(mesh->get_mesh().is_null());
+ ERR_CONTINUE(mesh->get_mesh()->get_mesh().is_null());
+ const String prop = "blend_shapes/" + mesh->get_mesh()->get_blend_shape_name(i);
+
+ const String blend_path = String(node_path) + ":" + prop;
+
+ const int track_idx = animation->get_track_count();
+ animation->add_track(Animation::TYPE_VALUE);
+ animation->track_set_path(track_idx, blend_path);
+
+ // Only LINEAR and STEP (NEAREST) can be supported out of the box by Godot's Animation,
+ // the other modes have to be baked.
+ GLTFAnimation::Interpolation gltf_interp = track.weight_tracks[i].interpolation;
+ if (gltf_interp == GLTFAnimation::INTERP_LINEAR || gltf_interp == GLTFAnimation::INTERP_STEP) {
+ animation->track_set_interpolation_type(track_idx, gltf_interp == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_LINEAR);
+ for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
+ const float t = track.weight_tracks[i].times[j];
+ const float attribs = track.weight_tracks[i].values[j];
+ animation->track_insert_key(track_idx, t, attribs);
+ }
+ } else {
+ // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
+ const float increment = 1.0 / float(bake_fps);
+ float time = 0.0;
+ bool last = false;
+ while (true) {
+ _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, gltf_interp);
+ if (last) {
+ break;
+ }
+ time += increment;
+ if (time >= length) {
+ last = true;
+ time = length;
+ }
+ }
+ }
+ }
+ }
+
+ animation->set_length(length);
+
+ ap->add_animation(name, animation);
+}
+
+void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) {
+ for (GLTFNodeIndex mi_node_i = 0; mi_node_i < state->nodes.size(); ++mi_node_i) {
+ Ref<GLTFNode> node = state->nodes[mi_node_i];
+
+ if (node->mesh < 0) {
+ continue;
+ }
+ Array json_skins;
+ if (state->json.has("skins")) {
+ json_skins = state->json["skins"];
+ }
+ Map<GLTFNodeIndex, Node *>::Element *mi_element = state->scene_nodes.find(mi_node_i);
+ if (!mi_element) {
+ continue;
+ }
+ MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(mi_element->get());
+ ERR_CONTINUE(!mi);
+ Transform mi_xform = mi->get_transform();
+ node->scale = mi_xform.basis.get_scale();
+ node->rotation = mi_xform.basis.get_rotation_quat();
+ node->translation = mi_xform.origin;
+
+ Dictionary json_skin;
+ Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(mi->get_node(mi->get_skeleton_path()));
+ if (!skeleton) {
+ continue;
+ }
+ if (!skeleton->get_bone_count()) {
+ continue;
+ }
+ Ref<Skin> skin = mi->get_skin();
+ if (skin.is_null()) {
+ skin = skeleton->register_skin(nullptr)->get_skin();
+ }
+ Ref<GLTFSkin> gltf_skin;
+ gltf_skin.instance();
+ Array json_joints;
+ GLTFSkeletonIndex skeleton_gltf_i = -1;
+
+ NodePath skeleton_path = mi->get_skeleton_path();
+ bool is_unique = true;
+ for (int32_t skin_i = 0; skin_i < state->skins.size(); skin_i++) {
+ Ref<GLTFSkin> prev_gltf_skin = state->skins.write[skin_i];
+ if (gltf_skin.is_null()) {
+ continue;
+ }
+ GLTFSkeletonIndex prev_skeleton = prev_gltf_skin->get_skeleton();
+ if (prev_skeleton == -1 || prev_skeleton >= state->skeletons.size()) {
+ continue;
+ }
+ if (prev_gltf_skin->get_godot_skin() == skin && state->skeletons[prev_skeleton]->godot_skeleton == skeleton) {
+ node->skin = skin_i;
+ node->skeleton = prev_skeleton;
+ is_unique = false;
+ break;
+ }
+ }
+ if (!is_unique) {
+ continue;
+ }
+ GLTFSkeletonIndex skeleton_i = _convert_skeleton(state, skeleton);
+ skeleton_gltf_i = skeleton_i;
+ ERR_CONTINUE(skeleton_gltf_i == -1);
+ gltf_skin->skeleton = skeleton_gltf_i;
+ Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skeleton_gltf_i];
+ for (int32_t bind_i = 0; bind_i < skin->get_bind_count(); bind_i++) {
+ String godot_bone_name = skin->get_bind_name(bind_i);
+ if (godot_bone_name.is_empty()) {
+ int32_t bone = skin->get_bind_bone(bind_i);
+ godot_bone_name = skeleton->get_bone_name(bone);
+ }
+ if (skeleton->find_bone(godot_bone_name) == -1) {
+ godot_bone_name = skeleton->get_bone_name(0);
+ }
+ BoneId bone_index = skeleton->find_bone(godot_bone_name);
+ ERR_CONTINUE(bone_index == -1);
+ Ref<GLTFNode> joint_node;
+ joint_node.instance();
+ String gltf_bone_name = _gen_unique_bone_name(state, skeleton_gltf_i, godot_bone_name);
+ joint_node->set_name(gltf_bone_name);
+
+ Transform bone_rest_xform = skeleton->get_bone_rest(bone_index);
+ joint_node->scale = bone_rest_xform.basis.get_scale();
+ joint_node->rotation = bone_rest_xform.basis.get_rotation_quat();
+ joint_node->translation = bone_rest_xform.origin;
+ joint_node->joint = true;
+
+ int32_t joint_node_i = state->nodes.size();
+ state->nodes.push_back(joint_node);
+ gltf_skeleton->godot_bone_node.insert(bone_index, joint_node_i);
+ int32_t joint_index = gltf_skin->joints.size();
+ gltf_skin->joint_i_to_bone_i.insert(joint_index, bone_index);
+ gltf_skin->joints.push_back(joint_node_i);
+ gltf_skin->joints_original.push_back(joint_node_i);
+ gltf_skin->inverse_binds.push_back(skin->get_bind_pose(bind_i));
+ json_joints.push_back(joint_node_i);
+ for (Map<GLTFNodeIndex, Node *>::Element *skin_scene_node_i = state->scene_nodes.front(); skin_scene_node_i; skin_scene_node_i = skin_scene_node_i->next()) {
+ if (skin_scene_node_i->get() == skeleton) {
+ gltf_skin->skin_root = skin_scene_node_i->key();
+ json_skin["skeleton"] = skin_scene_node_i->key();
+ }
+ }
+ gltf_skin->godot_skin = skin;
+ gltf_skin->set_name(_gen_unique_name(state, skin->get_name()));
+ }
+ for (int32_t bind_i = 0; bind_i < skin->get_bind_count(); bind_i++) {
+ String bone_name = skeleton->get_bone_name(bind_i);
+ String godot_bone_name = skin->get_bind_name(bind_i);
+ int32_t bone = -1;
+ if (skin->get_bind_bone(bind_i) != -1) {
+ bone = skin->get_bind_bone(bind_i);
+ godot_bone_name = skeleton->get_bone_name(bone);
+ }
+ bone = skeleton->find_bone(godot_bone_name);
+ if (bone == -1) {
+ continue;
+ }
+ BoneId bone_parent = skeleton->get_bone_parent(bone);
+ GLTFNodeIndex joint_node_i = gltf_skeleton->godot_bone_node[bone];
+ ERR_CONTINUE(joint_node_i >= state->nodes.size());
+ if (bone_parent != -1) {
+ GLTFNodeIndex parent_joint_gltf_node = gltf_skin->joints[bone_parent];
+ Ref<GLTFNode> parent_joint_node = state->nodes.write[parent_joint_gltf_node];
+ parent_joint_node->children.push_back(joint_node_i);
+ } else {
+ Node *node_parent = skeleton->get_parent();
+ ERR_CONTINUE(!node_parent);
+ for (Map<GLTFNodeIndex, Node *>::Element *E = state->scene_nodes.front(); E; E = E->next()) {
+ if (E->get() == node_parent) {
+ GLTFNodeIndex gltf_node_i = E->key();
+ Ref<GLTFNode> gltf_node = state->nodes.write[gltf_node_i];
+ gltf_node->children.push_back(joint_node_i);
+ break;
+ }
+ }
+ }
+ }
+ _expand_skin(state, gltf_skin);
+ node->skin = state->skins.size();
+ state->skins.push_back(gltf_skin);
+
+ json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(state, gltf_skin->inverse_binds, false);
+ json_skin["joints"] = json_joints;
+ json_skin["name"] = gltf_skin->get_name();
+ json_skins.push_back(json_skin);
+ state->json["skins"] = json_skins;
+ }
+}
+
+float GLTFDocument::solve_metallic(float p_dielectric_specular, float diffuse, float specular, float p_one_minus_specular_strength) {
+ if (specular <= p_dielectric_specular) {
+ return 0.0f;
+ }
+
+ const float a = p_dielectric_specular;
+ const float b = diffuse * p_one_minus_specular_strength / (1.0f - p_dielectric_specular) + specular - 2.0f * p_dielectric_specular;
+ const float c = p_dielectric_specular - specular;
+ const float D = b * b - 4.0f * a * c;
+ return CLAMP((-b + Math::sqrt(D)) / (2.0f * a), 0.0f, 1.0f);
+}
+
+float GLTFDocument::get_perceived_brightness(const Color p_color) {
+ const Color coeff = Color(R_BRIGHTNESS_COEFF, G_BRIGHTNESS_COEFF, B_BRIGHTNESS_COEFF);
+ const Color value = coeff * (p_color * p_color);
+
+ const float r = value.r;
+ const float g = value.g;
+ const float b = value.b;
+
+ return Math::sqrt(r + g + b);
+}
+
+float GLTFDocument::get_max_component(const Color &p_color) {
+ const float r = p_color.r;
+ const float g = p_color.g;
+ const float b = p_color.b;
+
+ return MAX(MAX(r, g), b);
+}
+
+void GLTFDocument::_process_mesh_instances(Ref<GLTFState> state, Node *scene_root) {
+ for (GLTFNodeIndex node_i = 0; node_i < state->nodes.size(); ++node_i) {
+ Ref<GLTFNode> node = state->nodes[node_i];
+
+ if (node->skin >= 0 && node->mesh >= 0) {
+ const GLTFSkinIndex skin_i = node->skin;
+
+ Map<GLTFNodeIndex, Node *>::Element *mi_element = state->scene_nodes.find(node_i);
+ EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(mi_element->get());
+ ERR_FAIL_COND(mi == nullptr);
+
+ const GLTFSkeletonIndex skel_i = state->skins.write[node->skin]->skeleton;
+ Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skel_i];
+ Skeleton3D *skeleton = gltf_skeleton->godot_skeleton;
+ ERR_FAIL_COND(skeleton == nullptr);
+
+ mi->get_parent()->remove_child(mi);
+ skeleton->add_child(mi);
+ mi->set_owner(skeleton->get_owner());
+
+ mi->set_skin(state->skins.write[skin_i]->godot_skin);
+ mi->set_skeleton_path(mi->get_path_to(skeleton));
+ mi->set_transform(Transform());
+ }
+ }
+}
+
+GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state, GLTFAnimation::Track p_track, Ref<Animation> p_animation, Transform p_bone_rest, int32_t p_track_i, GLTFNodeIndex p_node_i) {
+ Animation::InterpolationType interpolation = p_animation->track_get_interpolation_type(p_track_i);
+
+ GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
+ if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
+ gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
+ } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
+ gltf_interpolation = GLTFAnimation::INTERP_STEP;
+ } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
+ gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
+ }
+ Animation::TrackType track_type = p_animation->track_get_type(p_track_i);
+ int32_t key_count = p_animation->track_get_key_count(p_track_i);
+ Vector<float> times;
+ times.resize(key_count);
+ String path = p_animation->track_get_path(p_track_i);
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ times.write[key_i] = p_animation->track_get_key_time(p_track_i, key_i);
+ }
+ const float BAKE_FPS = 30.0f;
+ if (track_type == Animation::TYPE_TRANSFORM) {
+ p_track.translation_track.times = times;
+ p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.rotation_track.times = times;
+ p_track.rotation_track.interpolation = gltf_interpolation;
+ p_track.scale_track.times = times;
+ p_track.scale_track.interpolation = gltf_interpolation;
+
+ p_track.scale_track.values.resize(key_count);
+ p_track.scale_track.interpolation = gltf_interpolation;
+ p_track.translation_track.values.resize(key_count);
+ p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.rotation_track.values.resize(key_count);
+ p_track.rotation_track.interpolation = gltf_interpolation;
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Vector3 translation;
+ Quat rotation;
+ Vector3 scale;
+ Error err = p_animation->transform_track_get_key(p_track_i, key_i, &translation, &rotation, &scale);
+ ERR_CONTINUE(err != OK);
+ Transform xform;
+ xform.basis.set_quat_scale(rotation, scale);
+ xform.origin = translation;
+ xform = p_bone_rest * xform;
+ p_track.translation_track.values.write[key_i] = xform.get_origin();
+ p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat();
+ p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
+ }
+ } else if (path.find(":transform") != -1) {
+ p_track.translation_track.times = times;
+ p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.rotation_track.times = times;
+ p_track.rotation_track.interpolation = gltf_interpolation;
+ p_track.scale_track.times = times;
+ p_track.scale_track.interpolation = gltf_interpolation;
+
+ p_track.scale_track.values.resize(key_count);
+ p_track.scale_track.interpolation = gltf_interpolation;
+ p_track.translation_track.values.resize(key_count);
+ p_track.translation_track.interpolation = gltf_interpolation;
+ p_track.rotation_track.values.resize(key_count);
+ p_track.rotation_track.interpolation = gltf_interpolation;
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Transform xform = p_animation->track_get_key_value(p_track_i, key_i);
+ p_track.translation_track.values.write[key_i] = xform.get_origin();
+ p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat();
+ p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
+ }
+ } else if (track_type == Animation::TYPE_VALUE) {
+ if (path.find("/rotation_quat") != -1) {
+ p_track.rotation_track.times = times;
+ p_track.rotation_track.interpolation = gltf_interpolation;
+
+ p_track.rotation_track.values.resize(key_count);
+ p_track.rotation_track.interpolation = gltf_interpolation;
+
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Quat rotation_track = p_animation->track_get_key_value(p_track_i, key_i);
+ p_track.rotation_track.values.write[key_i] = rotation_track;
+ }
+ } else if (path.find(":translation") != -1) {
+ p_track.translation_track.times = times;
+ p_track.translation_track.interpolation = gltf_interpolation;
+
+ p_track.translation_track.values.resize(key_count);
+ p_track.translation_track.interpolation = gltf_interpolation;
+
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Vector3 translation = p_animation->track_get_key_value(p_track_i, key_i);
+ p_track.translation_track.values.write[key_i] = translation;
+ }
+ } else if (path.find(":rotation_degrees") != -1) {
+ p_track.rotation_track.times = times;
+ p_track.rotation_track.interpolation = gltf_interpolation;
+
+ p_track.rotation_track.values.resize(key_count);
+ p_track.rotation_track.interpolation = gltf_interpolation;
+
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Quat rotation;
+ Vector3 rotation_degrees = p_animation->track_get_key_value(p_track_i, key_i);
+ Vector3 rotation_radian;
+ rotation_radian.x = Math::deg2rad(rotation_degrees.x);
+ rotation_radian.y = Math::deg2rad(rotation_degrees.y);
+ rotation_radian.z = Math::deg2rad(rotation_degrees.z);
+ rotation.set_euler(rotation_radian);
+ p_track.rotation_track.values.write[key_i] = rotation;
+ }
+ } else if (path.find(":scale") != -1) {
+ p_track.scale_track.times = times;
+ p_track.scale_track.interpolation = gltf_interpolation;
+
+ p_track.scale_track.values.resize(key_count);
+ p_track.scale_track.interpolation = gltf_interpolation;
+
+ for (int32_t key_i = 0; key_i < key_count; key_i++) {
+ Vector3 scale_track = p_animation->track_get_key_value(p_track_i, key_i);
+ p_track.scale_track.values.write[key_i] = scale_track;
+ }
+ }
+ } else if (track_type == Animation::TYPE_BEZIER) {
+ if (path.find("/scale") != -1) {
+ const int32_t keys = p_animation->track_get_key_time(p_track_i, key_count - 1) * BAKE_FPS;
+ if (!p_track.scale_track.times.size()) {
+ Vector<float> new_times;
+ new_times.resize(keys);
+ for (int32_t key_i = 0; key_i < keys; key_i++) {
+ new_times.write[key_i] = key_i / BAKE_FPS;
+ }
+ p_track.scale_track.times = new_times;
+ p_track.scale_track.interpolation = gltf_interpolation;
+
+ p_track.scale_track.values.resize(keys);
+
+ for (int32_t key_i = 0; key_i < keys; key_i++) {
+ p_track.scale_track.values.write[key_i] = Vector3(1.0f, 1.0f, 1.0f);
+ }
+ p_track.scale_track.interpolation = gltf_interpolation;
+ }
+
+ for (int32_t key_i = 0; key_i < keys; key_i++) {
+ Vector3 bezier_track = p_track.scale_track.values[key_i];
+ if (path.find("/scale:x") != -1) {
+ bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.x = p_bone_rest.affine_inverse().basis.get_scale().x * bezier_track.x;
+ } else if (path.find("/scale:y") != -1) {
+ bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.y = p_bone_rest.affine_inverse().basis.get_scale().y * bezier_track.y;
+ } else if (path.find("/scale:z") != -1) {
+ bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.z = p_bone_rest.affine_inverse().basis.get_scale().z * bezier_track.z;
+ }
+ p_track.scale_track.values.write[key_i] = bezier_track;
+ }
+ } else if (path.find("/translation") != -1) {
+ const int32_t keys = p_animation->track_get_key_time(p_track_i, key_count - 1) * BAKE_FPS;
+ if (!p_track.translation_track.times.size()) {
+ Vector<float> new_times;
+ new_times.resize(keys);
+ for (int32_t key_i = 0; key_i < keys; key_i++) {
+ new_times.write[key_i] = key_i / BAKE_FPS;
+ }
+ p_track.translation_track.times = new_times;
+ p_track.translation_track.interpolation = gltf_interpolation;
+
+ p_track.translation_track.values.resize(keys);
+ p_track.translation_track.interpolation = gltf_interpolation;
+ }
+
+ for (int32_t key_i = 0; key_i < keys; key_i++) {
+ Vector3 bezier_track = p_track.translation_track.values[key_i];
+ if (path.find("/translation:x") != -1) {
+ bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.x = p_bone_rest.affine_inverse().origin.x * bezier_track.x;
+ } else if (path.find("/translation:y") != -1) {
+ bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.y = p_bone_rest.affine_inverse().origin.y * bezier_track.y;
+ } else if (path.find("/translation:z") != -1) {
+ bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
+ bezier_track.z = p_bone_rest.affine_inverse().origin.z * bezier_track.z;
+ }
+ p_track.translation_track.values.write[key_i] = bezier_track;
+ }
+ }
+ }
+
+ return p_track;
+}
+
+void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, String p_animation_track_name) {
+ Ref<Animation> animation = ap->get_animation(p_animation_track_name);
+ Ref<GLTFAnimation> gltf_animation;
+ gltf_animation.instance();
+ gltf_animation->set_name(_gen_unique_name(state, p_animation_track_name));
+
+ for (int32_t track_i = 0; track_i < animation->get_track_count(); track_i++) {
+ if (!animation->track_is_enabled(track_i)) {
+ continue;
+ }
+ String orig_track_path = animation->track_get_path(track_i);
+ if (String(orig_track_path).find(":translation") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":translation");
+ const NodePath path = node_suffix[0];
+ const Node *node = ap->get_parent()->get_node_or_null(path);
+ for (Map<GLTFNodeIndex, Node *>::Element *translation_scene_node_i = state->scene_nodes.front(); translation_scene_node_i; translation_scene_node_i = translation_scene_node_i->next()) {
+ if (translation_scene_node_i->get() == node) {
+ GLTFNodeIndex node_index = translation_scene_node_i->key();
+ Map<int, GLTFAnimation::Track>::Element *translation_track_i = gltf_animation->get_tracks().find(node_index);
+ GLTFAnimation::Track track;
+ if (translation_track_i) {
+ track = translation_track_i->get();
+ }
+ track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index);
+ gltf_animation->get_tracks().insert(node_index, track);
+ }
+ }
+ } else if (String(orig_track_path).find(":rotation_degrees") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":rotation_degrees");
+ const NodePath path = node_suffix[0];
+ const Node *node = ap->get_parent()->get_node_or_null(path);
+ for (Map<GLTFNodeIndex, Node *>::Element *rotation_degree_scene_node_i = state->scene_nodes.front(); rotation_degree_scene_node_i; rotation_degree_scene_node_i = rotation_degree_scene_node_i->next()) {
+ if (rotation_degree_scene_node_i->get() == node) {
+ GLTFNodeIndex node_index = rotation_degree_scene_node_i->key();
+ Map<int, GLTFAnimation::Track>::Element *rotation_degree_track_i = gltf_animation->get_tracks().find(node_index);
+ GLTFAnimation::Track track;
+ if (rotation_degree_track_i) {
+ track = rotation_degree_track_i->get();
+ }
+ track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index);
+ gltf_animation->get_tracks().insert(node_index, track);
+ }
+ }
+ } else if (String(orig_track_path).find(":scale") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":scale");
+ const NodePath path = node_suffix[0];
+ const Node *node = ap->get_parent()->get_node_or_null(path);
+ for (Map<GLTFNodeIndex, Node *>::Element *scale_scene_node_i = state->scene_nodes.front(); scale_scene_node_i; scale_scene_node_i = scale_scene_node_i->next()) {
+ if (scale_scene_node_i->get() == node) {
+ GLTFNodeIndex node_index = scale_scene_node_i->key();
+ Map<int, GLTFAnimation::Track>::Element *scale_track_i = gltf_animation->get_tracks().find(node_index);
+ GLTFAnimation::Track track;
+ if (scale_track_i) {
+ track = scale_track_i->get();
+ }
+ track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index);
+ gltf_animation->get_tracks().insert(node_index, track);
+ }
+ }
+ } else if (String(orig_track_path).find(":transform") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":transform");
+ const NodePath path = node_suffix[0];
+ const Node *node = ap->get_parent()->get_node_or_null(path);
+ for (Map<GLTFNodeIndex, Node *>::Element *transform_track_i = state->scene_nodes.front(); transform_track_i; transform_track_i = transform_track_i->next()) {
+ if (transform_track_i->get() == node) {
+ GLTFAnimation::Track track;
+ track = _convert_animation_track(state, track, animation, Transform(), track_i, transform_track_i->key());
+ gltf_animation->get_tracks().insert(transform_track_i->key(), track);
+ }
+ }
+ } else if (String(orig_track_path).find(":blend_shapes/") != -1) {
+ const Vector<String> node_suffix = String(orig_track_path).split(":blend_shapes/");
+ const NodePath path = node_suffix[0];
+ const String suffix = node_suffix[1];
+ const Node *node = ap->get_parent()->get_node_or_null(path);
+ for (Map<GLTFNodeIndex, Node *>::Element *transform_track_i = state->scene_nodes.front(); transform_track_i; transform_track_i = transform_track_i->next()) {
+ if (transform_track_i->get() == node) {
+ const MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(node);
+ if (!mi) {
+ continue;
+ }
+ Ref<ArrayMesh> array_mesh = mi->get_mesh();
+ if (array_mesh.is_null()) {
+ continue;
+ }
+ if (node_suffix.size() != 2) {
+ continue;
+ }
+ GLTFNodeIndex mesh_index = -1;
+ for (GLTFNodeIndex node_i = 0; node_i < state->scene_nodes.size(); node_i++) {
+ if (state->scene_nodes[node_i] == node) {
+ mesh_index = node_i;
+ break;
+ }
+ }
+ ERR_CONTINUE(mesh_index == -1);
+ Ref<Mesh> mesh = mi->get_mesh();
+ ERR_CONTINUE(mesh.is_null());
+ for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) {
+ if (mesh->get_blend_shape_name(shape_i) != suffix) {
+ continue;
+ }
+ GLTFAnimation::Track track;
+ Map<int, GLTFAnimation::Track>::Element *blend_shape_track_i = gltf_animation->get_tracks().find(mesh_index);
+ if (blend_shape_track_i) {
+ track = blend_shape_track_i->get();
+ }
+ Animation::InterpolationType interpolation = animation->track_get_interpolation_type(track_i);
+
+ GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
+ if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
+ gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
+ } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
+ gltf_interpolation = GLTFAnimation::INTERP_STEP;
+ } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
+ gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
+ }
+ Animation::TrackType track_type = animation->track_get_type(track_i);
+ if (track_type == Animation::TYPE_VALUE) {
+ int32_t key_count = animation->track_get_key_count(track_i);
+ GLTFAnimation::Channel<float> weight;
+ weight.interpolation = gltf_interpolation;
+ weight.times.resize(key_count);
+ for (int32_t time_i = 0; time_i < key_count; time_i++) {
+ weight.times.write[time_i] = animation->track_get_key_time(track_i, time_i);
+ }
+ weight.values.resize(key_count);
+ for (int32_t value_i = 0; value_i < key_count; value_i++) {
+ weight.values.write[value_i] = animation->track_get_key_value(track_i, value_i);
+ }
+ track.weight_tracks.push_back(weight);
+ }
+ gltf_animation->get_tracks()[mesh_index] = track;
+ }
+ }
+ }
+
+ } else if (String(orig_track_path).find(":") != -1) {
+ //Process skeleton
+ const Vector<String> node_suffix = String(orig_track_path).split(":");
+ const String node = node_suffix[0];
+ const NodePath node_path = node;
+ const String suffix = node_suffix[1];
+ Node *godot_node = ap->get_parent()->get_node_or_null(node_path);
+ Skeleton3D *skeleton = nullptr;
+ GLTFSkeletonIndex skeleton_gltf_i = -1;
+ for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < state->skeletons.size(); skeleton_i++) {
+ if (state->skeletons[skeleton_i]->godot_skeleton == cast_to<Skeleton3D>(godot_node)) {
+ skeleton = state->skeletons[skeleton_i]->godot_skeleton;
+ skeleton_gltf_i = skeleton_i;
+ ERR_CONTINUE(!skeleton);
+ Ref<GLTFSkeleton> skeleton_gltf = state->skeletons[skeleton_gltf_i];
+ int32_t bone = skeleton->find_bone(suffix);
+ ERR_CONTINUE(bone == -1);
+ Transform xform = skeleton->get_bone_rest(bone);
+ if (!skeleton_gltf->godot_bone_node.has(bone)) {
+ continue;
+ }
+ GLTFNodeIndex node_i = skeleton_gltf->godot_bone_node[bone];
+ Map<int, GLTFAnimation::Track>::Element *property_track_i = gltf_animation->get_tracks().find(node_i);
+ GLTFAnimation::Track track;
+ if (property_track_i) {
+ track = property_track_i->get();
+ }
+ track = _convert_animation_track(state, track, animation, xform, track_i, node_i);
+ gltf_animation->get_tracks()[node_i] = track;
+ }
+ }
+ } else if (String(orig_track_path).find(":") == -1) {
+ const Node *node = ap->get_parent()->get_node_or_null(orig_track_path);
+ for (Map<GLTFNodeIndex, Node *>::Element *scene_node_i = state->scene_nodes.front(); scene_node_i; scene_node_i = scene_node_i->next()) {
+ if (scene_node_i->get() == node) {
+ GLTFNodeIndex node_index = scene_node_i->key();
+ Map<int, GLTFAnimation::Track>::Element *node_track_i = gltf_animation->get_tracks().find(node_index);
+ GLTFAnimation::Track track;
+ if (node_track_i) {
+ track = node_track_i->get();
+ }
+ track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index);
+ gltf_animation->get_tracks().insert(node_index, track);
+ break;
+ }
+ }
+ }
+ }
+ if (gltf_animation->get_tracks().size()) {
+ state->animations.push_back(gltf_animation);
+ }
+}
+
+Error GLTFDocument::parse(Ref<GLTFState> state, String p_path, bool p_read_binary) {
+ Error err;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (!f) {
+ return err;
+ }
+ uint32_t magic = f->get_32();
+ if (magic == 0x46546C67) {
+ //binary file
+ //text file
+ err = _parse_glb(p_path, state);
+ if (err)
+ return FAILED;
+ } else {
+ //text file
+ err = _parse_json(p_path, state);
+ if (err)
+ return FAILED;
+ }
+ f->close();
+
+ ERR_FAIL_COND_V(!state->json.has("asset"), Error::FAILED);
+
+ Dictionary asset = state->json["asset"];
+
+ ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
+
+ String version = asset["version"];
+
+ state->major_version = version.get_slice(".", 0).to_int();
+ state->minor_version = version.get_slice(".", 1).to_int();
+
+ /* STEP 0 PARSE SCENE */
+ err = _parse_scenes(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 1 PARSE NODES */
+ err = _parse_nodes(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 2 PARSE BUFFERS */
+ err = _parse_buffers(state, p_path.get_base_dir());
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 3 PARSE BUFFER VIEWS */
+ err = _parse_buffer_views(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 4 PARSE ACCESSORS */
+ err = _parse_accessors(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 5 PARSE IMAGES */
+ err = _parse_images(state, p_path.get_base_dir());
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 6 PARSE TEXTURES */
+ err = _parse_textures(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 7 PARSE TEXTURES */
+ err = _parse_materials(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 9 PARSE SKINS */
+ err = _parse_skins(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 10 DETERMINE SKELETONS */
+ err = _determine_skeletons(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 11 CREATE SKELETONS */
+ err = _create_skeletons(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 12 CREATE SKINS */
+ err = _create_skins(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 13 PARSE MESHES (we have enough info now) */
+ err = _parse_meshes(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 14 PARSE LIGHTS */
+ err = _parse_lights(state);
+ if (err != OK) {
+ return Error::FAILED;
+ }
+
+ /* STEP 15 PARSE CAMERAS */
+ err = _parse_cameras(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 16 PARSE ANIMATIONS */
+ err = _parse_animations(state);
+ if (err != OK)
+ return Error::FAILED;
+
+ /* STEP 17 ASSIGN SCENE NAMES */
+ _assign_scene_names(state);
+
+ return OK;
+}
+
+Dictionary GLTFDocument::_serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material) {
+ Dictionary extension;
+ Ref<BaseMaterial3D> mat = p_material;
+ if (mat.is_valid()) {
+ Dictionary texture_transform;
+ Array offset;
+ offset.resize(2);
+ offset[0] = mat->get_uv2_offset().x;
+ offset[1] = mat->get_uv2_offset().y;
+ texture_transform["offset"] = offset;
+ Array scale;
+ scale.resize(2);
+ scale[0] = mat->get_uv2_scale().x;
+ scale[1] = mat->get_uv2_scale().y;
+ texture_transform["scale"] = scale;
+ // Godot doesn't support texture rotation
+ extension["KHR_texture_transform"] = texture_transform;
+ }
+ return extension;
+}
+
+Dictionary GLTFDocument::_serialize_texture_transform_uv1(Ref<BaseMaterial3D> p_material) {
+ Dictionary extension;
+ if (p_material.is_valid()) {
+ Dictionary texture_transform;
+ Array offset;
+ offset.resize(2);
+ offset[0] = p_material->get_uv1_offset().x;
+ offset[1] = p_material->get_uv1_offset().y;
+ texture_transform["offset"] = offset;
+ Array scale;
+ scale.resize(2);
+ scale[0] = p_material->get_uv1_scale().x;
+ scale[1] = p_material->get_uv1_scale().y;
+ texture_transform["scale"] = scale;
+ // Godot doesn't support texture rotation
+ extension["KHR_texture_transform"] = texture_transform;
+ }
+ return extension;
+}
+
+Error GLTFDocument::_serialize_version(Ref<GLTFState> state) {
+ const String version = "2.0";
+ state->major_version = version.get_slice(".", 0).to_int();
+ state->minor_version = version.get_slice(".", 1).to_int();
+ Dictionary asset;
+ asset["version"] = version;
+
+ String hash = VERSION_HASH;
+ asset["generator"] = String(VERSION_FULL_NAME) + String("@") + (hash.length() == 0 ? String("unknown") : hash);
+ state->json["asset"] = asset;
+ ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
+ ERR_FAIL_COND_V(!state->json.has("asset"), Error::FAILED);
+ return OK;
+}
+
+Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) {
+ Error err = FAILED;
+ if (p_path.to_lower().ends_with("glb")) {
+ err = _encode_buffer_glb(state, p_path);
+ ERR_FAIL_COND_V(err != OK, err);
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE, &err);
+ ERR_FAIL_COND_V(!f, FAILED);
+
+ String json = JSON::print(state->json);
+
+ const uint32_t magic = 0x46546C67; // GLTF
+ const int32_t header_size = 12;
+ const int32_t chunk_header_size = 8;
+
+ for (int32_t pad_i = 0; pad_i < (chunk_header_size + json.utf8().length()) % 4; pad_i++) {
+ json += " ";
+ }
+ CharString cs = json.utf8();
+ const uint32_t text_chunk_length = cs.length();
+
+ const uint32_t text_chunk_type = 0x4E4F534A; //JSON
+ int32_t binary_data_length = 0;
+ if (state->buffers.size()) {
+ binary_data_length = state->buffers[0].size();
+ }
+ const int32_t binary_chunk_length = binary_data_length;
+ const int32_t binary_chunk_type = 0x004E4942; //BIN
+
+ f->create(FileAccess::ACCESS_RESOURCES);
+ f->store_32(magic);
+ f->store_32(state->major_version); // version
+ f->store_32(header_size + chunk_header_size + text_chunk_length + chunk_header_size + binary_data_length); // length
+ f->store_32(text_chunk_length);
+ f->store_32(text_chunk_type);
+ f->store_buffer((uint8_t *)&cs[0], cs.length());
+ if (binary_chunk_length) {
+ f->store_32(binary_chunk_length);
+ f->store_32(binary_chunk_type);
+ f->store_buffer(state->buffers[0].ptr(), binary_data_length);
+ }
+
+ f->close();
+ } else {
+ err = _encode_buffer_bins(state, p_path);
+ ERR_FAIL_COND_V(err != OK, err);
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE, &err);
+ ERR_FAIL_COND_V(!f, FAILED);
+
+ f->create(FileAccess::ACCESS_RESOURCES);
+ String json = JSON::print(state->json);
+ f->store_string(json);
+ f->close();
+ }
+ return err;
+}
diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h
new file mode 100644
index 0000000000..111324d1e6
--- /dev/null
+++ b/modules/gltf/gltf_document.h
@@ -0,0 +1,428 @@
+/*************************************************************************/
+/* gltf_document.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_DOCUMENT_H
+#define GLTF_DOCUMENT_H
+
+#include "editor/import/resource_importer_scene.h"
+#include "editor/import/scene_importer_mesh_node_3d.h"
+#include "gltf_animation.h"
+#include "scene/2d/node_2d.h"
+#include "scene/3d/bone_attachment_3d.h"
+#include "scene/3d/light_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/3d/skeleton_3d.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/material.h"
+#include "scene/resources/texture.h"
+
+class GLTFState;
+class GLTFSkin;
+class GLTFNode;
+class GLTFSpecGloss;
+class GLTFSkeleton;
+
+using GLTFAccessorIndex = int;
+using GLTFAnimationIndex = int;
+using GLTFBufferIndex = int;
+using GLTFBufferViewIndex = int;
+using GLTFCameraIndex = int;
+using GLTFImageIndex = int;
+using GLTFMaterialIndex = int;
+using GLTFMeshIndex = int;
+using GLTFLightIndex = int;
+using GLTFNodeIndex = int;
+using GLTFSkeletonIndex = int;
+using GLTFSkinIndex = int;
+using GLTFTextureIndex = int;
+
+class GLTFDocument : public Resource {
+ GDCLASS(GLTFDocument, Resource);
+ friend class GLTFState;
+ friend class GLTFSkin;
+ friend class GLTFSkeleton;
+
+public:
+ const int32_t JOINT_GROUP_SIZE = 4;
+ enum GLTFType {
+ TYPE_SCALAR,
+ TYPE_VEC2,
+ TYPE_VEC3,
+ TYPE_VEC4,
+ TYPE_MAT2,
+ TYPE_MAT3,
+ TYPE_MAT4,
+ };
+
+ enum {
+ ARRAY_BUFFER = 34962,
+ ELEMENT_ARRAY_BUFFER = 34963,
+
+ TYPE_BYTE = 5120,
+ TYPE_UNSIGNED_BYTE = 5121,
+ TYPE_SHORT = 5122,
+ TYPE_UNSIGNED_SHORT = 5123,
+ TYPE_UNSIGNED_INT = 5125,
+ TYPE_FLOAT = 5126,
+
+ COMPONENT_TYPE_BYTE = 5120,
+ COMPONENT_TYPE_UNSIGNED_BYTE = 5121,
+ COMPONENT_TYPE_SHORT = 5122,
+ COMPONENT_TYPE_UNSIGNED_SHORT = 5123,
+ COMPONENT_TYPE_INT = 5125,
+ COMPONENT_TYPE_FLOAT = 5126,
+ };
+
+private:
+ template <class T>
+ static Array to_array(const Vector<T> &p_inp) {
+ Array ret;
+ for (int i = 0; i < p_inp.size(); i++) {
+ ret.push_back(p_inp[i]);
+ }
+ return ret;
+ }
+
+ template <class T>
+ static Array to_array(const Set<T> &p_inp) {
+ Array ret;
+ typename Set<T>::Element *elem = p_inp.front();
+ while (elem) {
+ ret.push_back(elem->get());
+ elem = elem->next();
+ }
+ return ret;
+ }
+
+ template <class T>
+ static void set_from_array(Vector<T> &r_out, const Array &p_inp) {
+ r_out.clear();
+ for (int i = 0; i < p_inp.size(); i++) {
+ r_out.push_back(p_inp[i]);
+ }
+ }
+
+ template <class T>
+ static void set_from_array(Set<T> &r_out, const Array &p_inp) {
+ r_out.clear();
+ for (int i = 0; i < p_inp.size(); i++) {
+ r_out.insert(p_inp[i]);
+ }
+ }
+ template <class K, class V>
+ static Dictionary to_dict(const Map<K, V> &p_inp) {
+ Dictionary ret;
+ for (typename Map<K, V>::Element *E = p_inp.front(); E; E = E->next()) {
+ ret[E->key()] = E->value();
+ }
+ return ret;
+ }
+
+ template <class K, class V>
+ static void set_from_dict(Map<K, V> &r_out, const Dictionary &p_inp) {
+ r_out.clear();
+ Array keys = p_inp.keys();
+ for (int i = 0; i < keys.size(); i++) {
+ r_out[keys[i]] = p_inp[keys[i]];
+ }
+ }
+ double _filter_number(double p_float);
+ String _get_component_type_name(const uint32_t p_component);
+ int _get_component_type_size(const int component_type);
+ Error _parse_scenes(Ref<GLTFState> state);
+ Error _parse_nodes(Ref<GLTFState> state);
+ String _get_type_name(const GLTFType p_component);
+ String _get_accessor_type_name(const GLTFDocument::GLTFType p_type);
+ String _sanitize_scene_name(const String &name);
+ String _gen_unique_name(Ref<GLTFState> state, const String &p_name);
+ String _sanitize_bone_name(const String &name);
+ String _gen_unique_bone_name(Ref<GLTFState> state,
+ const GLTFSkeletonIndex skel_i,
+ const String &p_name);
+ GLTFTextureIndex _set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture);
+ Ref<Texture2D> _get_texture(Ref<GLTFState> state,
+ const GLTFTextureIndex p_texture);
+ Error _parse_json(const String &p_path, Ref<GLTFState> state);
+ Error _parse_glb(const String &p_path, Ref<GLTFState> state);
+ void _compute_node_heights(Ref<GLTFState> state);
+ Error _parse_buffers(Ref<GLTFState> state, const String &p_base_path);
+ Error _parse_buffer_views(Ref<GLTFState> state);
+ GLTFType _get_type_from_str(const String &p_string);
+ Error _parse_accessors(Ref<GLTFState> state);
+ Error _decode_buffer_view(Ref<GLTFState> state, double *dst,
+ const GLTFBufferViewIndex p_buffer_view,
+ const int skip_every, const int skip_bytes,
+ const int element_size, const int count,
+ const GLTFType type, const int component_count,
+ const int component_type, const int component_size,
+ const bool normalized, const int byte_offset,
+ const bool for_vertex);
+ Vector<double> _decode_accessor(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<float> _decode_accessor_as_floats(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<int> _decode_accessor_as_ints(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Vector2> _decode_accessor_as_vec2(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Vector3> _decode_accessor_as_vec3(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Color> _decode_accessor_as_color(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Quat> _decode_accessor_as_quat(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Transform2D> _decode_accessor_as_xform2d(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Basis> _decode_accessor_as_basis(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Vector<Transform> _decode_accessor_as_xform(Ref<GLTFState> state,
+ const GLTFAccessorIndex p_accessor,
+ const bool p_for_vertex);
+ Error _parse_meshes(Ref<GLTFState> state);
+ Error _serialize_textures(Ref<GLTFState> state);
+ Error _serialize_images(Ref<GLTFState> state, const String &p_path);
+ Error _serialize_lights(Ref<GLTFState> state);
+ Error _parse_images(Ref<GLTFState> state, const String &p_base_path);
+ Error _parse_textures(Ref<GLTFState> state);
+ Error _parse_materials(Ref<GLTFState> state);
+ void _set_texture_transform_uv1(const Dictionary &d, Ref<BaseMaterial3D> material);
+ void spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss,
+ Ref<BaseMaterial3D> p_material);
+ static void spec_gloss_to_metal_base_color(const Color &p_specular_factor,
+ const Color &p_diffuse,
+ Color &r_base_color,
+ float &r_metallic);
+ GLTFNodeIndex _find_highest_node(Ref<GLTFState> state,
+ const Vector<GLTFNodeIndex> &subset);
+ bool _capture_nodes_in_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin,
+ const GLTFNodeIndex node_index);
+ void _capture_nodes_for_multirooted_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin);
+ Error _expand_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin);
+ Error _verify_skin(Ref<GLTFState> state, Ref<GLTFSkin> skin);
+ Error _parse_skins(Ref<GLTFState> state);
+ Error _determine_skeletons(Ref<GLTFState> state);
+ Error _reparent_non_joint_skeleton_subtrees(
+ Ref<GLTFState> state, Ref<GLTFSkeleton> skeleton,
+ const Vector<GLTFNodeIndex> &non_joints);
+ Error _reparent_to_fake_joint(Ref<GLTFState> state, Ref<GLTFSkeleton> skeleton,
+ const GLTFNodeIndex node_index);
+ Error _determine_skeleton_roots(Ref<GLTFState> state,
+ const GLTFSkeletonIndex skel_i);
+ Error _create_skeletons(Ref<GLTFState> state);
+ Error _map_skin_joints_indices_to_skeleton_bone_indices(Ref<GLTFState> state);
+ Error _serialize_skins(Ref<GLTFState> state);
+ Error _create_skins(Ref<GLTFState> state);
+ bool _skins_are_same(const Ref<Skin> skin_a, const Ref<Skin> skin_b);
+ void _remove_duplicate_skins(Ref<GLTFState> state);
+ Error _serialize_cameras(Ref<GLTFState> state);
+ Error _parse_cameras(Ref<GLTFState> state);
+ Error _parse_lights(Ref<GLTFState> state);
+ Error _parse_animations(Ref<GLTFState> state);
+ Error _serialize_animations(Ref<GLTFState> state);
+ BoneAttachment3D *_generate_bone_attachment(Ref<GLTFState> state,
+ Skeleton3D *skeleton,
+ const GLTFNodeIndex node_index);
+ EditorSceneImporterMeshNode3D *_generate_mesh_instance(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index);
+ Camera3D *_generate_camera(Ref<GLTFState> state, Node *scene_parent,
+ const GLTFNodeIndex node_index);
+ Light3D *_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index);
+ Node3D *_generate_spatial(Ref<GLTFState> state, Node *scene_parent,
+ const GLTFNodeIndex node_index);
+ void _assign_scene_names(Ref<GLTFState> state);
+ template <class T>
+ T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values,
+ const float p_time,
+ const GLTFAnimation::Interpolation p_interp);
+ GLTFAccessorIndex _encode_accessor_as_quats(Ref<GLTFState> state,
+ const Vector<Quat> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_weights(Ref<GLTFState> state,
+ const Vector<Color> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_joints(Ref<GLTFState> state,
+ const Vector<Color> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_floats(Ref<GLTFState> state,
+ const Vector<real_t> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_vec2(Ref<GLTFState> state,
+ const Vector<Vector2> p_attribs,
+ const bool p_for_vertex);
+
+ void _calc_accessor_vec2_min_max(int i, const int element_count, Vector<double> &type_max, Vector2 attribs, Vector<double> &type_min) {
+ if (i == 0) {
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = attribs[(i * element_count) + type_i];
+ type_min.write[type_i] = attribs[(i * element_count) + type_i];
+ }
+ }
+ for (int32_t type_i = 0; type_i < element_count; type_i++) {
+ type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
+ type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
+ type_max.write[type_i] = _filter_number(type_max.write[type_i]);
+ type_min.write[type_i] = _filter_number(type_min.write[type_i]);
+ }
+ }
+
+ GLTFAccessorIndex _encode_accessor_as_vec3(Ref<GLTFState> state,
+ const Vector<Vector3> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_color(Ref<GLTFState> state,
+ const Vector<Color> p_attribs,
+ const bool p_for_vertex);
+
+ void _calc_accessor_min_max(int p_i, const int p_element_count, Vector<double> &p_type_max, Vector<double> p_attribs, Vector<double> &p_type_min);
+
+ GLTFAccessorIndex _encode_accessor_as_ints(Ref<GLTFState> state,
+ const Vector<int32_t> p_attribs,
+ const bool p_for_vertex);
+ GLTFAccessorIndex _encode_accessor_as_xform(Ref<GLTFState> state,
+ const Vector<Transform> p_attribs,
+ const bool p_for_vertex);
+ Error _encode_buffer_view(Ref<GLTFState> state, const double *src,
+ const int count, const GLTFType type,
+ const int component_type, const bool normalized,
+ const int byte_offset, const bool for_vertex,
+ GLTFBufferViewIndex &r_accessor);
+ Error _encode_accessors(Ref<GLTFState> state);
+ Error _encode_buffer_views(Ref<GLTFState> state);
+ Error _serialize_materials(Ref<GLTFState> state);
+ Error _serialize_meshes(Ref<GLTFState> state);
+ Error _serialize_nodes(Ref<GLTFState> state);
+ Error _serialize_scenes(Ref<GLTFState> state);
+ String interpolation_to_string(const GLTFAnimation::Interpolation p_interp);
+ GLTFAnimation::Track _convert_animation_track(Ref<GLTFState> state,
+ GLTFAnimation::Track p_track,
+ Ref<Animation> p_animation, Transform p_bone_rest,
+ int32_t p_track_i,
+ GLTFNodeIndex p_node_i);
+ Error _encode_buffer_bins(Ref<GLTFState> state, const String &p_path);
+ Error _encode_buffer_glb(Ref<GLTFState> state, const String &p_path);
+ Error _serialize_bone_attachment(Ref<GLTFState> state);
+ Dictionary _serialize_texture_transform_uv1(Ref<BaseMaterial3D> p_material);
+ Dictionary _serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material);
+ Error _serialize_version(Ref<GLTFState> state);
+ Error _serialize_file(Ref<GLTFState> state, const String p_path);
+ Error _serialize_extensions(Ref<GLTFState> state) const;
+
+public:
+ // http://www.itu.int/rec/R-REC-BT.601
+ // http://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.601-7-201103-I!!PDF-E.pdf
+ static constexpr float R_BRIGHTNESS_COEFF = 0.299f;
+ static constexpr float G_BRIGHTNESS_COEFF = 0.587f;
+ static constexpr float B_BRIGHTNESS_COEFF = 0.114f;
+
+private:
+ // https://github.com/microsoft/glTF-SDK/blob/master/GLTFSDK/Source/PBRUtils.cpp#L9
+ // https://bghgary.github.io/glTF/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
+ static float solve_metallic(float p_dielectric_specular, float diffuse,
+ float specular,
+ float p_one_minus_specular_strength);
+ static float get_perceived_brightness(const Color p_color);
+ static float get_max_component(const Color &p_color);
+
+public:
+ void _process_mesh_instances(Ref<GLTFState> state, Node *scene_root);
+ void _generate_scene_node(Ref<GLTFState> state, Node *scene_parent,
+ Node3D *scene_root,
+ const GLTFNodeIndex node_index);
+ void _import_animation(Ref<GLTFState> state, AnimationPlayer *ap,
+ const GLTFAnimationIndex index, const int bake_fps);
+ GLTFMeshIndex _convert_mesh_instance(Ref<GLTFState> state,
+ MeshInstance3D *p_mesh_instance);
+ void _convert_mesh_instances(Ref<GLTFState> state);
+ GLTFCameraIndex _convert_camera(Ref<GLTFState> state, Camera3D *p_camera);
+ void _convert_light_to_gltf(Light3D *light, Ref<GLTFState> state, Node3D *spatial, Ref<GLTFNode> gltf_node);
+ GLTFLightIndex _convert_light(Ref<GLTFState> state, Light3D *p_light);
+ GLTFSkeletonIndex _convert_skeleton(Ref<GLTFState> state, Skeleton3D *p_skeleton);
+ void _convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref<GLTFNode> p_node);
+ void _convert_scene_node(Ref<GLTFState> state, Node *p_current, Node *p_root,
+ const GLTFNodeIndex p_gltf_current,
+ const GLTFNodeIndex p_gltf_root);
+
+ void _convert_csg_shape_to_gltf(Node *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> gltf_node, Ref<GLTFState> state);
+
+ void _create_gltf_node(Ref<GLTFState> state,
+ Node *p_scene_parent,
+ GLTFNodeIndex current_node_i,
+ GLTFNodeIndex p_parent_node_index,
+ GLTFNodeIndex p_root_gltf_node,
+ Ref<GLTFNode> gltf_node);
+ void _convert_animation_player_to_gltf(
+ AnimationPlayer *animation_player, Ref<GLTFState> state,
+ const GLTFNodeIndex &p_gltf_current,
+ const GLTFNodeIndex &p_gltf_root_index,
+ Ref<GLTFNode> p_gltf_node, Node *p_scene_parent,
+ Node *p_root);
+ void _check_visibility(Node *p_node, bool &retflag);
+ void _convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> state,
+ Node3D *spatial,
+ Ref<GLTFNode> gltf_node);
+ void _convert_grid_map_to_gltf(
+ Node *p_scene_parent,
+ const GLTFNodeIndex &p_parent_node_index,
+ const GLTFNodeIndex &p_root_node_index,
+ Ref<GLTFNode> gltf_node, Ref<GLTFState> state,
+ Node *p_root_node);
+ void _convert_mult_mesh_instance_to_gltf(
+ Node *p_scene_parent,
+ const GLTFNodeIndex &p_parent_node_index,
+ const GLTFNodeIndex &p_root_node_index,
+ Ref<GLTFNode> gltf_node, Ref<GLTFState> state,
+ Node *p_root_node);
+ void _convert_skeleton_to_gltf(
+ Node *p_scene_parent, Ref<GLTFState> state,
+ const GLTFNodeIndex &p_parent_node_index,
+ const GLTFNodeIndex &p_root_node_index,
+ Ref<GLTFNode> gltf_node, Node *p_root_node);
+ void _convert_bone_attachment_to_gltf(Node *p_scene_parent,
+ Ref<GLTFState> state,
+ Ref<GLTFNode> gltf_node,
+ bool &retflag);
+ void _convert_mesh_to_gltf(Node *p_scene_parent,
+ Ref<GLTFState> state, Node3D *spatial,
+ Ref<GLTFNode> gltf_node);
+ void _convert_animation(Ref<GLTFState> state, AnimationPlayer *ap,
+ String p_animation_track_name);
+ Error serialize(Ref<GLTFState> state, Node *p_root, const String &p_path);
+ Error parse(Ref<GLTFState> state, String p_paths, bool p_read_binary = false);
+};
+
+#endif // GLTF_DOCUMENT_H
diff --git a/modules/gltf/gltf_light.cpp b/modules/gltf/gltf_light.cpp
new file mode 100644
index 0000000000..95cca9cf71
--- /dev/null
+++ b/modules/gltf/gltf_light.cpp
@@ -0,0 +1,101 @@
+/*************************************************************************/
+/* gltf_light.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_light.h"
+
+void GLTFLight::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_color"), &GLTFLight::get_color);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &GLTFLight::set_color);
+ ClassDB::bind_method(D_METHOD("get_intensity"), &GLTFLight::get_intensity);
+ ClassDB::bind_method(D_METHOD("set_intensity", "intensity"), &GLTFLight::set_intensity);
+ ClassDB::bind_method(D_METHOD("get_type"), &GLTFLight::get_type);
+ ClassDB::bind_method(D_METHOD("set_type", "type"), &GLTFLight::set_type);
+ ClassDB::bind_method(D_METHOD("get_range"), &GLTFLight::get_range);
+ ClassDB::bind_method(D_METHOD("set_range", "range"), &GLTFLight::set_range);
+ ClassDB::bind_method(D_METHOD("get_inner_cone_angle"), &GLTFLight::get_inner_cone_angle);
+ ClassDB::bind_method(D_METHOD("set_inner_cone_angle", "inner_cone_angle"), &GLTFLight::set_inner_cone_angle);
+ ClassDB::bind_method(D_METHOD("get_outer_cone_angle"), &GLTFLight::get_outer_cone_angle);
+ ClassDB::bind_method(D_METHOD("set_outer_cone_angle", "outer_cone_angle"), &GLTFLight::set_outer_cone_angle);
+
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); // Color
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "intensity"), "set_intensity", "get_intensity"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "type"), "set_type", "get_type"); // String
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "range"), "set_range", "get_range"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "inner_cone_angle"), "set_inner_cone_angle", "get_inner_cone_angle"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "outer_cone_angle"), "set_outer_cone_angle", "get_outer_cone_angle"); // float
+}
+
+Color GLTFLight::get_color() {
+ return color;
+}
+
+void GLTFLight::set_color(Color p_color) {
+ color = p_color;
+}
+
+float GLTFLight::get_intensity() {
+ return intensity;
+}
+
+void GLTFLight::set_intensity(float p_intensity) {
+ intensity = p_intensity;
+}
+
+String GLTFLight::get_type() {
+ return type;
+}
+
+void GLTFLight::set_type(String p_type) {
+ type = p_type;
+}
+
+float GLTFLight::get_range() {
+ return range;
+}
+
+void GLTFLight::set_range(float p_range) {
+ range = p_range;
+}
+
+float GLTFLight::get_inner_cone_angle() {
+ return inner_cone_angle;
+}
+
+void GLTFLight::set_inner_cone_angle(float p_inner_cone_angle) {
+ inner_cone_angle = p_inner_cone_angle;
+}
+
+float GLTFLight::get_outer_cone_angle() {
+ return outer_cone_angle;
+}
+
+void GLTFLight::set_outer_cone_angle(float p_outer_cone_angle) {
+ outer_cone_angle = p_outer_cone_angle;
+}
diff --git a/modules/gltf/gltf_light.h b/modules/gltf/gltf_light.h
new file mode 100644
index 0000000000..a859ca1833
--- /dev/null
+++ b/modules/gltf/gltf_light.h
@@ -0,0 +1,72 @@
+/*************************************************************************/
+/* gltf_light.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_LIGHT_H
+#define GLTF_LIGHT_H
+
+#include "core/config/engine.h"
+#include "core/io/resource.h"
+
+class GLTFLight : public Resource {
+ GDCLASS(GLTFLight, Resource)
+ friend class GLTFDocument;
+
+protected:
+ static void _bind_methods();
+
+private:
+ Color color;
+ float intensity = 0.0f;
+ String type;
+ float range = 0.0f;
+ float inner_cone_angle = 0.0f;
+ float outer_cone_angle = 0.0f;
+
+public:
+ Color get_color();
+ void set_color(Color p_color);
+
+ float get_intensity();
+ void set_intensity(float p_intensity);
+
+ String get_type();
+ void set_type(String p_type);
+
+ float get_range();
+ void set_range(float p_range);
+
+ float get_inner_cone_angle();
+ void set_inner_cone_angle(float p_inner_cone_angle);
+
+ float get_outer_cone_angle();
+ void set_outer_cone_angle(float p_outer_cone_angle);
+};
+
+#endif // GLTF_LIGHT_H
diff --git a/modules/gltf/gltf_mesh.cpp b/modules/gltf/gltf_mesh.cpp
new file mode 100644
index 0000000000..8c10e42c89
--- /dev/null
+++ b/modules/gltf/gltf_mesh.cpp
@@ -0,0 +1,58 @@
+/*************************************************************************/
+/* gltf_mesh.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_mesh.h"
+#include "editor/import/scene_importer_mesh.h"
+
+void GLTFMesh::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_mesh"), &GLTFMesh::get_mesh);
+ ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &GLTFMesh::set_mesh);
+ ClassDB::bind_method(D_METHOD("get_blend_weights"), &GLTFMesh::get_blend_weights);
+ ClassDB::bind_method(D_METHOD("set_blend_weights", "blend_weights"), &GLTFMesh::set_blend_weights);
+
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh"), "set_mesh", "get_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_FLOAT32_ARRAY, "blend_weights"), "set_blend_weights", "get_blend_weights"); // Vector<float>
+}
+
+Ref<EditorSceneImporterMesh> GLTFMesh::get_mesh() {
+ return mesh;
+}
+
+void GLTFMesh::set_mesh(Ref<EditorSceneImporterMesh> p_mesh) {
+ mesh = p_mesh;
+}
+
+Vector<float> GLTFMesh::get_blend_weights() {
+ return blend_weights;
+}
+
+void GLTFMesh::set_blend_weights(Vector<float> p_blend_weights) {
+ blend_weights = p_blend_weights;
+}
diff --git a/modules/gltf/gltf_mesh.h b/modules/gltf/gltf_mesh.h
new file mode 100644
index 0000000000..0fc750fc9f
--- /dev/null
+++ b/modules/gltf/gltf_mesh.h
@@ -0,0 +1,55 @@
+/*************************************************************************/
+/* gltf_mesh.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_MESH_H
+#define GLTF_MESH_H
+
+#include "core/io/resource.h"
+#include "editor/import/resource_importer_scene.h"
+#include "editor/import/scene_importer_mesh.h"
+#include "scene/resources/mesh.h"
+
+class GLTFMesh : public Resource {
+ GDCLASS(GLTFMesh, Resource);
+
+private:
+ Ref<EditorSceneImporterMesh> mesh;
+ Vector<float> blend_weights;
+
+protected:
+ static void _bind_methods();
+
+public:
+ Ref<EditorSceneImporterMesh> get_mesh();
+ void set_mesh(Ref<EditorSceneImporterMesh> p_mesh);
+ Vector<float> get_blend_weights();
+ void set_blend_weights(Vector<float> p_blend_weights);
+};
+#endif // GLTF_MESH_H
diff --git a/modules/gltf/gltf_node.cpp b/modules/gltf/gltf_node.cpp
new file mode 100644
index 0000000000..777c6fbd9a
--- /dev/null
+++ b/modules/gltf/gltf_node.cpp
@@ -0,0 +1,189 @@
+/*************************************************************************/
+/* gltf_node.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_node.h"
+
+void GLTFNode::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_parent"), &GLTFNode::get_parent);
+ ClassDB::bind_method(D_METHOD("set_parent", "parent"), &GLTFNode::set_parent);
+ ClassDB::bind_method(D_METHOD("get_height"), &GLTFNode::get_height);
+ ClassDB::bind_method(D_METHOD("set_height", "height"), &GLTFNode::set_height);
+ ClassDB::bind_method(D_METHOD("get_xform"), &GLTFNode::get_xform);
+ ClassDB::bind_method(D_METHOD("set_xform", "xform"), &GLTFNode::set_xform);
+ ClassDB::bind_method(D_METHOD("get_mesh"), &GLTFNode::get_mesh);
+ ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &GLTFNode::set_mesh);
+ ClassDB::bind_method(D_METHOD("get_camera"), &GLTFNode::get_camera);
+ ClassDB::bind_method(D_METHOD("set_camera", "camera"), &GLTFNode::set_camera);
+ ClassDB::bind_method(D_METHOD("get_skin"), &GLTFNode::get_skin);
+ ClassDB::bind_method(D_METHOD("set_skin", "skin"), &GLTFNode::set_skin);
+ ClassDB::bind_method(D_METHOD("get_skeleton"), &GLTFNode::get_skeleton);
+ ClassDB::bind_method(D_METHOD("set_skeleton", "skeleton"), &GLTFNode::set_skeleton);
+ ClassDB::bind_method(D_METHOD("get_joint"), &GLTFNode::get_joint);
+ ClassDB::bind_method(D_METHOD("set_joint", "joint"), &GLTFNode::set_joint);
+ ClassDB::bind_method(D_METHOD("get_translation"), &GLTFNode::get_translation);
+ ClassDB::bind_method(D_METHOD("set_translation", "translation"), &GLTFNode::set_translation);
+ ClassDB::bind_method(D_METHOD("get_rotation"), &GLTFNode::get_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation", "rotation"), &GLTFNode::set_rotation);
+ ClassDB::bind_method(D_METHOD("get_scale"), &GLTFNode::get_scale);
+ ClassDB::bind_method(D_METHOD("set_scale", "scale"), &GLTFNode::set_scale);
+ ClassDB::bind_method(D_METHOD("get_children"), &GLTFNode::get_children);
+ ClassDB::bind_method(D_METHOD("set_children", "children"), &GLTFNode::set_children);
+ ClassDB::bind_method(D_METHOD("get_fake_joint_parent"), &GLTFNode::get_fake_joint_parent);
+ ClassDB::bind_method(D_METHOD("set_fake_joint_parent", "fake_joint_parent"), &GLTFNode::set_fake_joint_parent);
+ ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light);
+ ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "parent"), "set_parent", "get_parent"); // GLTFNodeIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "height"), "set_height", "get_height"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "xform"), "set_xform", "get_xform"); // Transform
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mesh"), "set_mesh", "get_mesh"); // GLTFMeshIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "camera"), "set_camera", "get_camera"); // GLTFCameraIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "skin"), "set_skin", "get_skin"); // GLTFSkinIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "skeleton"), "set_skeleton", "get_skeleton"); // GLTFSkeletonIndex
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "joint"), "set_joint", "get_joint"); // bool
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation"), "set_translation", "get_translation"); // Vector3
+ ADD_PROPERTY(PropertyInfo(Variant::QUAT, "rotation"), "set_rotation", "get_rotation"); // Quat
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale"), "set_scale", "get_scale"); // Vector3
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "children"), "set_children", "get_children"); // Vector<int>
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "fake_joint_parent"), "set_fake_joint_parent", "get_fake_joint_parent"); // GLTFNodeIndex
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "light"), "set_light", "get_light"); // GLTFLightIndex
+}
+
+GLTFNodeIndex GLTFNode::get_parent() {
+ return parent;
+}
+
+void GLTFNode::set_parent(GLTFNodeIndex p_parent) {
+ parent = p_parent;
+}
+
+int GLTFNode::get_height() {
+ return height;
+}
+
+void GLTFNode::set_height(int p_height) {
+ height = p_height;
+}
+
+Transform GLTFNode::get_xform() {
+ return xform;
+}
+
+void GLTFNode::set_xform(Transform p_xform) {
+ xform = p_xform;
+}
+
+GLTFMeshIndex GLTFNode::get_mesh() {
+ return mesh;
+}
+
+void GLTFNode::set_mesh(GLTFMeshIndex p_mesh) {
+ mesh = p_mesh;
+}
+
+GLTFCameraIndex GLTFNode::get_camera() {
+ return camera;
+}
+
+void GLTFNode::set_camera(GLTFCameraIndex p_camera) {
+ camera = p_camera;
+}
+
+GLTFSkinIndex GLTFNode::get_skin() {
+ return skin;
+}
+
+void GLTFNode::set_skin(GLTFSkinIndex p_skin) {
+ skin = p_skin;
+}
+
+GLTFSkeletonIndex GLTFNode::get_skeleton() {
+ return skeleton;
+}
+
+void GLTFNode::set_skeleton(GLTFSkeletonIndex p_skeleton) {
+ skeleton = p_skeleton;
+}
+
+bool GLTFNode::get_joint() {
+ return joint;
+}
+
+void GLTFNode::set_joint(bool p_joint) {
+ joint = p_joint;
+}
+
+Vector3 GLTFNode::get_translation() {
+ return translation;
+}
+
+void GLTFNode::set_translation(Vector3 p_translation) {
+ translation = p_translation;
+}
+
+Quat GLTFNode::get_rotation() {
+ return rotation;
+}
+
+void GLTFNode::set_rotation(Quat p_rotation) {
+ rotation = p_rotation;
+}
+
+Vector3 GLTFNode::get_scale() {
+ return scale;
+}
+
+void GLTFNode::set_scale(Vector3 p_scale) {
+ scale = p_scale;
+}
+
+Vector<int> GLTFNode::get_children() {
+ return children;
+}
+
+void GLTFNode::set_children(Vector<int> p_children) {
+ children = p_children;
+}
+
+GLTFNodeIndex GLTFNode::get_fake_joint_parent() {
+ return fake_joint_parent;
+}
+
+void GLTFNode::set_fake_joint_parent(GLTFNodeIndex p_fake_joint_parent) {
+ fake_joint_parent = p_fake_joint_parent;
+}
+
+GLTFLightIndex GLTFNode::get_light() {
+ return light;
+}
+
+void GLTFNode::set_light(GLTFLightIndex p_light) {
+ light = p_light;
+}
diff --git a/modules/gltf/gltf_node.h b/modules/gltf/gltf_node.h
new file mode 100644
index 0000000000..ce8aff8944
--- /dev/null
+++ b/modules/gltf/gltf_node.h
@@ -0,0 +1,105 @@
+/*************************************************************************/
+/* gltf_node.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_NODE_H
+#define GLTF_NODE_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+class GLTFNode : public Resource {
+ GDCLASS(GLTFNode, Resource);
+ friend class GLTFDocument;
+ friend class PackedSceneGLTF;
+
+private:
+ // matrices need to be transformed to this
+ GLTFNodeIndex parent = -1;
+ int height = -1;
+ Transform xform;
+ GLTFMeshIndex mesh = -1;
+ GLTFCameraIndex camera = -1;
+ GLTFSkinIndex skin = -1;
+ GLTFSkeletonIndex skeleton = -1;
+ bool joint = false;
+ Vector3 translation;
+ Quat rotation;
+ Vector3 scale = Vector3(1, 1, 1);
+ Vector<int> children;
+ GLTFNodeIndex fake_joint_parent = -1;
+ GLTFLightIndex light = -1;
+
+protected:
+ static void _bind_methods();
+
+public:
+ GLTFNodeIndex get_parent();
+ void set_parent(GLTFNodeIndex p_parent);
+
+ int get_height();
+ void set_height(int p_height);
+
+ Transform get_xform();
+ void set_xform(Transform p_xform);
+
+ GLTFMeshIndex get_mesh();
+ void set_mesh(GLTFMeshIndex p_mesh);
+
+ GLTFCameraIndex get_camera();
+ void set_camera(GLTFCameraIndex p_camera);
+
+ GLTFSkinIndex get_skin();
+ void set_skin(GLTFSkinIndex p_skin);
+
+ GLTFSkeletonIndex get_skeleton();
+ void set_skeleton(GLTFSkeletonIndex p_skeleton);
+
+ bool get_joint();
+ void set_joint(bool p_joint);
+
+ Vector3 get_translation();
+ void set_translation(Vector3 p_translation);
+
+ Quat get_rotation();
+ void set_rotation(Quat p_rotation);
+
+ Vector3 get_scale();
+ void set_scale(Vector3 p_scale);
+
+ Vector<int> get_children();
+ void set_children(Vector<int> p_children);
+
+ GLTFNodeIndex get_fake_joint_parent();
+ void set_fake_joint_parent(GLTFNodeIndex p_fake_joint_parent);
+
+ GLTFLightIndex get_light();
+ void set_light(GLTFLightIndex p_light);
+};
+#endif // GLTF_NODE_H
diff --git a/modules/gltf/gltf_skeleton.cpp b/modules/gltf/gltf_skeleton.cpp
new file mode 100644
index 0000000000..739779d3bd
--- /dev/null
+++ b/modules/gltf/gltf_skeleton.cpp
@@ -0,0 +1,95 @@
+/*************************************************************************/
+/* gltf_skeleton.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_skeleton.h"
+
+void GLTFSkeleton::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_joints"), &GLTFSkeleton::get_joints);
+ ClassDB::bind_method(D_METHOD("set_joints", "joints"), &GLTFSkeleton::set_joints);
+ ClassDB::bind_method(D_METHOD("get_roots"), &GLTFSkeleton::get_roots);
+ ClassDB::bind_method(D_METHOD("set_roots", "roots"), &GLTFSkeleton::set_roots);
+ ClassDB::bind_method(D_METHOD("get_godot_skeleton"), &GLTFSkeleton::get_godot_skeleton);
+ ClassDB::bind_method(D_METHOD("get_unique_names"), &GLTFSkeleton::get_unique_names);
+ ClassDB::bind_method(D_METHOD("set_unique_names", "unique_names"), &GLTFSkeleton::set_unique_names);
+ ClassDB::bind_method(D_METHOD("get_godot_bone_node"), &GLTFSkeleton::get_godot_bone_node);
+ ClassDB::bind_method(D_METHOD("set_godot_bone_node", "godot_bone_node"), &GLTFSkeleton::set_godot_bone_node);
+ ClassDB::bind_method(D_METHOD("get_bone_attachment_count"), &GLTFSkeleton::get_bone_attachment_count);
+ ClassDB::bind_method(D_METHOD("get_bone_attachment"), &GLTFSkeleton::get_bone_attachment);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "joints"), "set_joints", "get_joints"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "roots"), "set_roots", "get_roots"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "unique_names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_unique_names", "get_unique_names"); // Set<String>
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "godot_bone_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_godot_bone_node", "get_godot_bone_node"); // Map<int32_t,
+}
+
+Vector<GLTFNodeIndex> GLTFSkeleton::get_joints() {
+ return joints;
+}
+
+void GLTFSkeleton::set_joints(Vector<GLTFNodeIndex> p_joints) {
+ joints = p_joints;
+}
+
+Vector<GLTFNodeIndex> GLTFSkeleton::get_roots() {
+ return roots;
+}
+
+void GLTFSkeleton::set_roots(Vector<GLTFNodeIndex> p_roots) {
+ roots = p_roots;
+}
+
+Skeleton3D *GLTFSkeleton::get_godot_skeleton() {
+ return godot_skeleton;
+}
+
+Array GLTFSkeleton::get_unique_names() {
+ return GLTFDocument::to_array(unique_names);
+}
+
+void GLTFSkeleton::set_unique_names(Array p_unique_names) {
+ GLTFDocument::set_from_array(unique_names, p_unique_names);
+}
+
+Dictionary GLTFSkeleton::get_godot_bone_node() {
+ return GLTFDocument::to_dict(godot_bone_node);
+}
+
+void GLTFSkeleton::set_godot_bone_node(Dictionary p_indict) {
+ GLTFDocument::set_from_dict(godot_bone_node, p_indict);
+}
+
+BoneAttachment3D *GLTFSkeleton::get_bone_attachment(int idx) {
+ ERR_FAIL_INDEX_V(idx, bone_attachments.size(), nullptr);
+ return bone_attachments[idx];
+}
+
+int32_t GLTFSkeleton::get_bone_attachment_count() {
+ return bone_attachments.size();
+}
diff --git a/modules/gltf/gltf_skeleton.h b/modules/gltf/gltf_skeleton.h
new file mode 100644
index 0000000000..d6986eb35a
--- /dev/null
+++ b/modules/gltf/gltf_skeleton.h
@@ -0,0 +1,101 @@
+/*************************************************************************/
+/* gltf_skeleton.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_SKELETON_H
+#define GLTF_SKELETON_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+class GLTFSkeleton : public Resource {
+ GDCLASS(GLTFSkeleton, Resource);
+ friend class GLTFDocument;
+
+private:
+ // The *synthesized* skeletons joints
+ Vector<GLTFNodeIndex> joints;
+
+ // The roots of the skeleton. If there are multiple, each root must have the
+ // same parent (ie roots are siblings)
+ Vector<GLTFNodeIndex> roots;
+
+ // The created Skeleton3D for the scene
+ Skeleton3D *godot_skeleton = nullptr;
+
+ // Set of unique bone names for the skeleton
+ Set<String> unique_names;
+
+ Map<int32_t, GLTFNodeIndex> godot_bone_node;
+
+ Vector<BoneAttachment3D *> bone_attachments;
+
+protected:
+ static void _bind_methods();
+
+public:
+ Vector<GLTFNodeIndex> get_joints();
+ void set_joints(Vector<GLTFNodeIndex> p_joints);
+
+ Vector<GLTFNodeIndex> get_roots();
+ void set_roots(Vector<GLTFNodeIndex> p_roots);
+
+ Skeleton3D *get_godot_skeleton();
+
+ // Skeleton *get_godot_skeleton() {
+ // return this->godot_skeleton;
+ // }
+ // void set_godot_skeleton(Skeleton p_*godot_skeleton) {
+ // this->godot_skeleton = p_godot_skeleton;
+ // }
+
+ Array get_unique_names();
+ void set_unique_names(Array p_unique_names);
+
+ //Map<int32_t, GLTFNodeIndex> get_godot_bone_node() {
+ // return this->godot_bone_node;
+ //}
+ //void set_godot_bone_node(Map<int32_t, GLTFNodeIndex> p_godot_bone_node) {
+ // this->godot_bone_node = p_godot_bone_node;
+ //}
+ Dictionary get_godot_bone_node();
+ void set_godot_bone_node(Dictionary p_indict);
+
+ //Dictionary get_godot_bone_node() {
+ // return VariantConversion::to_dict(this->godot_bone_node);
+ //}
+ //void set_godot_bone_node(Dictionary p_indict) {
+ // VariantConversion::set_from_dict(this->godot_bone_node, p_indict);
+ //}
+
+ BoneAttachment3D *get_bone_attachment(int idx);
+
+ int32_t get_bone_attachment_count();
+};
+#endif // GLTF_SKELETON_H
diff --git a/modules/gltf/gltf_skin.cpp b/modules/gltf/gltf_skin.cpp
new file mode 100644
index 0000000000..fd39e4f45a
--- /dev/null
+++ b/modules/gltf/gltf_skin.cpp
@@ -0,0 +1,155 @@
+/*************************************************************************/
+/* gltf_skin.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_skin.h"
+
+void GLTFSkin::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_skin_root"), &GLTFSkin::get_skin_root);
+ ClassDB::bind_method(D_METHOD("set_skin_root", "skin_root"), &GLTFSkin::set_skin_root);
+ ClassDB::bind_method(D_METHOD("get_joints_original"), &GLTFSkin::get_joints_original);
+ ClassDB::bind_method(D_METHOD("set_joints_original", "joints_original"), &GLTFSkin::set_joints_original);
+ ClassDB::bind_method(D_METHOD("get_inverse_binds"), &GLTFSkin::get_inverse_binds);
+ ClassDB::bind_method(D_METHOD("set_inverse_binds", "inverse_binds"), &GLTFSkin::set_inverse_binds);
+ ClassDB::bind_method(D_METHOD("get_joints"), &GLTFSkin::get_joints);
+ ClassDB::bind_method(D_METHOD("set_joints", "joints"), &GLTFSkin::set_joints);
+ ClassDB::bind_method(D_METHOD("get_non_joints"), &GLTFSkin::get_non_joints);
+ ClassDB::bind_method(D_METHOD("set_non_joints", "non_joints"), &GLTFSkin::set_non_joints);
+ ClassDB::bind_method(D_METHOD("get_roots"), &GLTFSkin::get_roots);
+ ClassDB::bind_method(D_METHOD("set_roots", "roots"), &GLTFSkin::set_roots);
+ ClassDB::bind_method(D_METHOD("get_skeleton"), &GLTFSkin::get_skeleton);
+ ClassDB::bind_method(D_METHOD("set_skeleton", "skeleton"), &GLTFSkin::set_skeleton);
+ ClassDB::bind_method(D_METHOD("get_joint_i_to_bone_i"), &GLTFSkin::get_joint_i_to_bone_i);
+ ClassDB::bind_method(D_METHOD("set_joint_i_to_bone_i", "joint_i_to_bone_i"), &GLTFSkin::set_joint_i_to_bone_i);
+ ClassDB::bind_method(D_METHOD("get_joint_i_to_name"), &GLTFSkin::get_joint_i_to_name);
+ ClassDB::bind_method(D_METHOD("set_joint_i_to_name", "joint_i_to_name"), &GLTFSkin::set_joint_i_to_name);
+ ClassDB::bind_method(D_METHOD("get_godot_skin"), &GLTFSkin::get_godot_skin);
+ ClassDB::bind_method(D_METHOD("set_godot_skin", "godot_skin"), &GLTFSkin::set_godot_skin);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "skin_root"), "set_skin_root", "get_skin_root"); // GLTFNodeIndex
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "joints_original"), "set_joints_original", "get_joints_original"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "inverse_binds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "set_inverse_binds", "get_inverse_binds"); // Vector<Transform>
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "joints"), "set_joints", "get_joints"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "non_joints"), "set_non_joints", "get_non_joints"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "roots"), "set_roots", "get_roots"); // Vector<GLTFNodeIndex>
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "skeleton"), "set_skeleton", "get_skeleton"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "joint_i_to_bone_i", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "set_joint_i_to_bone_i", "get_joint_i_to_bone_i"); // Map<int,
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "joint_i_to_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "set_joint_i_to_name", "get_joint_i_to_name"); // Map<int,
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "godot_skin"), "set_godot_skin", "get_godot_skin"); // Ref<Skin>
+}
+
+GLTFNodeIndex GLTFSkin::get_skin_root() {
+ return skin_root;
+}
+
+void GLTFSkin::set_skin_root(GLTFNodeIndex p_skin_root) {
+ skin_root = p_skin_root;
+}
+
+Vector<GLTFNodeIndex> GLTFSkin::get_joints_original() {
+ return joints_original;
+}
+
+void GLTFSkin::set_joints_original(Vector<GLTFNodeIndex> p_joints_original) {
+ joints_original = p_joints_original;
+}
+
+Array GLTFSkin::get_inverse_binds() {
+ return GLTFDocument::to_array(inverse_binds);
+}
+
+void GLTFSkin::set_inverse_binds(Array p_inverse_binds) {
+ GLTFDocument::set_from_array(inverse_binds, p_inverse_binds);
+}
+
+Vector<GLTFNodeIndex> GLTFSkin::get_joints() {
+ return joints;
+}
+
+void GLTFSkin::set_joints(Vector<GLTFNodeIndex> p_joints) {
+ joints = p_joints;
+}
+
+Vector<GLTFNodeIndex> GLTFSkin::get_non_joints() {
+ return non_joints;
+}
+
+void GLTFSkin::set_non_joints(Vector<GLTFNodeIndex> p_non_joints) {
+ non_joints = p_non_joints;
+}
+
+Vector<GLTFNodeIndex> GLTFSkin::get_roots() {
+ return roots;
+}
+
+void GLTFSkin::set_roots(Vector<GLTFNodeIndex> p_roots) {
+ roots = p_roots;
+}
+
+int GLTFSkin::get_skeleton() {
+ return skeleton;
+}
+
+void GLTFSkin::set_skeleton(int p_skeleton) {
+ skeleton = p_skeleton;
+}
+
+Dictionary GLTFSkin::get_joint_i_to_bone_i() {
+ return GLTFDocument::to_dict(joint_i_to_bone_i);
+}
+
+void GLTFSkin::set_joint_i_to_bone_i(Dictionary p_joint_i_to_bone_i) {
+ GLTFDocument::set_from_dict(joint_i_to_bone_i, p_joint_i_to_bone_i);
+}
+
+Dictionary GLTFSkin::get_joint_i_to_name() {
+ Dictionary ret;
+ Map<int, StringName>::Element *elem = joint_i_to_name.front();
+ while (elem) {
+ ret[elem->key()] = String(elem->value());
+ elem = elem->next();
+ }
+ return ret;
+}
+
+void GLTFSkin::set_joint_i_to_name(Dictionary p_joint_i_to_name) {
+ joint_i_to_name = Map<int, StringName>();
+ Array keys = p_joint_i_to_name.keys();
+ for (int i = 0; i < keys.size(); i++) {
+ joint_i_to_name[keys[i]] = joint_i_to_name[keys[i]];
+ }
+}
+
+Ref<Skin> GLTFSkin::get_godot_skin() {
+ return godot_skin;
+}
+
+void GLTFSkin::set_godot_skin(Ref<Skin> p_godot_skin) {
+ godot_skin = p_godot_skin;
+}
diff --git a/modules/gltf/gltf_skin.h b/modules/gltf/gltf_skin.h
new file mode 100644
index 0000000000..7cc09d85bc
--- /dev/null
+++ b/modules/gltf/gltf_skin.h
@@ -0,0 +1,109 @@
+/*************************************************************************/
+/* gltf_skin.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_SKIN_H
+#define GLTF_SKIN_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+class GLTFSkin : public Resource {
+ GDCLASS(GLTFSkin, Resource);
+ friend class GLTFDocument;
+
+private:
+ // The "skeleton" property defined in the gltf spec. -1 = Scene Root
+ GLTFNodeIndex skin_root = -1;
+
+ Vector<GLTFNodeIndex> joints_original;
+ Vector<Transform> inverse_binds;
+
+ // Note: joints + non_joints should form a complete subtree, or subtrees
+ // with a common parent
+
+ // All nodes that are skins that are caught in-between the original joints
+ // (inclusive of joints_original)
+ Vector<GLTFNodeIndex> joints;
+
+ // All Nodes that are caught in-between skin joint nodes, and are not
+ // defined as joints by any skin
+ Vector<GLTFNodeIndex> non_joints;
+
+ // The roots of the skin. In the case of multiple roots, their parent *must*
+ // be the same (the roots must be siblings)
+ Vector<GLTFNodeIndex> roots;
+
+ // The GLTF Skeleton this Skin points to (after we determine skeletons)
+ GLTFSkeletonIndex skeleton = -1;
+
+ // A mapping from the joint indices (in the order of joints_original) to the
+ // Godot Skeleton's bone_indices
+ Map<int, int> joint_i_to_bone_i;
+ Map<int, StringName> joint_i_to_name;
+
+ // The Actual Skin that will be created as a mapping between the IBM's of
+ // this skin to the generated skeleton for the mesh instances.
+ Ref<Skin> godot_skin;
+
+protected:
+ static void _bind_methods();
+
+public:
+ GLTFNodeIndex get_skin_root();
+ void set_skin_root(GLTFNodeIndex p_skin_root);
+
+ Vector<GLTFNodeIndex> get_joints_original();
+ void set_joints_original(Vector<GLTFNodeIndex> p_joints_original);
+
+ Array get_inverse_binds();
+ void set_inverse_binds(Array p_inverse_binds);
+
+ Vector<GLTFNodeIndex> get_joints();
+ void set_joints(Vector<GLTFNodeIndex> p_joints);
+
+ Vector<GLTFNodeIndex> get_non_joints();
+ void set_non_joints(Vector<GLTFNodeIndex> p_non_joints);
+
+ Vector<GLTFNodeIndex> get_roots();
+ void set_roots(Vector<GLTFNodeIndex> p_roots);
+
+ int get_skeleton();
+ void set_skeleton(int p_skeleton);
+
+ Dictionary get_joint_i_to_bone_i();
+ void set_joint_i_to_bone_i(Dictionary p_joint_i_to_bone_i);
+
+ Dictionary get_joint_i_to_name();
+ void set_joint_i_to_name(Dictionary p_joint_i_to_name);
+
+ Ref<Skin> get_godot_skin();
+ void set_godot_skin(Ref<Skin> p_godot_skin);
+};
+#endif // GLTF_SKIN_H
diff --git a/modules/gltf/gltf_spec_gloss.cpp b/modules/gltf/gltf_spec_gloss.cpp
new file mode 100644
index 0000000000..70b182da52
--- /dev/null
+++ b/modules/gltf/gltf_spec_gloss.cpp
@@ -0,0 +1,90 @@
+/*************************************************************************/
+/* gltf_spec_gloss.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_spec_gloss.h"
+
+void GLTFSpecGloss::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_diffuse_img"), &GLTFSpecGloss::get_diffuse_img);
+ ClassDB::bind_method(D_METHOD("set_diffuse_img", "diffuse_img"), &GLTFSpecGloss::set_diffuse_img);
+ ClassDB::bind_method(D_METHOD("get_diffuse_factor"), &GLTFSpecGloss::get_diffuse_factor);
+ ClassDB::bind_method(D_METHOD("set_diffuse_factor", "diffuse_factor"), &GLTFSpecGloss::set_diffuse_factor);
+ ClassDB::bind_method(D_METHOD("get_gloss_factor"), &GLTFSpecGloss::get_gloss_factor);
+ ClassDB::bind_method(D_METHOD("set_gloss_factor", "gloss_factor"), &GLTFSpecGloss::set_gloss_factor);
+ ClassDB::bind_method(D_METHOD("get_specular_factor"), &GLTFSpecGloss::get_specular_factor);
+ ClassDB::bind_method(D_METHOD("set_specular_factor", "specular_factor"), &GLTFSpecGloss::set_specular_factor);
+ ClassDB::bind_method(D_METHOD("get_spec_gloss_img"), &GLTFSpecGloss::get_spec_gloss_img);
+ ClassDB::bind_method(D_METHOD("set_spec_gloss_img", "spec_gloss_img"), &GLTFSpecGloss::set_spec_gloss_img);
+
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "diffuse_img"), "set_diffuse_img", "get_diffuse_img"); // Ref<Image>
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "diffuse_factor"), "set_diffuse_factor", "get_diffuse_factor"); // Color
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gloss_factor"), "set_gloss_factor", "get_gloss_factor"); // float
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "specular_factor"), "set_specular_factor", "get_specular_factor"); // Color
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "spec_gloss_img"), "set_spec_gloss_img", "get_spec_gloss_img"); // Ref<Image>
+}
+
+Ref<Image> GLTFSpecGloss::get_diffuse_img() {
+ return diffuse_img;
+}
+
+void GLTFSpecGloss::set_diffuse_img(Ref<Image> p_diffuse_img) {
+ diffuse_img = p_diffuse_img;
+}
+
+Color GLTFSpecGloss::get_diffuse_factor() {
+ return diffuse_factor;
+}
+
+void GLTFSpecGloss::set_diffuse_factor(Color p_diffuse_factor) {
+ diffuse_factor = p_diffuse_factor;
+}
+
+float GLTFSpecGloss::get_gloss_factor() {
+ return gloss_factor;
+}
+
+void GLTFSpecGloss::set_gloss_factor(float p_gloss_factor) {
+ gloss_factor = p_gloss_factor;
+}
+
+Color GLTFSpecGloss::get_specular_factor() {
+ return specular_factor;
+}
+
+void GLTFSpecGloss::set_specular_factor(Color p_specular_factor) {
+ specular_factor = p_specular_factor;
+}
+
+Ref<Image> GLTFSpecGloss::get_spec_gloss_img() {
+ return spec_gloss_img;
+}
+
+void GLTFSpecGloss::set_spec_gloss_img(Ref<Image> p_spec_gloss_img) {
+ spec_gloss_img = p_spec_gloss_img;
+}
diff --git a/modules/gltf/gltf_spec_gloss.h b/modules/gltf/gltf_spec_gloss.h
new file mode 100644
index 0000000000..3cc6fb09ed
--- /dev/null
+++ b/modules/gltf/gltf_spec_gloss.h
@@ -0,0 +1,67 @@
+/*************************************************************************/
+/* gltf_spec_gloss.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_SPEC_GLOSS_H
+#define GLTF_SPEC_GLOSS_H
+
+#include "core/io/image.h"
+#include "core/io/resource.h"
+
+class GLTFSpecGloss : public Resource {
+ GDCLASS(GLTFSpecGloss, Resource);
+ friend class GLTFDocument;
+
+private:
+ Ref<Image> diffuse_img = nullptr;
+ Color diffuse_factor = Color(1.0f, 1.0f, 1.0f);
+ float gloss_factor = 1.0f;
+ Color specular_factor = Color(1.0f, 1.0f, 1.0f);
+ Ref<Image> spec_gloss_img = nullptr;
+
+protected:
+ static void _bind_methods();
+
+public:
+ Ref<Image> get_diffuse_img();
+ void set_diffuse_img(Ref<Image> p_diffuse_img);
+
+ Color get_diffuse_factor();
+ void set_diffuse_factor(Color p_diffuse_factor);
+
+ float get_gloss_factor();
+ void set_gloss_factor(float p_gloss_factor);
+
+ Color get_specular_factor();
+ void set_specular_factor(Color p_specular_factor);
+
+ Ref<Image> get_spec_gloss_img();
+ void set_spec_gloss_img(Ref<Image> p_spec_gloss_img);
+};
+#endif // GLTF_SPEC_GLOSS_H
diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp
new file mode 100644
index 0000000000..eedc743330
--- /dev/null
+++ b/modules/gltf/gltf_state.cpp
@@ -0,0 +1,296 @@
+/*************************************************************************/
+/* gltf_state.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_state.h"
+
+void GLTFState::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_json"), &GLTFState::get_json);
+ ClassDB::bind_method(D_METHOD("set_json", "json"), &GLTFState::set_json);
+ ClassDB::bind_method(D_METHOD("get_major_version"), &GLTFState::get_major_version);
+ ClassDB::bind_method(D_METHOD("set_major_version", "major_version"), &GLTFState::set_major_version);
+ ClassDB::bind_method(D_METHOD("get_minor_version"), &GLTFState::get_minor_version);
+ ClassDB::bind_method(D_METHOD("set_minor_version", "minor_version"), &GLTFState::set_minor_version);
+ ClassDB::bind_method(D_METHOD("get_glb_data"), &GLTFState::get_glb_data);
+ ClassDB::bind_method(D_METHOD("set_glb_data", "glb_data"), &GLTFState::set_glb_data);
+ ClassDB::bind_method(D_METHOD("get_use_named_skin_binds"), &GLTFState::get_use_named_skin_binds);
+ ClassDB::bind_method(D_METHOD("set_use_named_skin_binds", "use_named_skin_binds"), &GLTFState::set_use_named_skin_binds);
+ ClassDB::bind_method(D_METHOD("get_nodes"), &GLTFState::get_nodes);
+ ClassDB::bind_method(D_METHOD("set_nodes", "nodes"), &GLTFState::set_nodes);
+ ClassDB::bind_method(D_METHOD("get_buffers"), &GLTFState::get_buffers);
+ ClassDB::bind_method(D_METHOD("set_buffers", "buffers"), &GLTFState::set_buffers);
+ ClassDB::bind_method(D_METHOD("get_buffer_views"), &GLTFState::get_buffer_views);
+ ClassDB::bind_method(D_METHOD("set_buffer_views", "buffer_views"), &GLTFState::set_buffer_views);
+ ClassDB::bind_method(D_METHOD("get_accessors"), &GLTFState::get_accessors);
+ ClassDB::bind_method(D_METHOD("set_accessors", "accessors"), &GLTFState::set_accessors);
+ ClassDB::bind_method(D_METHOD("get_meshes"), &GLTFState::get_meshes);
+ ClassDB::bind_method(D_METHOD("set_meshes", "meshes"), &GLTFState::set_meshes);
+ ClassDB::bind_method(D_METHOD("get_animation_players_count"), &GLTFState::get_animation_players_count);
+ ClassDB::bind_method(D_METHOD("get_animation_player"), &GLTFState::get_animation_player);
+ ClassDB::bind_method(D_METHOD("get_materials"), &GLTFState::get_materials);
+ ClassDB::bind_method(D_METHOD("set_materials", "materials"), &GLTFState::set_materials);
+ ClassDB::bind_method(D_METHOD("get_scene_name"), &GLTFState::get_scene_name);
+ ClassDB::bind_method(D_METHOD("set_scene_name", "scene_name"), &GLTFState::set_scene_name);
+ ClassDB::bind_method(D_METHOD("get_root_nodes"), &GLTFState::get_root_nodes);
+ ClassDB::bind_method(D_METHOD("set_root_nodes", "root_nodes"), &GLTFState::set_root_nodes);
+ ClassDB::bind_method(D_METHOD("get_textures"), &GLTFState::get_textures);
+ ClassDB::bind_method(D_METHOD("set_textures", "textures"), &GLTFState::set_textures);
+ ClassDB::bind_method(D_METHOD("get_images"), &GLTFState::get_images);
+ ClassDB::bind_method(D_METHOD("set_images", "images"), &GLTFState::set_images);
+ ClassDB::bind_method(D_METHOD("get_skins"), &GLTFState::get_skins);
+ ClassDB::bind_method(D_METHOD("set_skins", "skins"), &GLTFState::set_skins);
+ ClassDB::bind_method(D_METHOD("get_cameras"), &GLTFState::get_cameras);
+ ClassDB::bind_method(D_METHOD("set_cameras", "cameras"), &GLTFState::set_cameras);
+ ClassDB::bind_method(D_METHOD("get_lights"), &GLTFState::get_lights);
+ ClassDB::bind_method(D_METHOD("set_lights", "lights"), &GLTFState::set_lights);
+ ClassDB::bind_method(D_METHOD("get_unique_names"), &GLTFState::get_unique_names);
+ ClassDB::bind_method(D_METHOD("set_unique_names", "unique_names"), &GLTFState::set_unique_names);
+ ClassDB::bind_method(D_METHOD("get_skeletons"), &GLTFState::get_skeletons);
+ ClassDB::bind_method(D_METHOD("set_skeletons", "skeletons"), &GLTFState::set_skeletons);
+ ClassDB::bind_method(D_METHOD("get_skeleton_to_node"), &GLTFState::get_skeleton_to_node);
+ ClassDB::bind_method(D_METHOD("set_skeleton_to_node", "skeleton_to_node"), &GLTFState::set_skeleton_to_node);
+ ClassDB::bind_method(D_METHOD("get_animations"), &GLTFState::get_animations);
+ ClassDB::bind_method(D_METHOD("set_animations", "animations"), &GLTFState::set_animations);
+ ClassDB::bind_method(D_METHOD("get_scene_node"), &GLTFState::get_scene_node);
+
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "json"), "set_json", "get_json"); // Dictionary
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "major_version"), "set_major_version", "get_major_version"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "minor_version"), "set_minor_version", "get_minor_version"); // int
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "glb_data"), "set_glb_data", "get_glb_data"); // Vector<uint8_t>
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_named_skin_binds"), "set_use_named_skin_binds", "get_use_named_skin_binds"); // bool
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "nodes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_nodes", "get_nodes"); // Vector<Ref<GLTFNode>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "buffers"), "set_buffers", "get_buffers"); // Vector<Vector<uint8_t>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "buffer_views", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_buffer_views", "get_buffer_views"); // Vector<Ref<GLTFBufferView>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "accessors", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_accessors", "get_accessors"); // Vector<Ref<GLTFAccessor>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "meshes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_meshes", "get_meshes"); // Vector<Ref<GLTFMesh>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "materials", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_materials", "get_materials"); // Vector<Ref<Material>
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "scene_name"), "set_scene_name", "get_scene_name"); // String
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "root_nodes"), "set_root_nodes", "get_root_nodes"); // Vector<int>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_textures", "get_textures"); // Vector<Ref<GLTFTexture>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "images", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_images", "get_images"); // Vector<Ref<Texture>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "skins", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_skins", "get_skins"); // Vector<Ref<GLTFSkin>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "cameras", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_cameras", "get_cameras"); // Vector<Ref<GLTFCamera>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "lights", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_lights", "get_lights"); // Vector<Ref<GLTFLight>>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "unique_names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_unique_names", "get_unique_names"); // Set<String>
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "skeletons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_skeletons", "get_skeletons"); // Vector<Ref<GLTFSkeleton>>
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "skeleton_to_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_skeleton_to_node", "get_skeleton_to_node"); // Map<GLTFSkeletonIndex,
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_animations", "get_animations"); // Vector<Ref<GLTFAnimation>>
+}
+
+Dictionary GLTFState::get_json() {
+ return json;
+}
+
+void GLTFState::set_json(Dictionary p_json) {
+ json = p_json;
+}
+
+int GLTFState::get_major_version() {
+ return major_version;
+}
+
+void GLTFState::set_major_version(int p_major_version) {
+ major_version = p_major_version;
+}
+
+int GLTFState::get_minor_version() {
+ return minor_version;
+}
+
+void GLTFState::set_minor_version(int p_minor_version) {
+ minor_version = p_minor_version;
+}
+
+Vector<uint8_t> GLTFState::get_glb_data() {
+ return glb_data;
+}
+
+void GLTFState::set_glb_data(Vector<uint8_t> p_glb_data) {
+ glb_data = p_glb_data;
+}
+
+bool GLTFState::get_use_named_skin_binds() {
+ return use_named_skin_binds;
+}
+
+void GLTFState::set_use_named_skin_binds(bool p_use_named_skin_binds) {
+ use_named_skin_binds = p_use_named_skin_binds;
+}
+
+Array GLTFState::get_nodes() {
+ return GLTFDocument::to_array(nodes);
+}
+
+void GLTFState::set_nodes(Array p_nodes) {
+ GLTFDocument::set_from_array(nodes, p_nodes);
+}
+
+Array GLTFState::get_buffers() {
+ return GLTFDocument::to_array(buffers);
+}
+
+void GLTFState::set_buffers(Array p_buffers) {
+ GLTFDocument::set_from_array(buffers, p_buffers);
+}
+
+Array GLTFState::get_buffer_views() {
+ return GLTFDocument::to_array(buffer_views);
+}
+
+void GLTFState::set_buffer_views(Array p_buffer_views) {
+ GLTFDocument::set_from_array(buffer_views, p_buffer_views);
+}
+
+Array GLTFState::get_accessors() {
+ return GLTFDocument::to_array(accessors);
+}
+
+void GLTFState::set_accessors(Array p_accessors) {
+ GLTFDocument::set_from_array(accessors, p_accessors);
+}
+
+Array GLTFState::get_meshes() {
+ return GLTFDocument::to_array(meshes);
+}
+
+void GLTFState::set_meshes(Array p_meshes) {
+ GLTFDocument::set_from_array(meshes, p_meshes);
+}
+
+Array GLTFState::get_materials() {
+ return GLTFDocument::to_array(materials);
+}
+
+void GLTFState::set_materials(Array p_materials) {
+ GLTFDocument::set_from_array(materials, p_materials);
+}
+
+String GLTFState::get_scene_name() {
+ return scene_name;
+}
+
+void GLTFState::set_scene_name(String p_scene_name) {
+ scene_name = p_scene_name;
+}
+
+Array GLTFState::get_root_nodes() {
+ return GLTFDocument::to_array(root_nodes);
+}
+
+void GLTFState::set_root_nodes(Array p_root_nodes) {
+ GLTFDocument::set_from_array(root_nodes, p_root_nodes);
+}
+
+Array GLTFState::get_textures() {
+ return GLTFDocument::to_array(textures);
+}
+
+void GLTFState::set_textures(Array p_textures) {
+ GLTFDocument::set_from_array(textures, p_textures);
+}
+
+Array GLTFState::get_images() {
+ return GLTFDocument::to_array(images);
+}
+
+void GLTFState::set_images(Array p_images) {
+ GLTFDocument::set_from_array(images, p_images);
+}
+
+Array GLTFState::get_skins() {
+ return GLTFDocument::to_array(skins);
+}
+
+void GLTFState::set_skins(Array p_skins) {
+ GLTFDocument::set_from_array(skins, p_skins);
+}
+
+Array GLTFState::get_cameras() {
+ return GLTFDocument::to_array(cameras);
+}
+
+void GLTFState::set_cameras(Array p_cameras) {
+ GLTFDocument::set_from_array(cameras, p_cameras);
+}
+
+Array GLTFState::get_lights() {
+ return GLTFDocument::to_array(lights);
+}
+
+void GLTFState::set_lights(Array p_lights) {
+ GLTFDocument::set_from_array(lights, p_lights);
+}
+
+Array GLTFState::get_unique_names() {
+ return GLTFDocument::to_array(unique_names);
+}
+
+void GLTFState::set_unique_names(Array p_unique_names) {
+ GLTFDocument::set_from_array(unique_names, p_unique_names);
+}
+
+Array GLTFState::get_skeletons() {
+ return GLTFDocument::to_array(skeletons);
+}
+
+void GLTFState::set_skeletons(Array p_skeletons) {
+ GLTFDocument::set_from_array(skeletons, p_skeletons);
+}
+
+Dictionary GLTFState::get_skeleton_to_node() {
+ return GLTFDocument::to_dict(skeleton_to_node);
+}
+
+void GLTFState::set_skeleton_to_node(Dictionary p_skeleton_to_node) {
+ GLTFDocument::set_from_dict(skeleton_to_node, p_skeleton_to_node);
+}
+
+Array GLTFState::get_animations() {
+ return GLTFDocument::to_array(animations);
+}
+
+void GLTFState::set_animations(Array p_animations) {
+ GLTFDocument::set_from_array(animations, p_animations);
+}
+
+Node *GLTFState::get_scene_node(GLTFNodeIndex idx) {
+ if (!scene_nodes.has(idx)) {
+ return nullptr;
+ }
+ return scene_nodes[idx];
+}
+
+int GLTFState::get_animation_players_count(int idx) {
+ return animation_players.size();
+}
+
+AnimationPlayer *GLTFState::get_animation_player(int idx) {
+ ERR_FAIL_INDEX_V(idx, animation_players.size(), nullptr);
+ return animation_players[idx];
+}
diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h
new file mode 100644
index 0000000000..4ce5aa9491
--- /dev/null
+++ b/modules/gltf/gltf_state.h
@@ -0,0 +1,180 @@
+/*************************************************************************/
+/* gltf_state.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_STATE_H
+#define GLTF_STATE_H
+
+#include "core/io/resource.h"
+#include "core/templates/vector.h"
+#include "editor_scene_importer_gltf.h"
+#include "gltf_accessor.h"
+#include "gltf_animation.h"
+#include "gltf_buffer_view.h"
+#include "gltf_camera.h"
+#include "gltf_document.h"
+#include "gltf_light.h"
+#include "gltf_mesh.h"
+#include "gltf_node.h"
+#include "gltf_skeleton.h"
+#include "gltf_skin.h"
+#include "gltf_texture.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/texture.h"
+
+class GLTFState : public Resource {
+ GDCLASS(GLTFState, Resource);
+ friend class GLTFDocument;
+ friend class PackedSceneGLTF;
+
+ Dictionary json;
+ int major_version = 0;
+ int minor_version = 0;
+ Vector<uint8_t> glb_data;
+
+ bool use_named_skin_binds = false;
+
+ Vector<Ref<GLTFNode>> nodes;
+ Vector<Vector<uint8_t>> buffers;
+ Vector<Ref<GLTFBufferView>> buffer_views;
+ Vector<Ref<GLTFAccessor>> accessors;
+
+ Vector<Ref<GLTFMesh>> meshes; // meshes are loaded directly, no reason not to.
+
+ Vector<AnimationPlayer *> animation_players;
+ Map<Ref<BaseMaterial3D>, GLTFMaterialIndex> material_cache;
+ Vector<Ref<BaseMaterial3D>> materials;
+
+ String scene_name;
+ Vector<int> root_nodes;
+ Vector<Ref<GLTFTexture>> textures;
+ Vector<Ref<Texture2D>> images;
+
+ Vector<Ref<GLTFSkin>> skins;
+ Vector<Ref<GLTFCamera>> cameras;
+ Vector<Ref<GLTFLight>> lights;
+ Set<String> unique_names;
+
+ Vector<Ref<GLTFSkeleton>> skeletons;
+ Map<GLTFSkeletonIndex, GLTFNodeIndex> skeleton_to_node;
+ Vector<Ref<GLTFAnimation>> animations;
+ Map<GLTFNodeIndex, Node *> scene_nodes;
+
+protected:
+ static void _bind_methods();
+
+public:
+ Dictionary get_json();
+ void set_json(Dictionary p_json);
+
+ int get_major_version();
+ void set_major_version(int p_major_version);
+
+ int get_minor_version();
+ void set_minor_version(int p_minor_version);
+
+ Vector<uint8_t> get_glb_data();
+ void set_glb_data(Vector<uint8_t> p_glb_data);
+
+ bool get_use_named_skin_binds();
+ void set_use_named_skin_binds(bool p_use_named_skin_binds);
+
+ Array get_nodes();
+ void set_nodes(Array p_nodes);
+
+ Array get_buffers();
+ void set_buffers(Array p_buffers);
+
+ Array get_buffer_views();
+ void set_buffer_views(Array p_buffer_views);
+
+ Array get_accessors();
+ void set_accessors(Array p_accessors);
+
+ Array get_meshes();
+ void set_meshes(Array p_meshes);
+
+ Array get_materials();
+ void set_materials(Array p_materials);
+
+ String get_scene_name();
+ void set_scene_name(String p_scene_name);
+
+ Array get_root_nodes();
+ void set_root_nodes(Array p_root_nodes);
+
+ Array get_textures();
+ void set_textures(Array p_textures);
+
+ Array get_images();
+ void set_images(Array p_images);
+
+ Array get_skins();
+ void set_skins(Array p_skins);
+
+ Array get_cameras();
+ void set_cameras(Array p_cameras);
+
+ Array get_lights();
+ void set_lights(Array p_lights);
+
+ Array get_unique_names();
+ void set_unique_names(Array p_unique_names);
+
+ Array get_skeletons();
+ void set_skeletons(Array p_skeletons);
+
+ Dictionary get_skeleton_to_node();
+ void set_skeleton_to_node(Dictionary p_skeleton_to_node);
+
+ Array get_animations();
+ void set_animations(Array p_animations);
+
+ Node *get_scene_node(GLTFNodeIndex idx);
+
+ int get_animation_players_count(int idx);
+
+ AnimationPlayer *get_animation_player(int idx);
+
+ //void set_scene_nodes(Map<GLTFNodeIndex, Node *> p_scene_nodes) {
+ // this->scene_nodes = p_scene_nodes;
+ //}
+
+ //void set_animation_players(Vector<AnimationPlayer *> p_animation_players) {
+ // this->animation_players = p_animation_players;
+ //}
+
+ //Map<Ref<Material>, GLTFMaterialIndex> get_material_cache() {
+ // return this->material_cache;
+ //}
+ //void set_material_cache(Map<Ref<Material>, GLTFMaterialIndex> p_material_cache) {
+ // this->material_cache = p_material_cache;
+ //}
+};
+#endif // GLTF_STATE_H
diff --git a/modules/gltf/gltf_texture.cpp b/modules/gltf/gltf_texture.cpp
new file mode 100644
index 0000000000..0482c1064e
--- /dev/null
+++ b/modules/gltf/gltf_texture.cpp
@@ -0,0 +1,46 @@
+/*************************************************************************/
+/* gltf_texture.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "gltf_texture.h"
+
+void GLTFTexture::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_src_image"), &GLTFTexture::get_src_image);
+ ClassDB::bind_method(D_METHOD("set_src_image", "src_image"), &GLTFTexture::set_src_image);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "src_image"), "set_src_image", "get_src_image"); // int
+}
+
+GLTFImageIndex GLTFTexture::get_src_image() const {
+ return src_image;
+}
+
+void GLTFTexture::set_src_image(GLTFImageIndex val) {
+ src_image = val;
+}
diff --git a/modules/gltf/gltf_texture.h b/modules/gltf/gltf_texture.h
new file mode 100644
index 0000000000..e1d0407fb4
--- /dev/null
+++ b/modules/gltf/gltf_texture.h
@@ -0,0 +1,51 @@
+/*************************************************************************/
+/* gltf_texture.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GLTF_TEXTURE_H
+#define GLTF_TEXTURE_H
+
+#include "core/io/resource.h"
+#include "gltf_document.h"
+
+class GLTFTexture : public Resource {
+ GDCLASS(GLTFTexture, Resource);
+
+private:
+ GLTFImageIndex src_image;
+
+protected:
+ static void _bind_methods();
+
+public:
+ GLTFImageIndex get_src_image() const;
+ void set_src_image(GLTFImageIndex val);
+};
+
+#endif // GLTF_TEXTURE_H
diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp
new file mode 100644
index 0000000000..dc995c9249
--- /dev/null
+++ b/modules/gltf/register_types.cpp
@@ -0,0 +1,88 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "editor/editor_node.h"
+#include "editor_scene_exporter_gltf_plugin.h"
+#include "editor_scene_importer_gltf.h"
+#include "gltf_accessor.h"
+#include "gltf_animation.h"
+#include "gltf_buffer_view.h"
+#include "gltf_camera.h"
+#include "gltf_document.h"
+#include "gltf_light.h"
+#include "gltf_mesh.h"
+#include "gltf_node.h"
+#include "gltf_skeleton.h"
+#include "gltf_skin.h"
+#include "gltf_spec_gloss.h"
+#include "gltf_state.h"
+#include "gltf_texture.h"
+
+#ifndef _3D_DISABLED
+#ifdef TOOLS_ENABLED
+static void _editor_init() {
+ Ref<EditorSceneImporterGLTF> import_gltf;
+ import_gltf.instance();
+ ResourceImporterScene::get_singleton()->add_importer(import_gltf);
+}
+#endif
+#endif
+
+void register_gltf_types() {
+#ifndef _3D_DISABLED
+#ifdef TOOLS_ENABLED
+ ClassDB::APIType prev_api = ClassDB::get_current_api();
+ ClassDB::set_current_api(ClassDB::API_EDITOR);
+ ClassDB::register_class<EditorSceneImporterGLTF>();
+ ClassDB::register_class<GLTFMesh>();
+ EditorPlugins::add_by_type<SceneExporterGLTFPlugin>();
+ ClassDB::set_current_api(prev_api);
+ EditorNode::add_init_callback(_editor_init);
+#endif
+ ClassDB::register_class<GLTFSpecGloss>();
+ ClassDB::register_class<GLTFNode>();
+ ClassDB::register_class<GLTFAnimation>();
+ ClassDB::register_class<GLTFBufferView>();
+ ClassDB::register_class<GLTFAccessor>();
+ ClassDB::register_class<GLTFTexture>();
+ ClassDB::register_class<GLTFSkeleton>();
+ ClassDB::register_class<GLTFSkin>();
+ ClassDB::register_class<GLTFCamera>();
+ ClassDB::register_class<GLTFLight>();
+ ClassDB::register_class<GLTFState>();
+ ClassDB::register_class<GLTFDocument>();
+ ClassDB::register_class<PackedSceneGLTF>();
+#endif
+}
+
+void unregister_gltf_types() {
+}
diff --git a/modules/arkit/register_types.h b/modules/gltf/register_types.h
index 5c697baf68..fefacb1106 100644
--- a/modules/arkit/register_types.h
+++ b/modules/gltf/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,5 +28,5 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-void register_arkit_types();
-void unregister_arkit_types();
+void register_gltf_types();
+void unregister_gltf_types();
diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml
index a213069e19..4dccb03369 100644
--- a/modules/gridmap/doc_classes/GridMap.xml
+++ b/modules/gridmap/doc_classes/GridMap.xml
@@ -10,7 +10,9 @@
Internally, a GridMap is split into a sparse collection of octants for efficient rendering and physics processing. Every octant has the same dimensions and can contain several cells.
</description>
<tutorials>
- <link>https://docs.godotengine.org/en/latest/tutorials/3d/using_gridmaps.html</link>
+ <link title="Using gridmaps">https://docs.godotengine.org/en/latest/tutorials/3d/using_gridmaps.html</link>
+ <link title="3D Platformer Demo">https://godotengine.org/asset-library/asset/125</link>
+ <link title="3D Kinematic Character Demo">https://godotengine.org/asset-library/asset/126</link>
</tutorials>
<methods>
<method name="clear">
@@ -43,27 +45,19 @@
<method name="get_cell_item" qualifiers="const">
<return type="int">
</return>
- <argument index="0" name="x" type="int">
- </argument>
- <argument index="1" name="y" type="int">
- </argument>
- <argument index="2" name="z" type="int">
+ <argument index="0" name="position" type="Vector3i">
</argument>
<description>
- The [MeshLibrary] item index located at the grid-based X, Y and Z coordinates. If the cell is empty, [constant INVALID_CELL_ITEM] will be returned.
+ The [MeshLibrary] item index located at the given grid coordinates. If the cell is empty, [constant INVALID_CELL_ITEM] will be returned.
</description>
</method>
<method name="get_cell_item_orientation" qualifiers="const">
<return type="int">
</return>
- <argument index="0" name="x" type="int">
- </argument>
- <argument index="1" name="y" type="int">
- </argument>
- <argument index="2" name="z" type="int">
+ <argument index="0" name="position" type="Vector3i">
</argument>
<description>
- The orientation of the cell at the grid-based X, Y and Z coordinates. -1 is returned if the cell is empty.
+ The orientation of the cell at the given grid coordinates. [code]-1[/code] is returned if the cell is empty.
</description>
</method>
<method name="get_collision_layer_bit" qualifiers="const">
@@ -111,11 +105,7 @@
<method name="map_to_world" qualifiers="const">
<return type="Vector3">
</return>
- <argument index="0" name="x" type="int">
- </argument>
- <argument index="1" name="y" type="int">
- </argument>
- <argument index="2" name="z" type="int">
+ <argument index="0" name="map_position" type="Vector3i">
</argument>
<description>
Returns the position of a grid cell in the GridMap's local coordinate space.
@@ -132,18 +122,14 @@
<method name="set_cell_item">
<return type="void">
</return>
- <argument index="0" name="x" type="int">
- </argument>
- <argument index="1" name="y" type="int">
+ <argument index="0" name="position" type="Vector3i">
</argument>
- <argument index="2" name="z" type="int">
+ <argument index="1" name="item" type="int">
</argument>
- <argument index="3" name="item" type="int">
- </argument>
- <argument index="4" name="orientation" type="int" default="0">
+ <argument index="2" name="orientation" type="int" default="0">
</argument>
<description>
- Sets the mesh index for the cell referenced by its grid-based X, Y and Z coordinates.
+ Sets the mesh index for the cell referenced by its grid coordinates.
A negative item index such as [constant INVALID_CELL_ITEM] will clear the cell.
Optionally, the item's orientation can be passed. For valid orientation values, see [method Basis.get_orthogonal_index].
</description>
@@ -185,9 +171,9 @@
</description>
</method>
<method name="world_to_map" qualifiers="const">
- <return type="Vector3">
+ <return type="Vector3i">
</return>
- <argument index="0" name="pos" type="Vector3">
+ <argument index="0" name="world_position" type="Vector3">
</argument>
<description>
Returns the coordinates of the grid cell containing the given point.
@@ -221,7 +207,7 @@
GridMaps act as static bodies, meaning they aren't affected by gravity or other forces. They only affect other physics bodies that collide with them.
</member>
<member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1">
- The physics layers this GridMap detects collisions in.
+ The physics layers this GridMap detects collisions in. See [url=https://docs.godotengine.org/en/latest/tutorials/physics/physics_introduction.html#collision-layers-and-masks]Collision layers and masks[/url] in the documentation for more information.
</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 0dbefbb39f..5a17541075 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#include "grid_map.h"
#include "core/io/marshalls.h"
-#include "core/message_queue.h"
+#include "core/object/message_queue.h"
#include "scene/3d/light_3d.h"
#include "scene/resources/mesh_library.h"
#include "scene/resources/surface_tool.h"
@@ -40,22 +40,18 @@
#include "servers/rendering_server.h"
bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
-
String name = p_name;
if (name == "data") {
-
Dictionary d = p_value;
if (d.has("cells")) {
-
Vector<int> cells = d["cells"];
int amount = cells.size();
const int *r = cells.ptr();
ERR_FAIL_COND_V(amount % 3, false); // not even
cell_map.clear();
for (int i = 0; i < amount / 3; i++) {
-
IndexKey ik;
ik.key = decode_uint64((const uint8_t *)&r[i * 3]);
Cell cell;
@@ -67,7 +63,6 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
_recreate_octant_data();
} else if (name == "baked_meshes") {
-
clear_baked_meshes();
Array meshes = p_value;
@@ -96,11 +91,9 @@ bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
}
bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
-
String name = p_name;
if (name == "data") {
-
Dictionary d;
Vector<int> cells;
@@ -109,7 +102,6 @@ bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
int *w = cells.ptrw();
int i = 0;
for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next(), i++) {
-
encode_uint64(E->key().key, (uint8_t *)&w[i * 3]);
encode_uint32(E->get().cell, (uint8_t *)&w[i * 3 + 2]);
}
@@ -119,7 +111,6 @@ bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
r_ret = d;
} else if (name == "baked_meshes") {
-
Array ret;
ret.resize(baked_meshes.size());
for (int i = 0; i < baked_meshes.size(); i++) {
@@ -127,14 +118,14 @@ bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
}
r_ret = ret;
- } else
+ } else {
return false;
+ }
return true;
}
void GridMap::_get_property_list(List<PropertyInfo> *p_list) const {
-
if (baked_meshes.size()) {
p_list->push_back(PropertyInfo(Variant::ARRAY, "baked_meshes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
}
@@ -143,71 +134,65 @@ void GridMap::_get_property_list(List<PropertyInfo> *p_list) const {
}
void GridMap::set_collision_layer(uint32_t p_layer) {
-
collision_layer = p_layer;
_reset_physic_bodies_collision_filters();
}
uint32_t GridMap::get_collision_layer() const {
-
return collision_layer;
}
void GridMap::set_collision_mask(uint32_t p_mask) {
-
collision_mask = p_mask;
_reset_physic_bodies_collision_filters();
}
uint32_t GridMap::get_collision_mask() const {
-
return collision_mask;
}
void GridMap::set_collision_mask_bit(int p_bit, bool p_value) {
-
uint32_t mask = get_collision_mask();
- if (p_value)
+ if (p_value) {
mask |= 1 << p_bit;
- else
+ } else {
mask &= ~(1 << p_bit);
+ }
set_collision_mask(mask);
}
bool GridMap::get_collision_mask_bit(int p_bit) const {
-
return get_collision_mask() & (1 << p_bit);
}
void GridMap::set_collision_layer_bit(int p_bit, bool p_value) {
-
uint32_t mask = get_collision_layer();
- if (p_value)
+ if (p_value) {
mask |= 1 << p_bit;
- else
+ } else {
mask &= ~(1 << p_bit);
+ }
set_collision_layer(mask);
}
bool GridMap::get_collision_layer_bit(int p_bit) const {
-
return get_collision_layer() & (1 << p_bit);
}
void GridMap::set_mesh_library(const Ref<MeshLibrary> &p_mesh_library) {
-
- if (!mesh_library.is_null())
+ if (!mesh_library.is_null()) {
mesh_library->unregister_owner(this);
+ }
mesh_library = p_mesh_library;
- if (!mesh_library.is_null())
+ if (!mesh_library.is_null()) {
mesh_library->register_owner(this);
+ }
_recreate_octant_data();
_change_notify("mesh_library");
}
Ref<MeshLibrary> GridMap::get_mesh_library() const {
-
return mesh_library;
}
@@ -217,24 +202,22 @@ void GridMap::set_cell_size(const Vector3 &p_size) {
_recreate_octant_data();
emit_signal("cell_size_changed", cell_size);
}
-Vector3 GridMap::get_cell_size() const {
+Vector3 GridMap::get_cell_size() const {
return cell_size;
}
void GridMap::set_octant_size(int p_size) {
-
ERR_FAIL_COND(p_size == 0);
octant_size = p_size;
_recreate_octant_data();
}
-int GridMap::get_octant_size() const {
+int GridMap::get_octant_size() const {
return octant_size;
}
void GridMap::set_center_x(bool p_enable) {
-
center_x = p_enable;
_recreate_octant_data();
}
@@ -244,7 +227,6 @@ bool GridMap::get_center_x() const {
}
void GridMap::set_center_y(bool p_enable) {
-
center_y = p_enable;
_recreate_octant_data();
}
@@ -254,7 +236,6 @@ bool GridMap::get_center_y() const {
}
void GridMap::set_center_z(bool p_enable) {
-
center_z = p_enable;
_recreate_octant_data();
}
@@ -263,27 +244,26 @@ bool GridMap::get_center_z() const {
return center_z;
}
-void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) {
-
+void GridMap::set_cell_item(const Vector3i &p_position, int p_item, int p_rot) {
if (baked_meshes.size() && !recreating_octants) {
//if you set a cell item, baked meshes go good bye
clear_baked_meshes();
_recreate_octant_data();
}
- ERR_FAIL_INDEX(ABS(p_x), 1 << 20);
- ERR_FAIL_INDEX(ABS(p_y), 1 << 20);
- ERR_FAIL_INDEX(ABS(p_z), 1 << 20);
+ ERR_FAIL_INDEX(ABS(p_position.x), 1 << 20);
+ ERR_FAIL_INDEX(ABS(p_position.y), 1 << 20);
+ ERR_FAIL_INDEX(ABS(p_position.z), 1 << 20);
IndexKey key;
- key.x = p_x;
- key.y = p_y;
- key.z = p_z;
+ key.x = p_position.x;
+ key.y = p_position.y;
+ key.z = p_position.z;
OctantKey ok;
- ok.x = p_x / octant_size;
- ok.y = p_y / octant_size;
- ok.z = p_z / octant_size;
+ ok.x = p_position.x / octant_size;
+ ok.y = p_position.y / octant_size;
+ ok.z = p_position.z / octant_size;
if (p_item < 0) {
//erase
@@ -313,7 +293,6 @@ void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) {
SceneTree *st = SceneTree::get_singleton();
if (st && st->is_debugging_collisions_hint()) {
-
g->collision_debug = RenderingServer::get_singleton()->mesh_create();
g->collision_debug_instance = RenderingServer::get_singleton()->instance_create();
RenderingServer::get_singleton()->instance_set_base(g->collision_debug_instance, g->collision_debug);
@@ -339,57 +318,56 @@ void GridMap::set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot) {
cell_map[key] = c;
}
-int GridMap::get_cell_item(int p_x, int p_y, int p_z) const {
-
- ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, INVALID_CELL_ITEM);
- ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, INVALID_CELL_ITEM);
- ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, INVALID_CELL_ITEM);
+int GridMap::get_cell_item(const Vector3i &p_position) const {
+ ERR_FAIL_INDEX_V(ABS(p_position.x), 1 << 20, INVALID_CELL_ITEM);
+ ERR_FAIL_INDEX_V(ABS(p_position.y), 1 << 20, INVALID_CELL_ITEM);
+ ERR_FAIL_INDEX_V(ABS(p_position.z), 1 << 20, INVALID_CELL_ITEM);
IndexKey key;
- key.x = p_x;
- key.y = p_y;
- key.z = p_z;
+ key.x = p_position.x;
+ key.y = p_position.y;
+ key.z = p_position.z;
- if (!cell_map.has(key))
+ if (!cell_map.has(key)) {
return INVALID_CELL_ITEM;
+ }
return cell_map[key].item;
}
-int GridMap::get_cell_item_orientation(int p_x, int p_y, int p_z) const {
-
- ERR_FAIL_INDEX_V(ABS(p_x), 1 << 20, -1);
- ERR_FAIL_INDEX_V(ABS(p_y), 1 << 20, -1);
- ERR_FAIL_INDEX_V(ABS(p_z), 1 << 20, -1);
+int GridMap::get_cell_item_orientation(const Vector3i &p_position) const {
+ ERR_FAIL_INDEX_V(ABS(p_position.x), 1 << 20, -1);
+ ERR_FAIL_INDEX_V(ABS(p_position.y), 1 << 20, -1);
+ ERR_FAIL_INDEX_V(ABS(p_position.z), 1 << 20, -1);
IndexKey key;
- key.x = p_x;
- key.y = p_y;
- key.z = p_z;
+ key.x = p_position.x;
+ key.y = p_position.y;
+ key.z = p_position.z;
- if (!cell_map.has(key))
+ if (!cell_map.has(key)) {
return -1;
+ }
return cell_map[key].rot;
}
-Vector3 GridMap::world_to_map(const Vector3 &p_world_pos) const {
- Vector3 map_pos = p_world_pos / cell_size;
- map_pos.x = floor(map_pos.x);
- map_pos.y = floor(map_pos.y);
- map_pos.z = floor(map_pos.z);
- return map_pos;
+Vector3i GridMap::world_to_map(const Vector3 &p_world_position) const {
+ Vector3 map_position = p_world_position / cell_size;
+ map_position.x = floor(map_position.x);
+ map_position.y = floor(map_position.y);
+ map_position.z = floor(map_position.z);
+ return Vector3i(map_position);
}
-Vector3 GridMap::map_to_world(int p_x, int p_y, int p_z) const {
+Vector3 GridMap::map_to_world(const Vector3i &p_map_position) const {
Vector3 offset = _get_offset();
Vector3 world_pos(
- p_x * cell_size.x + offset.x,
- p_y * cell_size.y + offset.y,
- p_z * cell_size.z + offset.z);
+ p_map_position.x * cell_size.x + offset.x,
+ p_map_position.y * cell_size.y + offset.y,
+ p_map_position.z * cell_size.z + offset.z);
return world_pos;
}
void GridMap::_octant_transform(const OctantKey &p_key) {
-
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
PhysicsServer3D::get_singleton()->body_set_state(g.static_body, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
@@ -406,15 +384,15 @@ void GridMap::_octant_transform(const OctantKey &p_key) {
bool GridMap::_octant_update(const OctantKey &p_key) {
ERR_FAIL_COND_V(!octant_map.has(p_key), false);
Octant &g = *octant_map[p_key];
- if (!g.dirty)
+ if (!g.dirty) {
return false;
+ }
//erase body shapes
PhysicsServer3D::get_singleton()->body_clear_shapes(g.static_body);
//erase body shapes debug
if (g.collision_debug.is_valid()) {
-
RS::get_singleton()->mesh_clear(g.collision_debug);
}
@@ -427,7 +405,6 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
//erase multimeshes
for (int i = 0; i < g.multimesh_instances.size(); i++) {
-
RS::get_singleton()->free(g.multimesh_instances[i].instance);
RS::get_singleton()->free(g.multimesh_instances[i].multimesh);
}
@@ -450,12 +427,12 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
Map<int, List<Pair<Transform, IndexKey>>> multimesh_items;
for (Set<IndexKey>::Element *E = g.cells.front(); E; E = E->next()) {
-
ERR_CONTINUE(!cell_map.has(E->get()));
const Cell &c = cell_map[E->get()];
- if (!mesh_library.is_valid() || !mesh_library->has_item(c.item))
+ if (!mesh_library.is_valid() || !mesh_library->has_item(c.item)) {
continue;
+ }
Vector3 cellpos = Vector3(E->get().x, E->get().y, E->get().z);
Vector3 ofs = _get_offset();
@@ -482,8 +459,9 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
// add the item's shape at given xform to octant's static_body
for (int i = 0; i < shapes.size(); i++) {
// add the item's shape
- if (!shapes[i].shape.is_valid())
+ if (!shapes[i].shape.is_valid()) {
continue;
+ }
PhysicsServer3D::get_singleton()->body_add_shape(g.static_body, shapes[i].shape->get_rid(), xform * shapes[i].local_transform);
if (g.collision_debug.is_valid()) {
shapes.write[i].shape->add_vertices_to_array(col_debug, xform * shapes[i].local_transform);
@@ -509,7 +487,6 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
//update multimeshes, only if not baked
if (baked_meshes.size() == 0) {
-
for (Map<int, List<Pair<Transform, IndexKey>>>::Element *E = multimesh_items.front(); E; E = E->next()) {
Octant::MultimeshInstance mmi;
@@ -548,7 +525,6 @@ bool GridMap::_octant_update(const OctantKey &p_key) {
}
if (col_debug.size()) {
-
Array arr;
arr.resize(RS::ARRAY_MAX);
arr[RS::ARRAY_VERTEX] = col_debug;
@@ -573,7 +549,6 @@ void GridMap::_reset_physic_bodies_collision_filters() {
}
void GridMap::_octant_enter_world(const OctantKey &p_key) {
-
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
PhysicsServer3D::get_singleton()->body_set_state(g.static_body, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
@@ -591,7 +566,6 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) {
if (navigation && mesh_library.is_valid()) {
for (Map<IndexKey, Octant::NavMesh>::Element *F = g.navmesh_ids.front(); F; F = F->next()) {
-
if (cell_map.has(F->key()) && F->get().region.is_valid() == false) {
Ref<NavigationMesh> nm = mesh_library->get_item_navmesh(cell_map[F->key()].item);
if (nm.is_valid()) {
@@ -607,14 +581,12 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) {
}
void GridMap::_octant_exit_world(const OctantKey &p_key) {
-
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
PhysicsServer3D::get_singleton()->body_set_state(g.static_body, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
PhysicsServer3D::get_singleton()->body_set_space(g.static_body, RID());
if (g.collision_debug_instance.is_valid()) {
-
RS::get_singleton()->instance_set_scenario(g.collision_debug_instance, RID());
}
@@ -624,7 +596,6 @@ void GridMap::_octant_exit_world(const OctantKey &p_key) {
if (navigation) {
for (Map<IndexKey, Octant::NavMesh>::Element *F = g.navmesh_ids.front(); F; F = F->next()) {
-
if (F->get().region.is_valid()) {
NavigationServer3D::get_singleton()->free(F->get().region);
F->get().region = RID();
@@ -634,14 +605,15 @@ void GridMap::_octant_exit_world(const OctantKey &p_key) {
}
void GridMap::_octant_clean_up(const OctantKey &p_key) {
-
ERR_FAIL_COND(!octant_map.has(p_key));
Octant &g = *octant_map[p_key];
- if (g.collision_debug.is_valid())
+ if (g.collision_debug.is_valid()) {
RS::get_singleton()->free(g.collision_debug);
- if (g.collision_debug_instance.is_valid())
+ }
+ if (g.collision_debug_instance.is_valid()) {
RS::get_singleton()->free(g.collision_debug_instance);
+ }
PhysicsServer3D::get_singleton()->free(g.static_body);
@@ -654,7 +626,6 @@ void GridMap::_octant_clean_up(const OctantKey &p_key) {
//erase multimeshes
for (int i = 0; i < g.multimesh_instances.size(); i++) {
-
RS::get_singleton()->free(g.multimesh_instances[i].instance);
RS::get_singleton()->free(g.multimesh_instances[i].multimesh);
}
@@ -662,11 +633,8 @@ void GridMap::_octant_clean_up(const OctantKey &p_key) {
}
void GridMap::_notification(int p_what) {
-
switch (p_what) {
-
case NOTIFICATION_ENTER_WORLD: {
-
Node3D *c = this;
while (c) {
navigation = Object::cast_to<Navigation3D>(c);
@@ -690,10 +658,10 @@ void GridMap::_notification(int p_what) {
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
-
Transform new_xform = get_global_transform();
- if (new_xform == last_transform)
+ if (new_xform == last_transform) {
break;
+ }
//update run
for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
_octant_transform(E->key());
@@ -707,7 +675,6 @@ void GridMap::_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_WORLD: {
-
for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
_octant_exit_world(E->key());
}
@@ -729,8 +696,9 @@ void GridMap::_notification(int p_what) {
}
void GridMap::_update_visibility() {
- if (!is_inside_tree())
+ if (!is_inside_tree()) {
return;
+ }
_change_notify("visible");
@@ -738,37 +706,35 @@ void GridMap::_update_visibility() {
Octant *octant = e->value();
for (int i = 0; i < octant->multimesh_instances.size(); i++) {
const Octant::MultimeshInstance &mi = octant->multimesh_instances[i];
- RS::get_singleton()->instance_set_visible(mi.instance, is_visible());
+ RS::get_singleton()->instance_set_visible(mi.instance, is_visible_in_tree());
}
}
}
void GridMap::_queue_octants_dirty() {
-
- if (awaiting_update)
+ if (awaiting_update) {
return;
+ }
MessageQueue::get_singleton()->push_call(this, "_update_octants_callback");
awaiting_update = true;
}
void GridMap::_recreate_octant_data() {
-
recreating_octants = true;
Map<IndexKey, Cell> cell_copy = cell_map;
_clear_internal();
for (Map<IndexKey, Cell>::Element *E = cell_copy.front(); E; E = E->next()) {
-
- set_cell_item(E->key().x, E->key().y, E->key().z, E->get().item, E->get().rot);
+ set_cell_item(Vector3i(E->key()), E->get().item, E->get().rot);
}
recreating_octants = false;
}
void GridMap::_clear_internal() {
-
for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
- if (is_inside_world())
+ if (is_inside_world()) {
_octant_exit_world(E->key());
+ }
_octant_clean_up(E->key());
memdelete(E->get());
@@ -779,24 +745,21 @@ void GridMap::_clear_internal() {
}
void GridMap::clear() {
-
_clear_internal();
clear_baked_meshes();
}
void GridMap::resource_changed(const RES &p_res) {
-
_recreate_octant_data();
}
void GridMap::_update_octants_callback() {
-
- if (!awaiting_update)
+ if (!awaiting_update) {
return;
+ }
List<OctantKey> to_delete;
for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
-
if (_octant_update(E->key())) {
to_delete.push_back(E->key());
}
@@ -812,7 +775,6 @@ void GridMap::_update_octants_callback() {
}
void GridMap::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &GridMap::set_collision_layer);
ClassDB::bind_method(D_METHOD("get_collision_layer"), &GridMap::get_collision_layer);
@@ -837,12 +799,12 @@ void GridMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_octant_size", "size"), &GridMap::set_octant_size);
ClassDB::bind_method(D_METHOD("get_octant_size"), &GridMap::get_octant_size);
- ClassDB::bind_method(D_METHOD("set_cell_item", "x", "y", "z", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_cell_item", "x", "y", "z"), &GridMap::get_cell_item);
- ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "x", "y", "z"), &GridMap::get_cell_item_orientation);
+ ClassDB::bind_method(D_METHOD("set_cell_item", "position", "item", "orientation"), &GridMap::set_cell_item, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_cell_item", "position"), &GridMap::get_cell_item);
+ ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "position"), &GridMap::get_cell_item_orientation);
- ClassDB::bind_method(D_METHOD("world_to_map", "pos"), &GridMap::world_to_map);
- ClassDB::bind_method(D_METHOD("map_to_world", "x", "y", "z"), &GridMap::map_to_world);
+ ClassDB::bind_method(D_METHOD("world_to_map", "world_position"), &GridMap::world_to_map);
+ ClassDB::bind_method(D_METHOD("map_to_world", "map_position"), &GridMap::map_to_world);
ClassDB::bind_method(D_METHOD("_update_octants_callback"), &GridMap::_update_octants_callback);
ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &GridMap::resource_changed);
@@ -885,11 +847,12 @@ void GridMap::_bind_methods() {
}
void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) {
-
- if (!p_enabled && !clip)
+ if (!p_enabled && !clip) {
return;
- if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis)
+ }
+ if (clip && p_enabled && clip_floor == p_floor && p_clip_above == clip_above && p_axis == clip_axis) {
return;
+ }
clip = p_enabled;
clip_floor = p_floor;
@@ -898,7 +861,6 @@ void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::
//make it all update
for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
-
Octant *g = E->get();
g->dirty = true;
}
@@ -907,18 +869,15 @@ void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::
}
void GridMap::set_cell_scale(float p_scale) {
-
cell_scale = p_scale;
_recreate_octant_data();
}
float GridMap::get_cell_scale() const {
-
return cell_scale;
}
Array GridMap::get_used_cells() const {
-
Array a;
a.resize(cell_map.size());
int i = 0;
@@ -931,21 +890,22 @@ Array GridMap::get_used_cells() const {
}
Array GridMap::get_meshes() {
-
- if (mesh_library.is_null())
+ if (mesh_library.is_null()) {
return Array();
+ }
Vector3 ofs = _get_offset();
Array meshes;
for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
-
int id = E->get().item;
- if (!mesh_library->has_item(id))
+ if (!mesh_library->has_item(id)) {
continue;
+ }
Ref<Mesh> mesh = mesh_library->get_item_mesh(id);
- if (mesh.is_null())
+ if (mesh.is_null()) {
continue;
+ }
IndexKey ik = E->key();
@@ -973,7 +933,6 @@ Vector3 GridMap::_get_offset() const {
}
void GridMap::clear_baked_meshes() {
-
for (int i = 0; i < baked_meshes.size(); i++) {
RS::get_singleton()->free(baked_meshes[i].instance);
}
@@ -983,24 +942,25 @@ void GridMap::clear_baked_meshes() {
}
void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texel_size) {
-
- if (!mesh_library.is_valid())
+ if (!mesh_library.is_valid()) {
return;
+ }
//generate
Map<OctantKey, Map<Ref<Material>, Ref<SurfaceTool>>> surface_map;
for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
-
IndexKey key = E->key();
int item = E->get().item;
- if (!mesh_library->has_item(item))
+ if (!mesh_library->has_item(item)) {
continue;
+ }
Ref<Mesh> mesh = mesh_library->get_item_mesh(item);
- if (!mesh.is_valid())
+ if (!mesh.is_valid()) {
continue;
+ }
Vector3 cellpos = Vector3(key.x, key.y, key.z);
Vector3 ofs = _get_offset();
@@ -1023,9 +983,9 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
Map<Ref<Material>, Ref<SurfaceTool>> &mat_map = surface_map[ok];
for (int i = 0; i < mesh->get_surface_count(); i++) {
-
- if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
+ if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue;
+ }
Ref<Material> surf_mat = mesh->surface_get_material(i);
if (!mat_map.has(surf_mat)) {
@@ -1041,7 +1001,6 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
}
for (Map<OctantKey, Map<Ref<Material>, Ref<SurfaceTool>>>::Element *E = surface_map.front(); E; E = E->next()) {
-
Ref<ArrayMesh> mesh;
mesh.instance();
for (Map<Ref<Material>, Ref<SurfaceTool>>::Element *F = E->get().front(); F; F = F->next()) {
@@ -1068,7 +1027,6 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe
}
Array GridMap::get_bake_meshes() {
-
if (!baked_meshes.size()) {
make_baked_meshes(true);
}
@@ -1083,13 +1041,11 @@ Array GridMap::get_bake_meshes() {
}
RID GridMap::get_bake_mesh_instance(int p_idx) {
-
ERR_FAIL_INDEX_V(p_idx, baked_meshes.size(), RID());
return baked_meshes[p_idx].instance;
}
GridMap::GridMap() {
-
collision_layer = 1;
collision_mask = 1;
@@ -1113,9 +1069,9 @@ GridMap::GridMap() {
}
GridMap::~GridMap() {
-
- if (!mesh_library.is_null())
+ if (!mesh_library.is_null()) {
mesh_library->unregister_owner(this);
+ }
clear();
}
diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h
index 3f3da09fe9..48ad95f9ff 100644
--- a/modules/gridmap/grid_map.h
+++ b/modules/gridmap/grid_map.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,7 +40,6 @@
//should scale better with hardware that supports instancing
class GridMap : public Node3D {
-
GDCLASS(GridMap, Node3D);
enum {
@@ -49,7 +48,6 @@ class GridMap : public Node3D {
};
union IndexKey {
-
struct {
int16_t x;
int16_t y;
@@ -58,10 +56,18 @@ class GridMap : public Node3D {
uint64_t key;
_FORCE_INLINE_ bool operator<(const IndexKey &p_key) const {
-
return key < p_key.key;
}
+ _FORCE_INLINE_ operator Vector3i() const {
+ return Vector3i(x, y, z);
+ }
+
+ IndexKey(Vector3i p_vector) {
+ x = (int16_t)p_vector.x;
+ y = (int16_t)p_vector.y;
+ z = (int16_t)p_vector.z;
+ }
IndexKey() { key = 0; }
};
@@ -69,7 +75,6 @@ class GridMap : public Node3D {
* @brief A Cell is a single cell in the cube map space; it is defined by its coordinates and the populating Item, identified by int id.
*/
union Cell {
-
struct {
unsigned int item : 16;
unsigned int rot : 5;
@@ -89,7 +94,6 @@ class GridMap : public Node3D {
* A GridMap can have multiple Octants.
*/
struct Octant {
-
struct NavMesh {
RID region;
Transform xform;
@@ -118,7 +122,6 @@ class GridMap : public Node3D {
};
union OctantKey {
-
struct {
int16_t x;
int16_t y;
@@ -129,7 +132,6 @@ class GridMap : public Node3D {
uint64_t key;
_FORCE_INLINE_ bool operator<(const OctantKey &p_key) const {
-
return key < p_key.key;
}
@@ -165,7 +167,6 @@ class GridMap : public Node3D {
void _recreate_octant_data();
struct BakeLight {
-
RS::LightType type;
Vector3 pos;
Vector3 dir;
@@ -173,7 +174,6 @@ class GridMap : public Node3D {
};
_FORCE_INLINE_ Vector3 _octant_get_offset(const OctantKey &p_key) const {
-
return Vector3(p_key.x, p_key.y, p_key.z) * cell_size * octant_size;
}
@@ -243,12 +243,12 @@ public:
void set_center_z(bool p_enable);
bool get_center_z() const;
- void set_cell_item(int p_x, int p_y, int p_z, int p_item, int p_rot = 0);
- int get_cell_item(int p_x, int p_y, int p_z) const;
- int get_cell_item_orientation(int p_x, int p_y, int p_z) const;
+ void set_cell_item(const Vector3i &p_position, int p_item, int p_rot = 0);
+ int get_cell_item(const Vector3i &p_position) const;
+ int get_cell_item_orientation(const Vector3i &p_position) const;
- Vector3 world_to_map(const Vector3 &p_world_pos) const;
- Vector3 map_to_world(int p_x, int p_y, int p_z) const;
+ Vector3i world_to_map(const Vector3 &p_world_position) const;
+ Vector3 map_to_world(const Vector3i &p_map_position) const;
void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X);
diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp
index 9abbac6a0b..4732a3f62d 100644
--- a/modules/gridmap/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/grid_map_editor_plugin.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,28 +35,25 @@
#include "editor/plugins/node_3d_editor_plugin.h"
#include "scene/3d/camera_3d.h"
-#include "core/math/geometry.h"
#include "core/os/keyboard.h"
#include "scene/main/window.h"
void GridMapEditor::_node_removed(Node *p_node) {
-
- if (p_node == node)
+ if (p_node == node) {
node = nullptr;
+ }
}
void GridMapEditor::_configure() {
-
- if (!node)
+ if (!node) {
return;
+ }
update_grid();
}
void GridMapEditor::_menu_option(int p_option) {
-
switch (p_option) {
-
case MENU_OPTION_PREV_LEVEL: {
floor->set_value(floor->get_value() - 1);
} break;
@@ -66,7 +63,6 @@ void GridMapEditor::_menu_option(int p_option) {
} break;
case MENU_OPTION_LOCK_VIEW: {
-
int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW);
lock_view = !options->get_popup()->is_item_checked(index);
@@ -75,10 +71,8 @@ void GridMapEditor::_menu_option(int p_option) {
case MENU_OPTION_CLIP_DISABLED:
case MENU_OPTION_CLIP_ABOVE:
case MENU_OPTION_CLIP_BELOW: {
-
clip_mode = ClipMode(p_option - MENU_OPTION_CLIP_DISABLED);
for (int i = 0; i < 3; i++) {
-
int index = options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED + i);
options->get_popup()->set_item_checked(index, i == clip_mode);
}
@@ -88,7 +82,6 @@ void GridMapEditor::_menu_option(int p_option) {
case MENU_OPTION_X_AXIS:
case MENU_OPTION_Y_AXIS:
case MENU_OPTION_Z_AXIS: {
-
int new_axis = p_option - MENU_OPTION_X_AXIS;
for (int i = 0; i < 3; i++) {
int idx = options->get_popup()->get_item_index(MENU_OPTION_X_AXIS + i);
@@ -114,10 +107,8 @@ void GridMapEditor::_menu_option(int p_option) {
} break;
case MENU_OPTION_CURSOR_ROTATE_Y: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -131,10 +122,8 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_X: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -148,10 +137,8 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_Z: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -165,10 +152,8 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Y: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 1, 0), Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -182,10 +167,8 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_X: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(1, 0, 0), Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -199,10 +182,8 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Z: {
-
Basis r;
if (input_action == INPUT_PASTE) {
-
r.set_orthogonal_index(paste_indicator.orientation);
r.rotate(Vector3(0, 0, 1), Math_PI / 2.0);
paste_indicator.orientation = r.get_orthogonal_index();
@@ -216,9 +197,7 @@ void GridMapEditor::_menu_option(int p_option) {
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_CLEAR_ROTATION: {
-
if (input_action == INPUT_PASTE) {
-
paste_indicator.orientation = 0;
_update_paste_indicator();
break;
@@ -235,8 +214,9 @@ void GridMapEditor::_menu_option(int p_option) {
case MENU_OPTION_SELECTION_DUPLICATE:
case MENU_OPTION_SELECTION_CUT: {
- if (!(selection.active && input_action == INPUT_NONE))
+ if (!(selection.active && input_action == INPUT_NONE)) {
break;
+ }
_set_clipboard_data();
@@ -253,15 +233,17 @@ void GridMapEditor::_menu_option(int p_option) {
_update_paste_indicator();
} break;
case MENU_OPTION_SELECTION_CLEAR: {
- if (!selection.active)
+ if (!selection.active) {
break;
+ }
_delete_selection();
} break;
case MENU_OPTION_SELECTION_FILL: {
- if (!selection.active)
+ if (!selection.active) {
return;
+ }
_fill_selection();
@@ -273,7 +255,6 @@ void GridMapEditor::_menu_option(int p_option) {
}
void GridMapEditor::_update_cursor_transform() {
-
cursor_transform = Transform();
cursor_transform.origin = cursor_origin;
cursor_transform.basis.set_orthogonal_index(cursor_rot);
@@ -291,7 +272,6 @@ void GridMapEditor::_update_selection_transform() {
xf_zero.basis.set_zero();
if (!selection.active) {
-
RenderingServer::get_singleton()->instance_set_transform(selection_instance, xf_zero);
for (int i = 0; i < 3; i++) {
RenderingServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf_zero);
@@ -309,18 +289,17 @@ void GridMapEditor::_update_selection_transform() {
if (i != edit_axis || (edit_floor[edit_axis] < selection.begin[edit_axis]) || (edit_floor[edit_axis] > selection.end[edit_axis] + 1)) {
RenderingServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf_zero);
} else {
-
Vector3 scale = (selection.end - selection.begin + Vector3(1, 1, 1));
scale[edit_axis] = 1.0;
- Vector3 pos = selection.begin;
- pos[edit_axis] = edit_floor[edit_axis];
+ Vector3 position = selection.begin;
+ position[edit_axis] = edit_floor[edit_axis];
scale *= node->get_cell_size();
- pos *= node->get_cell_size();
+ position *= node->get_cell_size();
Transform xf2;
xf2.basis.scale(scale);
- xf2.origin = pos;
+ xf2.origin = position;
RenderingServer::get_singleton()->instance_set_transform(selection_level_instance[i], xf2);
}
@@ -328,24 +307,26 @@ void GridMapEditor::_update_selection_transform() {
}
void GridMapEditor::_validate_selection() {
-
- if (!selection.active)
+ if (!selection.active) {
return;
+ }
selection.begin = selection.click;
selection.end = selection.current;
- if (selection.begin.x > selection.end.x)
+ if (selection.begin.x > selection.end.x) {
SWAP(selection.begin.x, selection.end.x);
- if (selection.begin.y > selection.end.y)
+ }
+ if (selection.begin.y > selection.end.y) {
SWAP(selection.begin.y, selection.end.y);
- if (selection.begin.z > selection.end.z)
+ }
+ if (selection.begin.z > selection.end.z) {
SWAP(selection.begin.z, selection.end.z);
+ }
_update_selection_transform();
}
void GridMapEditor::_set_selection(bool p_active, const Vector3 &p_begin, const Vector3 &p_end) {
-
selection.active = p_active;
selection.begin = p_begin;
selection.end = p_end;
@@ -363,17 +344,20 @@ void GridMapEditor::_set_selection(bool p_active, const Vector3 &p_begin, const
}
bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, bool p_click) {
-
- if (!spatial_editor)
+ if (!spatial_editor) {
return false;
+ }
- if (selected_palette < 0 && input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE)
+ if (selected_palette < 0 && input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE) {
return false;
+ }
Ref<MeshLibrary> mesh_library = node->get_mesh_library();
- if (mesh_library.is_null())
+ if (mesh_library.is_null()) {
return false;
- if (input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE && !mesh_library->has_item(selected_palette))
+ }
+ if (input_action != INPUT_PICK && input_action != INPUT_SELECT && input_action != INPUT_PASTE && !mesh_library->has_item(selected_palette)) {
return false;
+ }
Camera3D *camera = p_camera;
Vector3 from = camera->project_ray_origin(p_point);
@@ -388,30 +372,30 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b
p.d = edit_floor[edit_axis] * node->get_cell_size()[edit_axis];
Vector3 inters;
- if (!p.intersects_segment(from, from + normal * settings_pick_distance->get_value(), &inters))
+ if (!p.intersects_segment(from, from + normal * settings_pick_distance->get_value(), &inters)) {
return false;
+ }
// Make sure the intersection is inside the frustum planes, to avoid
// Painting on invisible regions.
for (int i = 0; i < planes.size(); i++) {
-
Plane fp = local_xform.xform(planes[i]);
- if (fp.is_point_over(inters))
+ if (fp.is_point_over(inters)) {
return false;
+ }
}
int cell[3];
float cell_size[3] = { node->get_cell_size().x, node->get_cell_size().y, node->get_cell_size().z };
for (int i = 0; i < 3; i++) {
-
- if (i == edit_axis)
+ if (i == edit_axis) {
cell[i] = edit_floor[i];
- else {
-
+ } else {
cell[i] = inters[i] / node->get_cell_size()[i];
- if (inters[i] < 0)
+ if (inters[i] < 0) {
cell[i] -= 1; // Compensate negative.
+ }
grid_ofs[i] = cell[i] * cell_size[i];
}
}
@@ -419,7 +403,6 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b
RS::get_singleton()->instance_set_transform(grid_instance[edit_axis], node->get_global_transform() * edit_grid_xform);
if (cursor_instance.is_valid()) {
-
cursor_origin = (Vector3(cell[0], cell[1], cell[2]) + Vector3(0.5 * node->get_center_x(), 0.5 * node->get_center_y(), 0.5 * node->get_center_z())) * node->get_cell_size();
cursor_visible = true;
@@ -431,22 +414,20 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b
}
if (input_action == INPUT_PASTE) {
-
- paste_indicator.current = Vector3(cell[0], cell[1], cell[2]);
+ paste_indicator.current = Vector3i(cell[0], cell[1], cell[2]);
_update_paste_indicator();
} else if (input_action == INPUT_SELECT) {
-
- selection.current = Vector3(cell[0], cell[1], cell[2]);
- if (p_click)
+ selection.current = Vector3i(cell[0], cell[1], cell[2]);
+ if (p_click) {
selection.click = selection.current;
+ }
selection.active = true;
_validate_selection();
return true;
} else if (input_action == INPUT_PICK) {
-
- int item = node->get_cell_item(cell[0], cell[1], cell[2]);
+ int item = node->get_cell_item(Vector3i(cell[0], cell[1], cell[2]));
if (item >= 0) {
selected_palette = item;
mesh_library_palette->set_current(item);
@@ -457,23 +438,23 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b
}
if (input_action == INPUT_PAINT) {
SetItem si;
- si.pos = Vector3(cell[0], cell[1], cell[2]);
+ si.position = Vector3i(cell[0], cell[1], cell[2]);
si.new_value = selected_palette;
si.new_orientation = cursor_rot;
- si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]);
- si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]);
+ si.old_value = node->get_cell_item(Vector3i(cell[0], cell[1], cell[2]));
+ si.old_orientation = node->get_cell_item_orientation(Vector3i(cell[0], cell[1], cell[2]));
set_items.push_back(si);
- node->set_cell_item(cell[0], cell[1], cell[2], selected_palette, cursor_rot);
+ node->set_cell_item(Vector3i(cell[0], cell[1], cell[2]), selected_palette, cursor_rot);
return true;
} else if (input_action == INPUT_ERASE) {
SetItem si;
- si.pos = Vector3(cell[0], cell[1], cell[2]);
+ si.position = Vector3i(cell[0], cell[1], cell[2]);
si.new_value = -1;
si.new_orientation = 0;
- si.old_value = node->get_cell_item(cell[0], cell[1], cell[2]);
- si.old_orientation = node->get_cell_item_orientation(cell[0], cell[1], cell[2]);
+ si.old_value = node->get_cell_item(Vector3i(cell[0], cell[1], cell[2]));
+ si.old_orientation = node->get_cell_item_orientation(Vector3i(cell[0], cell[1], cell[2]));
set_items.push_back(si);
- node->set_cell_item(cell[0], cell[1], cell[2], -1);
+ node->set_cell_item(Vector3i(cell[0], cell[1], cell[2]), -1);
return true;
}
@@ -481,19 +462,17 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b
}
void GridMapEditor::_delete_selection() {
-
- if (!selection.active)
+ if (!selection.active) {
return;
+ }
undo_redo->create_action(TTR("GridMap Delete Selection"));
for (int i = selection.begin.x; i <= selection.end.x; i++) {
-
for (int j = selection.begin.y; j <= selection.end.y; j++) {
-
for (int k = selection.begin.z; k <= selection.end.z; k++) {
-
- undo_redo->add_do_method(node, "set_cell_item", i, j, k, GridMap::INVALID_CELL_ITEM);
- undo_redo->add_undo_method(node, "set_cell_item", i, j, k, node->get_cell_item(i, j, k), node->get_cell_item_orientation(i, j, k));
+ Vector3i selected = Vector3i(i, j, k);
+ undo_redo->add_do_method(node, "set_cell_item", selected, GridMap::INVALID_CELL_ITEM);
+ undo_redo->add_undo_method(node, "set_cell_item", selected, node->get_cell_item(selected), node->get_cell_item_orientation(selected));
}
}
}
@@ -503,19 +482,17 @@ void GridMapEditor::_delete_selection() {
}
void GridMapEditor::_fill_selection() {
-
- if (!selection.active)
+ if (!selection.active) {
return;
+ }
undo_redo->create_action(TTR("GridMap Fill Selection"));
for (int i = selection.begin.x; i <= selection.end.x; i++) {
-
for (int j = selection.begin.y; j <= selection.end.y; j++) {
-
for (int k = selection.begin.z; k <= selection.end.z; k++) {
-
- undo_redo->add_do_method(node, "set_cell_item", i, j, k, selected_palette, cursor_rot);
- undo_redo->add_undo_method(node, "set_cell_item", i, j, k, node->get_cell_item(i, j, k), node->get_cell_item_orientation(i, j, k));
+ Vector3i selected = Vector3i(i, j, k);
+ undo_redo->add_do_method(node, "set_cell_item", selected, selected_palette, cursor_rot);
+ undo_redo->add_undo_method(node, "set_cell_item", selected, node->get_cell_item(selected), node->get_cell_item_orientation(selected));
}
}
}
@@ -525,9 +502,7 @@ void GridMapEditor::_fill_selection() {
}
void GridMapEditor::_clear_clipboard_data() {
-
for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) {
-
RenderingServer::get_singleton()->free(E->get().instance);
}
@@ -535,27 +510,25 @@ void GridMapEditor::_clear_clipboard_data() {
}
void GridMapEditor::_set_clipboard_data() {
-
_clear_clipboard_data();
Ref<MeshLibrary> meshLibrary = node->get_mesh_library();
for (int i = selection.begin.x; i <= selection.end.x; i++) {
-
for (int j = selection.begin.y; j <= selection.end.y; j++) {
-
for (int k = selection.begin.z; k <= selection.end.z; k++) {
-
- int itm = node->get_cell_item(i, j, k);
- if (itm == GridMap::INVALID_CELL_ITEM)
+ Vector3i selected = Vector3i(i, j, k);
+ int itm = node->get_cell_item(selected);
+ if (itm == GridMap::INVALID_CELL_ITEM) {
continue;
+ }
Ref<Mesh> mesh = meshLibrary->get_item_mesh(itm);
ClipboardItem item;
item.cell_item = itm;
- item.grid_offset = Vector3(i, j, k) - selection.begin;
- item.orientation = node->get_cell_item_orientation(i, j, k);
+ item.grid_offset = Vector3(selected) - selection.begin;
+ item.orientation = node->get_cell_item_orientation(selected);
item.instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
clipboard_items.push_back(item);
@@ -565,9 +538,7 @@ void GridMapEditor::_set_clipboard_data() {
}
void GridMapEditor::_update_paste_indicator() {
-
if (input_action != INPUT_PASTE) {
-
Transform xf;
xf.basis.set_zero();
RenderingServer::get_singleton()->instance_set_transform(paste_instance, xf);
@@ -587,7 +558,6 @@ void GridMapEditor::_update_paste_indicator() {
RenderingServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf);
for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) {
-
ClipboardItem &item = E->get();
xf = Transform();
@@ -604,7 +574,6 @@ void GridMapEditor::_update_paste_indicator() {
}
void GridMapEditor::_do_paste() {
-
int idx = options->get_popup()->get_item_index(MENU_OPTION_PASTE_SELECTS);
bool reselect = options->get_popup()->is_item_checked(idx);
@@ -615,21 +584,19 @@ void GridMapEditor::_do_paste() {
undo_redo->create_action(TTR("GridMap Paste Selection"));
for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) {
-
ClipboardItem &item = E->get();
- Vector3 pos = rot.xform(item.grid_offset) + paste_indicator.begin + ofs;
+ Vector3 position = rot.xform(item.grid_offset) + paste_indicator.begin + ofs;
Basis orm;
orm.set_orthogonal_index(item.orientation);
orm = rot * orm;
- undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, item.cell_item, orm.get_orthogonal_index());
- undo_redo->add_undo_method(node, "set_cell_item", pos.x, pos.y, pos.z, node->get_cell_item(pos.x, pos.y, pos.z), node->get_cell_item_orientation(pos.x, pos.y, pos.z));
+ undo_redo->add_do_method(node, "set_cell_item", position, item.cell_item, orm.get_orthogonal_index());
+ undo_redo->add_undo_method(node, "set_cell_item", position, node->get_cell_item(position), node->get_cell_item_orientation(position));
}
if (reselect) {
-
undo_redo->add_do_method(this, "_set_selection", true, paste_indicator.begin + ofs, paste_indicator.end + ofs);
undo_redo->add_undo_method(this, "_set_selection", selection.active, selection.begin, selection.end);
}
@@ -647,15 +614,16 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
-
if (mb->get_button_index() == BUTTON_WHEEL_UP && (mb->get_command() || mb->get_shift())) {
- if (mb->is_pressed())
+ if (mb->is_pressed()) {
floor->set_value(floor->get_value() + mb->get_factor());
+ }
return true; // Eaten.
} else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && (mb->get_command() || mb->get_shift())) {
- if (mb->is_pressed())
+ if (mb->is_pressed()) {
floor->set_value(floor->get_value() - mb->get_factor());
+ }
return true;
}
@@ -664,7 +632,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
if ((nav_scheme == Node3DEditorViewport::NAVIGATION_MAYA || nav_scheme == Node3DEditorViewport::NAVIGATION_MODO) && mb->get_alt()) {
input_action = INPUT_NONE;
} else if (mb->get_button_index() == BUTTON_LEFT) {
-
bool can_edit = (node && node->get_mesh_library().is_valid());
if (input_action == INPUT_PASTE) {
_do_paste();
@@ -698,20 +665,16 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
return do_input_action(p_camera, Point2(mb->get_position().x, mb->get_position().y), true);
} else {
-
if ((mb->get_button_index() == BUTTON_RIGHT && input_action == INPUT_ERASE) || (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_PAINT)) {
-
if (set_items.size()) {
undo_redo->create_action(TTR("GridMap Paint"));
for (List<SetItem>::Element *E = set_items.front(); E; E = E->next()) {
-
const SetItem &si = E->get();
- undo_redo->add_do_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.new_value, si.new_orientation);
+ undo_redo->add_do_method(node, "set_cell_item", si.position, si.new_value, si.new_orientation);
}
for (List<SetItem>::Element *E = set_items.back(); E; E = E->prev()) {
-
const SetItem &si = E->get();
- undo_redo->add_undo_method(node, "set_cell_item", si.pos.x, si.pos.y, si.pos.z, si.old_value, si.old_orientation);
+ undo_redo->add_undo_method(node, "set_cell_item", si.position, si.old_value, si.old_orientation);
}
undo_redo->commit_action();
@@ -722,7 +685,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
}
if (mb->get_button_index() == BUTTON_LEFT && input_action == INPUT_SELECT) {
-
undo_redo->create_action("GridMap Selection");
undo_redo->add_do_method(this, "_set_selection", selection.active, selection.begin, selection.end);
undo_redo->add_undo_method(this, "_set_selection", last_selection.active, last_selection.begin, last_selection.end);
@@ -730,7 +692,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
}
if (mb->get_button_index() == BUTTON_LEFT && input_action != INPUT_NONE) {
-
set_items.clear();
input_action = INPUT_NONE;
return true;
@@ -745,7 +706,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid()) {
-
return do_input_action(p_camera, mm->get_position(), false);
}
@@ -754,7 +714,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
if (k.is_valid()) {
if (k->is_pressed()) {
if (k->get_keycode() == KEY_ESCAPE) {
-
if (input_action == INPUT_PASTE) {
_clear_clipboard_data();
input_action = INPUT_NONE;
@@ -765,7 +724,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
return true;
} else {
selected_palette = -1;
- mesh_library_palette->unselect_all();
+ mesh_library_palette->deselect_all();
update_palette();
_update_cursor_instance();
return true;
@@ -773,7 +732,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
}
if (k->get_shift() && selection.active && input_action != INPUT_PASTE) {
-
if (k->get_keycode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_PREV_LEVEL))) {
selection.click[edit_axis]--;
_validate_selection();
@@ -790,7 +748,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
Ref<InputEventPanGesture> pan_gesture = p_event;
if (pan_gesture.is_valid()) {
-
if (pan_gesture->get_alt() && (pan_gesture->get_command() || pan_gesture->get_shift())) {
const real_t delta = pan_gesture->get_delta().y * 0.5;
accumulated_floor_delta += delta;
@@ -811,7 +768,6 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In
}
struct _CGMEItemSort {
-
String name;
int id;
_FORCE_INLINE_ bool operator<(const _CGMEItemSort &r_it) const { return name < r_it.name; }
@@ -840,11 +796,9 @@ void GridMapEditor::_text_changed(const String &p_text) {
}
void GridMapEditor::_sbox_input(const Ref<InputEvent> &p_ie) {
-
const Ref<InputEventKey> k = p_ie;
if (k.is_valid() && (k->get_keycode() == KEY_UP || k->get_keycode() == KEY_DOWN || k->get_keycode() == KEY_PAGEUP || k->get_keycode() == KEY_PAGEDOWN)) {
-
// Forward the key input to the ItemList so it can be scrolled
mesh_library_palette->call("_gui_input", k);
search_box->accept_event();
@@ -852,12 +806,10 @@ void GridMapEditor::_sbox_input(const Ref<InputEvent> &p_ie) {
}
void GridMapEditor::_mesh_library_palette_input(const Ref<InputEvent> &p_ie) {
-
const Ref<InputEventMouseButton> mb = p_ie;
// Zoom in/out using Ctrl + mouse wheel
if (mb.is_valid() && mb->is_pressed() && mb->get_command()) {
-
if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) {
size_slider->set_value(size_slider->get_value() + 0.2);
}
@@ -911,7 +863,6 @@ void GridMapEditor::update_palette() {
List<_CGMEItemSort> il;
for (int i = 0; i < ids.size(); i++) {
-
_CGMEItemSort is;
is.id = ids[i];
is.name = mesh_library->get_item_name(ids[i]);
@@ -932,8 +883,9 @@ void GridMapEditor::update_palette() {
name = "#" + itos(id);
}
- if (filter != "" && !filter.is_subsequence_ofi(name))
+ if (filter != "" && !filter.is_subsequence_ofi(name)) {
continue;
+ }
mesh_library_palette->add_item("");
if (!preview.is_null()) {
@@ -954,8 +906,9 @@ void GridMapEditor::update_palette() {
}
void GridMapEditor::edit(GridMap *p_gridmap) {
- if (!p_gridmap && node)
+ if (!p_gridmap && node) {
node->disconnect("cell_size_changed", callable_mp(this, &GridMapEditor::_draw_grids));
+ }
node = p_gridmap;
@@ -993,16 +946,15 @@ void GridMapEditor::edit(GridMap *p_gridmap) {
}
void GridMapEditor::_update_clip() {
-
node->set_meta("_editor_clip_", clip_mode);
- if (clip_mode == CLIP_DISABLED)
+ if (clip_mode == CLIP_DISABLED) {
node->set_clip(false);
- else
+ } else {
node->set_clip(true, clip_mode == CLIP_ABOVE, edit_floor[edit_axis], edit_axis);
+ }
}
void GridMapEditor::update_grid() {
-
grid_xform.origin.x -= 1; // Force update in hackish way.
grid_ofs[edit_axis] = edit_floor[edit_axis] * node->get_cell_size()[edit_axis];
@@ -1031,7 +983,6 @@ void GridMapEditor::_draw_grids(const Vector3 &cell_size) {
Vector<Color> grid_colors[3];
for (int i = 0; i < 3; i++) {
-
Vector3 axis;
axis[i] = 1;
Vector3 axis_n1;
@@ -1040,9 +991,7 @@ void GridMapEditor::_draw_grids(const Vector3 &cell_size) {
axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3];
for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) {
-
for (int k = -GRID_CURSOR_SIZE; k <= GRID_CURSOR_SIZE; k++) {
-
Vector3 p = axis_n1 * j + axis_n2 * k;
float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2);
@@ -1074,21 +1023,22 @@ void GridMapEditor::_draw_grids(const Vector3 &cell_size) {
}
void GridMapEditor::_notification(int p_what) {
-
switch (p_what) {
-
case NOTIFICATION_ENTER_TREE: {
get_tree()->connect("node_removed", callable_mp(this, &GridMapEditor::_node_removed));
mesh_library_palette->connect("item_selected", callable_mp(this, &GridMapEditor::_item_selected_cbk));
for (int i = 0; i < 3; i++) {
-
grid[i] = RS::get_singleton()->mesh_create();
grid_instance[i] = RS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ RenderingServer::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
selection_level_instance[i] = RenderingServer::get_singleton()->instance_create2(selection_level_mesh[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ RenderingServer::get_singleton()->instance_set_layer_mask(selection_level_instance[i], 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
}
selection_instance = RenderingServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ RenderingServer::get_singleton()->instance_set_layer_mask(selection_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
paste_instance = RenderingServer::get_singleton()->instance_create2(paste_mesh, get_tree()->get_root()->get_world_3d()->get_scenario());
+ RenderingServer::get_singleton()->instance_set_layer_mask(paste_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER);
_update_selection_transform();
_update_paste_indicator();
@@ -1099,7 +1049,6 @@ void GridMapEditor::_notification(int p_what) {
_clear_clipboard_data();
for (int i = 0; i < 3; i++) {
-
RS::get_singleton()->free(grid_instance[i]);
RS::get_singleton()->free(grid[i]);
grid_instance[i] = RID();
@@ -1122,17 +1071,16 @@ void GridMapEditor::_notification(int p_what) {
if (xf != grid_xform) {
for (int i = 0; i < 3; i++) {
-
RS::get_singleton()->instance_set_transform(grid_instance[i], xf * edit_grid_xform);
}
grid_xform = xf;
}
Ref<MeshLibrary> cgmt = node->get_mesh_library();
- if (cgmt.operator->() != last_mesh_library)
+ if (cgmt.operator->() != last_mesh_library) {
update_palette();
+ }
if (lock_view) {
-
EditorNode *editor = Object::cast_to<EditorNode>(get_tree()->get_root()->get_child(0));
Plane p;
@@ -1141,8 +1089,9 @@ void GridMapEditor::_notification(int p_what) {
p = node->get_transform().xform(p); // plane to snap
Node3DEditorPlugin *sep = Object::cast_to<Node3DEditorPlugin>(editor->get_editor_plugin_screen());
- if (sep)
+ if (sep) {
sep->snap_cursor_to_plane(p);
+ }
}
} break;
@@ -1158,16 +1107,15 @@ void GridMapEditor::_update_cursor_instance() {
return;
}
- if (cursor_instance.is_valid())
+ if (cursor_instance.is_valid()) {
RenderingServer::get_singleton()->free(cursor_instance);
+ }
cursor_instance = RID();
if (selected_palette >= 0) {
-
if (node && !node->get_mesh_library().is_null()) {
Ref<Mesh> mesh = node->get_mesh_library()->get_item_mesh(selected_palette);
if (!mesh.is_null() && mesh->get_rid().is_valid()) {
-
cursor_instance = RenderingServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world_3d()->get_scenario());
RenderingServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform);
}
@@ -1182,9 +1130,9 @@ void GridMapEditor::_item_selected_cbk(int idx) {
}
void GridMapEditor::_floor_changed(float p_value) {
-
- if (updating)
+ if (updating) {
return;
+ }
edit_floor[edit_axis] = p_value;
node->set_meta("_editor_floor_", Vector3(edit_floor[0], edit_floor[1], edit_floor[2]));
@@ -1198,13 +1146,11 @@ void GridMapEditor::_floor_mouse_exited() {
}
void GridMapEditor::_bind_methods() {
-
ClassDB::bind_method("_configure", &GridMapEditor::_configure);
ClassDB::bind_method("_set_selection", &GridMapEditor::_set_selection);
}
GridMapEditor::GridMapEditor(EditorNode *p_editor) {
-
input_action = INPUT_NONE;
editor = p_editor;
undo_redo = p_editor->get_undo_redo();
@@ -1302,14 +1248,16 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
search_box->connect("text_changed", callable_mp(this, &GridMapEditor::_text_changed));
search_box->connect("gui_input", callable_mp(this, &GridMapEditor::_sbox_input));
- mode_thumbnail = memnew(ToolButton);
+ mode_thumbnail = memnew(Button);
+ mode_thumbnail->set_flat(true);
mode_thumbnail->set_toggle_mode(true);
mode_thumbnail->set_pressed(true);
mode_thumbnail->set_icon(p_editor->get_gui_base()->get_theme_icon("FileThumbnail", "EditorIcons"));
hb->add_child(mode_thumbnail);
mode_thumbnail->connect("pressed", callable_mp(this, &GridMapEditor::_set_display_mode), varray(DISPLAY_THUMBNAIL));
- mode_list = memnew(ToolButton);
+ mode_list = memnew(Button);
+ mode_list->set_flat(true);
mode_list->set_toggle_mode(true);
mode_list->set_pressed(false);
mode_list->set_icon(p_editor->get_gui_base()->get_theme_icon("FileList", "EditorIcons"));
@@ -1340,7 +1288,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
info_message->set_align(Label::ALIGN_CENTER);
info_message->set_autowrap(true);
info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
- info_message->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);
+ info_message->set_anchors_and_offsets_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE);
mesh_library_palette->add_child(info_message);
edit_axis = Vector3::AXIS_Y;
@@ -1364,22 +1312,20 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
Vector<Vector3> square[3];
for (int i = 0; i < 6; i++) {
-
Vector3 face_points[4];
for (int j = 0; j < 4; j++) {
-
float v[3];
v[0] = 1.0;
v[1] = 1 - 2 * ((j >> 1) & 1);
v[2] = v[1] * (1 - 2 * (j & 1));
for (int k = 0; k < 3; k++) {
-
- if (i < 3)
+ if (i < 3) {
face_points[j][(i + k) % 3] = v[k];
- else
+ } else {
face_points[3 - j][(i + k) % 3] = -v[k];
+ }
}
}
@@ -1393,7 +1339,6 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
}
for (int i = 0; i < 12; i++) {
-
AABB base(Vector3(0, 0, 0), Vector3(1, 1, 1));
Vector3 a, b;
base.get_edge(i, a, b);
@@ -1404,9 +1349,8 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
for (int i = 0; i < 3; i++) {
Vector3 points[4];
for (int j = 0; j < 4; j++) {
-
- static const bool orderx[4] = { 0, 1, 1, 0 };
- static const bool ordery[4] = { 0, 0, 1, 1 };
+ static const bool orderx[4] = { false, true, true, false };
+ static const bool ordery[4] = { false, false, true, true };
Vector3 sp;
if (orderx[j]) {
@@ -1420,7 +1364,6 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
}
for (int j = 0; j < 4; j++) {
-
Vector3 ofs;
ofs[i] += 0.01;
square[i].push_back(points[j] - ofs);
@@ -1487,36 +1430,39 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
}
GridMapEditor::~GridMapEditor() {
-
_clear_clipboard_data();
for (int i = 0; i < 3; i++) {
-
- if (grid[i].is_valid())
+ if (grid[i].is_valid()) {
RenderingServer::get_singleton()->free(grid[i]);
- if (grid_instance[i].is_valid())
+ }
+ if (grid_instance[i].is_valid()) {
RenderingServer::get_singleton()->free(grid_instance[i]);
- if (cursor_instance.is_valid())
+ }
+ if (cursor_instance.is_valid()) {
RenderingServer::get_singleton()->free(cursor_instance);
- if (selection_level_instance[i].is_valid())
+ }
+ if (selection_level_instance[i].is_valid()) {
RenderingServer::get_singleton()->free(selection_level_instance[i]);
- if (selection_level_mesh[i].is_valid())
+ }
+ if (selection_level_mesh[i].is_valid()) {
RenderingServer::get_singleton()->free(selection_level_mesh[i]);
+ }
}
RenderingServer::get_singleton()->free(selection_mesh);
- if (selection_instance.is_valid())
+ if (selection_instance.is_valid()) {
RenderingServer::get_singleton()->free(selection_instance);
+ }
RenderingServer::get_singleton()->free(paste_mesh);
- if (paste_instance.is_valid())
+ if (paste_instance.is_valid()) {
RenderingServer::get_singleton()->free(paste_instance);
+ }
}
void GridMapEditorPlugin::_notification(int p_what) {
-
if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
-
switch ((int)EditorSettings::get_singleton()->get("editors/grid_map/editor_side")) {
case 0: { // Left.
Node3DEditor::get_singleton()->get_palette_split()->move_child(grid_map_editor, 0);
@@ -1529,23 +1475,19 @@ void GridMapEditorPlugin::_notification(int p_what) {
}
void GridMapEditorPlugin::edit(Object *p_object) {
-
grid_map_editor->edit(Object::cast_to<GridMap>(p_object));
}
bool GridMapEditorPlugin::handles(Object *p_object) const {
-
return p_object->is_class("GridMap");
}
void GridMapEditorPlugin::make_visible(bool p_visible) {
-
if (p_visible) {
grid_map_editor->show();
grid_map_editor->spatial_editor_hb->show();
grid_map_editor->set_process(true);
} else {
-
grid_map_editor->spatial_editor_hb->hide();
grid_map_editor->hide();
grid_map_editor->edit(nullptr);
@@ -1554,7 +1496,6 @@ void GridMapEditorPlugin::make_visible(bool p_visible) {
}
GridMapEditorPlugin::GridMapEditorPlugin(EditorNode *p_node) {
-
editor = p_node;
EDITOR_DEF("editors/grid_map/editor_side", 1);
diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h
index fd880e8b7b..0c0ec64680 100644
--- a/modules/gridmap/grid_map_editor_plugin.h
+++ b/modules/gridmap/grid_map_editor_plugin.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
-#include "editor/pane_drag.h"
#include "grid_map.h"
class Node3DEditorPlugin;
@@ -42,12 +41,10 @@ class GridMapEditor : public VBoxContainer {
GDCLASS(GridMapEditor, VBoxContainer);
enum {
-
GRID_CURSOR_SIZE = 50
};
enum InputAction {
-
INPUT_NONE,
INPUT_PAINT,
INPUT_ERASE,
@@ -57,7 +54,6 @@ class GridMapEditor : public VBoxContainer {
};
enum ClipMode {
-
CLIP_DISABLED,
CLIP_ABOVE,
CLIP_BELOW
@@ -74,8 +70,8 @@ class GridMapEditor : public VBoxContainer {
MenuButton *options;
SpinBox *floor;
double accumulated_floor_delta;
- ToolButton *mode_thumbnail;
- ToolButton *mode_list;
+ Button *mode_thumbnail;
+ Button *mode_list;
LineEdit *search_box;
HSlider *size_slider;
HBoxContainer *spatial_editor_hb;
@@ -85,8 +81,7 @@ class GridMapEditor : public VBoxContainer {
Label *spin_box_label;
struct SetItem {
-
- Vector3 pos;
+ Vector3i position;
int new_value;
int new_orientation;
int old_value;
@@ -95,7 +90,7 @@ class GridMapEditor : public VBoxContainer {
List<SetItem> set_items;
- GridMap *node;
+ GridMap *node = nullptr;
MeshLibrary *last_mesh_library;
ClipMode clip_mode;
@@ -133,7 +128,6 @@ class GridMapEditor : public VBoxContainer {
bool updating;
struct Selection {
-
Vector3 click;
Vector3 current;
Vector3 begin;
@@ -143,7 +137,6 @@ class GridMapEditor : public VBoxContainer {
Selection last_selection;
struct PasteIndicator {
-
Vector3 click;
Vector3 current;
Vector3 begin;
@@ -162,7 +155,6 @@ class GridMapEditor : public VBoxContainer {
int cursor_rot;
enum Menu {
-
MENU_OPTION_NEXT_LEVEL,
MENU_OPTION_PREV_LEVEL,
MENU_OPTION_LOCK_VIEW,
@@ -191,7 +183,6 @@ class GridMapEditor : public VBoxContainer {
Node3DEditorPlugin *spatial_editor;
struct AreaDisplay {
-
RID mesh;
RID instance;
};
@@ -251,7 +242,6 @@ public:
};
class GridMapEditorPlugin : public EditorPlugin {
-
GDCLASS(GridMapEditorPlugin, EditorPlugin);
GridMapEditor *grid_map_editor;
@@ -261,12 +251,12 @@ protected:
void _notification(int p_what);
public:
- virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) { return grid_map_editor->forward_spatial_input_event(p_camera, p_event); }
- virtual String get_name() const { return "GridMap"; }
- bool has_main_screen() const { return false; }
- virtual void edit(Object *p_object);
- virtual bool handles(Object *p_object) const;
- virtual void make_visible(bool p_visible);
+ virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override { return grid_map_editor->forward_spatial_input_event(p_camera, p_event); }
+ virtual String get_name() const override { return "GridMap"; }
+ bool has_main_screen() const override { return false; }
+ virtual void edit(Object *p_object) override;
+ virtual bool handles(Object *p_object) const override;
+ virtual void make_visible(bool p_visible) override;
GridMapEditorPlugin(EditorNode *p_node);
~GridMapEditorPlugin();
diff --git a/modules/gridmap/icons/GridMap.svg b/modules/gridmap/icons/GridMap.svg
index eafe1211f2..7a36fd888c 100644
--- a/modules/gridmap/icons/GridMap.svg
+++ b/modules/gridmap/icons/GridMap.svg
@@ -1,5 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path 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"/></svg>
diff --git a/modules/gridmap/register_types.cpp b/modules/gridmap/register_types.cpp
index afd51945ab..5680664213 100644
--- a/modules/gridmap/register_types.cpp
+++ b/modules/gridmap/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "register_types.h"
#ifndef _3D_DISABLED
-#include "core/class_db.h"
+#include "core/object/class_db.h"
#include "grid_map.h"
#include "grid_map_editor_plugin.h"
#endif
void register_gridmap_types() {
-
#ifndef _3D_DISABLED
ClassDB::register_class<GridMap>();
#ifdef TOOLS_ENABLED
diff --git a/modules/gridmap/register_types.h b/modules/gridmap/register_types.h
index c0e3c39ca8..b977f4c5da 100644
--- a/modules/gridmap/register_types.h
+++ b/modules/gridmap/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp
index c03ae4ab1f..9d6a399eff 100644
--- a/modules/hdr/image_loader_hdr.cpp
+++ b/modules/hdr/image_loader_hdr.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,10 +31,9 @@
#include "image_loader_hdr.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
String header = f->get_token();
ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + ".");
@@ -42,8 +41,9 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
while (true) {
String line = f->get_line();
ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_UNRECOGNIZED);
- if (line == "") // empty line indicates end of header
+ if (line == "") { // empty line indicates end of header
break;
+ }
if (line.begins_with("FORMAT=")) { // leave option to implement other commands
ERR_FAIL_COND_V_MSG(line != "FORMAT=32-bit_rle_rgbe", ERR_FILE_UNRECOGNIZED, "Only 32-bit_rle_rgbe is supported for HDR files.");
} else if (!line.begins_with("#")) { // not comment
@@ -68,7 +68,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
imgdata.resize(height * width * sizeof(uint32_t));
{
-
uint8_t *w = imgdata.ptrw();
uint8_t *ptr = (uint8_t *)w;
@@ -109,12 +108,14 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
// Run
int value = f->get_8();
count -= 128;
- for (int z = 0; z < count; ++z)
+ for (int z = 0; z < count; ++z) {
ptr[(j * width + i++) * 4 + k] = uint8_t(value);
+ }
} else {
// Dump
- for (int z = 0; z < count; ++z)
+ for (int z = 0; z < count; ++z) {
ptr[(j * width + i++) * 4 + k] = f->get_8();
+ }
}
}
}
@@ -123,7 +124,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
//convert
for (int i = 0; i < width * height; i++) {
-
float exp = pow(2.0f, ptr[3] - 128.0f);
Color c(
@@ -146,7 +146,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
}
void ImageLoaderHDR::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("hdr");
}
diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h
index a5f1f9c387..33fcdd1245 100644
--- a/modules/hdr/image_loader_hdr.h
+++ b/modules/hdr/image_loader_hdr.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/io/image_loader.h"
class ImageLoaderHDR : public ImageFormatLoader {
-
public:
virtual Error load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/hdr/register_types.cpp b/modules/hdr/register_types.cpp
index 5f2d1578c5..5a4a1993e0 100644
--- a/modules/hdr/register_types.cpp
+++ b/modules/hdr/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
static ImageLoaderHDR *image_loader_hdr = nullptr;
void register_hdr_types() {
-
image_loader_hdr = memnew(ImageLoaderHDR);
ImageLoader::add_image_format_loader(image_loader_hdr);
}
void unregister_hdr_types() {
-
memdelete(image_loader_hdr);
}
diff --git a/modules/hdr/register_types.h b/modules/hdr/register_types.h
index 02441516ec..c85bc84dce 100644
--- a/modules/hdr/register_types.h
+++ b/modules/hdr/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/icloud/SCsub b/modules/icloud/SCsub
new file mode 100644
index 0000000000..805a484600
--- /dev/null
+++ b/modules/icloud/SCsub
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_icloud = env_modules.Clone()
+
+# (iOS) Enable module support
+env_icloud.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])
+
+# (iOS) Build as separate static library
+modules_sources = []
+env_icloud.add_source_files(modules_sources, "*.cpp")
+env_icloud.add_source_files(modules_sources, "*.mm")
+mod_lib = env_modules.add_library("#bin/libgodot_icloud_module" + env["LIBSUFFIX"], modules_sources)
diff --git a/modules/icloud/config.py b/modules/icloud/config.py
new file mode 100644
index 0000000000..e68603fc93
--- /dev/null
+++ b/modules/icloud/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return platform == "iphone"
+
+
+def configure(env):
+ pass
diff --git a/modules/icloud/icloud.gdip b/modules/icloud/icloud.gdip
new file mode 100644
index 0000000000..9f81be8a34
--- /dev/null
+++ b/modules/icloud/icloud.gdip
@@ -0,0 +1,17 @@
+[config]
+name="iCloud"
+binary="icloud_lib.a"
+
+initialization="register_icloud_types"
+deinitialization="unregister_icloud_types"
+
+[dependencies]
+linked=[]
+embedded=[]
+system=[]
+
+capabilities=[]
+
+files=[]
+
+[plist]
diff --git a/modules/icloud/icloud.h b/modules/icloud/icloud.h
new file mode 100644
index 0000000000..7b7aa52b63
--- /dev/null
+++ b/modules/icloud/icloud.h
@@ -0,0 +1,60 @@
+/*************************************************************************/
+/* icloud.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 ICLOUD_H
+#define ICLOUD_H
+
+#include "core/object/class_db.h"
+
+class ICloud : public Object {
+ GDCLASS(ICloud, Object);
+
+ static ICloud *instance;
+ static void _bind_methods();
+
+ List<Variant> pending_events;
+
+public:
+ Error remove_key(String p_param);
+ Array set_key_values(Dictionary p_params);
+ Variant get_key_value(String p_param);
+ Error synchronize_key_values();
+ Variant get_all_key_values();
+
+ int get_pending_event_count();
+ Variant pop_pending_event();
+
+ static ICloud *get_singleton();
+
+ ICloud();
+ ~ICloud();
+};
+
+#endif
diff --git a/modules/icloud/icloud.mm b/modules/icloud/icloud.mm
new file mode 100644
index 0000000000..937ef38018
--- /dev/null
+++ b/modules/icloud/icloud.mm
@@ -0,0 +1,345 @@
+/*************************************************************************/
+/* icloud.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "icloud.h"
+
+#import "platform/iphone/app_delegate.h"
+
+#import <Foundation/Foundation.h>
+
+ICloud *ICloud::instance = NULL;
+
+void ICloud::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("remove_key"), &ICloud::remove_key);
+
+ ClassDB::bind_method(D_METHOD("set_key_values"), &ICloud::set_key_values);
+ ClassDB::bind_method(D_METHOD("get_key_value"), &ICloud::get_key_value);
+
+ ClassDB::bind_method(D_METHOD("synchronize_key_values"), &ICloud::synchronize_key_values);
+ ClassDB::bind_method(D_METHOD("get_all_key_values"), &ICloud::get_all_key_values);
+
+ ClassDB::bind_method(D_METHOD("get_pending_event_count"), &ICloud::get_pending_event_count);
+ ClassDB::bind_method(D_METHOD("pop_pending_event"), &ICloud::pop_pending_event);
+};
+
+int ICloud::get_pending_event_count() {
+ return pending_events.size();
+};
+
+Variant ICloud::pop_pending_event() {
+ Variant front = pending_events.front()->get();
+ pending_events.pop_front();
+
+ return front;
+};
+
+ICloud *ICloud::get_singleton() {
+ return instance;
+};
+
+//convert from apple's abstract type to godot's abstract type....
+Variant nsobject_to_variant(NSObject *object) {
+ if ([object isKindOfClass:[NSString class]]) {
+ const char *str = [(NSString *)object UTF8String];
+ return String::utf8(str != NULL ? str : "");
+ } else if ([object isKindOfClass:[NSData class]]) {
+ PackedByteArray ret;
+ NSData *data = (NSData *)object;
+ if ([data length] > 0) {
+ ret.resize([data length]);
+ {
+ // PackedByteArray::Write w = ret.write();
+ copymem((void *)ret.ptr(), [data bytes], [data length]);
+ }
+ }
+ return ret;
+ } else if ([object isKindOfClass:[NSArray class]]) {
+ Array result;
+ NSArray *array = (NSArray *)object;
+ for (NSUInteger i = 0; i < [array count]; ++i) {
+ NSObject *value = [array objectAtIndex:i];
+ result.push_back(nsobject_to_variant(value));
+ }
+ return result;
+ } else if ([object isKindOfClass:[NSDictionary class]]) {
+ Dictionary result;
+ NSDictionary *dic = (NSDictionary *)object;
+
+ NSArray *keys = [dic allKeys];
+ int count = [keys count];
+ for (int i = 0; i < count; ++i) {
+ NSObject *k = [keys objectAtIndex:i];
+ NSObject *v = [dic objectForKey:k];
+
+ result[nsobject_to_variant(k)] = nsobject_to_variant(v);
+ }
+ return result;
+ } else if ([object isKindOfClass:[NSNumber class]]) {
+ //Every type except numbers can reliably identify its type. The following is comparing to the *internal* representation, which isn't guaranteed to match the type that was used to create it, and is not advised, particularly when dealing with potential platform differences (ie, 32/64 bit)
+ //To avoid errors, we'll cast as broadly as possible, and only return int or float.
+ //bool, char, int, uint, longlong -> int
+ //float, double -> float
+ NSNumber *num = (NSNumber *)object;
+ if (strcmp([num objCType], @encode(BOOL)) == 0) {
+ return Variant((int)[num boolValue]);
+ } else if (strcmp([num objCType], @encode(char)) == 0) {
+ return Variant((int)[num charValue]);
+ } else if (strcmp([num objCType], @encode(int)) == 0) {
+ return Variant([num intValue]);
+ } else if (strcmp([num objCType], @encode(unsigned int)) == 0) {
+ return Variant((int)[num unsignedIntValue]);
+ } else if (strcmp([num objCType], @encode(long long)) == 0) {
+ return Variant((int)[num longValue]);
+ } else if (strcmp([num objCType], @encode(float)) == 0) {
+ return Variant([num floatValue]);
+ } else if (strcmp([num objCType], @encode(double)) == 0) {
+ return Variant((float)[num doubleValue]);
+ } else {
+ return Variant();
+ }
+ } else if ([object isKindOfClass:[NSDate class]]) {
+ //this is a type that icloud supports...but how did you submit it in the first place?
+ //I guess this is a type that *might* show up, if you were, say, trying to make your game
+ //compatible with existing cloud data written by another engine's version of your game
+ WARN_PRINT("NSDate unsupported, returning null Variant");
+ return Variant();
+ } else if ([object isKindOfClass:[NSNull class]] or object == nil) {
+ return Variant();
+ } else {
+ WARN_PRINT("Trying to convert unknown NSObject type to Variant");
+ return Variant();
+ }
+}
+
+NSObject *variant_to_nsobject(Variant v) {
+ if (v.get_type() == Variant::STRING) {
+ return [[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()];
+ } else if (v.get_type() == Variant::FLOAT) {
+ return [NSNumber numberWithDouble:(double)v];
+ } else if (v.get_type() == Variant::INT) {
+ return [NSNumber numberWithLongLong:(long)(int)v];
+ } else if (v.get_type() == Variant::BOOL) {
+ return [NSNumber numberWithBool:BOOL((bool)v)];
+ } else if (v.get_type() == Variant::DICTIONARY) {
+ NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
+ Dictionary dic = v;
+ Array keys = dic.keys();
+ for (int i = 0; i < keys.size(); ++i) {
+ NSString *key = [[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()];
+ NSObject *value = variant_to_nsobject(dic[keys[i]]);
+
+ if (key == NULL || value == NULL) {
+ return NULL;
+ }
+
+ [result setObject:value forKey:key];
+ }
+ return result;
+ } else if (v.get_type() == Variant::ARRAY) {
+ NSMutableArray *result = [[NSMutableArray alloc] init];
+ Array arr = v;
+ for (int i = 0; i < arr.size(); ++i) {
+ NSObject *value = variant_to_nsobject(arr[i]);
+ if (value == NULL) {
+ //trying to add something unsupported to the array. cancel the whole array
+ return NULL;
+ }
+ [result addObject:value];
+ }
+ return result;
+ } else if (v.get_type() == Variant::PACKED_BYTE_ARRAY) {
+ PackedByteArray arr = v;
+ // PackedByteArray::Read r = arr.read();
+ NSData *result = [NSData dataWithBytes:arr.ptr() length:arr.size()];
+ return result;
+ }
+ WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type()) + "'").utf8().get_data());
+ return NULL;
+}
+
+Error ICloud::remove_key(String p_param) {
+ NSString *key = [[NSString alloc] initWithUTF8String:p_param.utf8().get_data()];
+
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+
+ if (![[store dictionaryRepresentation] objectForKey:key]) {
+ return ERR_INVALID_PARAMETER;
+ }
+
+ [store removeObjectForKey:key];
+ return OK;
+}
+
+//return an array of the keys that could not be set
+Array ICloud::set_key_values(Dictionary p_params) {
+ Array keys = p_params.keys();
+
+ Array error_keys;
+
+ for (int i = 0; i < keys.size(); ++i) {
+ String variant_key = keys[i];
+ Variant variant_value = p_params[variant_key];
+
+ NSString *key = [[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()];
+ if (key == NULL) {
+ error_keys.push_back(variant_key);
+ continue;
+ }
+
+ NSObject *value = variant_to_nsobject(variant_value);
+
+ if (value == NULL) {
+ error_keys.push_back(variant_key);
+ continue;
+ }
+
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+ [store setObject:value forKey:key];
+ }
+
+ return error_keys;
+}
+
+Variant ICloud::get_key_value(String p_param) {
+ NSString *key = [[NSString alloc] initWithUTF8String:p_param.utf8().get_data()];
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+
+ if (![[store dictionaryRepresentation] objectForKey:key]) {
+ return Variant();
+ }
+
+ Variant result = nsobject_to_variant([[store dictionaryRepresentation] objectForKey:key]);
+
+ return result;
+}
+
+Variant ICloud::get_all_key_values() {
+ Dictionary result;
+
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+ NSDictionary *store_dictionary = [store dictionaryRepresentation];
+
+ NSArray *keys = [store_dictionary allKeys];
+ int count = [keys count];
+ for (int i = 0; i < count; ++i) {
+ NSString *k = [keys objectAtIndex:i];
+ NSObject *v = [store_dictionary objectForKey:k];
+
+ const char *str = [k UTF8String];
+ if (str != NULL) {
+ result[String::utf8(str)] = nsobject_to_variant(v);
+ }
+ }
+
+ return result;
+}
+
+Error ICloud::synchronize_key_values() {
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+ BOOL result = [store synchronize];
+ if (result == YES) {
+ return OK;
+ } else {
+ return FAILED;
+ }
+}
+
+/*
+Error ICloud::initial_sync() {
+ //you sometimes have to write something to the store to get it to download new data. go apple!
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+ if ([store boolForKey:@"isb"])
+ {
+ [store setBool:NO forKey:@"isb"];
+ }
+ else
+ {
+ [store setBool:YES forKey:@"isb"];
+ }
+ return synchronize();
+}
+
+*/
+ICloud::ICloud() {
+ ERR_FAIL_COND(instance != NULL);
+ instance = this;
+ //connected = false;
+
+ [[NSNotificationCenter defaultCenter]
+ addObserverForName:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
+ object:[NSUbiquitousKeyValueStore defaultStore]
+ queue:nil
+ usingBlock:^(NSNotification *notification) {
+ NSDictionary *userInfo = [notification userInfo];
+ NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
+
+ Dictionary ret;
+ ret["type"] = "key_value_changed";
+
+ //PackedStringArray result_keys;
+ //Array result_values;
+ Dictionary keyValues;
+ String reason = "";
+
+ if (change == NSUbiquitousKeyValueStoreServerChange) {
+ reason = "server";
+ } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
+ reason = "initial_sync";
+ } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
+ reason = "quota_violation";
+ } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
+ reason = "account";
+ }
+
+ ret["reason"] = reason;
+
+ NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
+
+ NSArray *keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
+ for (NSString *key in keys) {
+ const char *str = [key UTF8String];
+ if (str == NULL) {
+ continue;
+ }
+
+ NSObject *object = [store objectForKey:key];
+
+ //figure out what kind of object it is
+ Variant value = nsobject_to_variant(object);
+
+ keyValues[String::utf8(str)] = value;
+ }
+
+ ret["changed_values"] = keyValues;
+ pending_events.push_back(ret);
+ }];
+}
+
+ICloud::~ICloud() {}
diff --git a/modules/icloud/icloud_module.cpp b/modules/icloud/icloud_module.cpp
new file mode 100644
index 0000000000..8a2c41a38c
--- /dev/null
+++ b/modules/icloud/icloud_module.cpp
@@ -0,0 +1,48 @@
+/*************************************************************************/
+/* icloud_module.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "icloud_module.h"
+
+#include "core/config/engine.h"
+
+#include "icloud.h"
+
+ICloud *icloud;
+
+void register_icloud_types() {
+ icloud = memnew(ICloud);
+ Engine::get_singleton()->add_singleton(Engine::Singleton("ICloud", icloud));
+}
+
+void unregister_icloud_types() {
+ if (icloud) {
+ memdelete(icloud);
+ }
+}
diff --git a/modules/icloud/icloud_module.h b/modules/icloud/icloud_module.h
new file mode 100644
index 0000000000..fb8b5fe66e
--- /dev/null
+++ b/modules/icloud/icloud_module.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* icloud_module.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+void register_icloud_types();
+void unregister_icloud_types();
diff --git a/modules/inappstore/SCsub b/modules/inappstore/SCsub
new file mode 100644
index 0000000000..cee6a256d5
--- /dev/null
+++ b/modules/inappstore/SCsub
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_inappstore = env_modules.Clone()
+
+# (iOS) Enable module support
+env_inappstore.Append(CCFLAGS=["-fmodules", "-fcxx-modules"])
+
+# (iOS) Build as separate static library
+modules_sources = []
+env_inappstore.add_source_files(modules_sources, "*.cpp")
+env_inappstore.add_source_files(modules_sources, "*.mm")
+mod_lib = env_modules.add_library("#bin/libgodot_inappstore_module" + env["LIBSUFFIX"], modules_sources)
diff --git a/modules/inappstore/config.py b/modules/inappstore/config.py
new file mode 100644
index 0000000000..e68603fc93
--- /dev/null
+++ b/modules/inappstore/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return platform == "iphone"
+
+
+def configure(env):
+ pass
diff --git a/modules/mono/glue/nodepath_glue.h b/modules/inappstore/in_app_store.h
index 727679c278..c66c306319 100644
--- a/modules/mono/glue/nodepath_glue.h
+++ b/modules/inappstore/in_app_store.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* nodepath_glue.h */
+/* in_app_store.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,41 +28,50 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef NODEPATH_GLUE_H
-#define NODEPATH_GLUE_H
+#ifndef IN_APP_STORE_H
+#define IN_APP_STORE_H
-#ifdef MONO_GLUE_ENABLED
+#include "core/object/class_db.h"
-#include "core/node_path.h"
+#ifdef __OBJC__
+@class GodotProductsDelegate;
+@class GodotTransactionsObserver;
-#include "../mono_gd/gd_mono_marshal.h"
+typedef GodotProductsDelegate InAppStoreProductDelegate;
+typedef GodotTransactionsObserver InAppStoreTransactionObserver;
+#else
+typedef void InAppStoreProductDelegate;
+typedef void InAppStoreTransactionObserver;
+#endif
-NodePath *godot_icall_NodePath_Ctor(MonoString *p_path);
+class InAppStore : public Object {
+ GDCLASS(InAppStore, Object);
-void godot_icall_NodePath_Dtor(NodePath *p_ptr);
+ static InAppStore *instance;
+ static void _bind_methods();
-MonoString *godot_icall_NodePath_operator_String(NodePath *p_np);
+ List<Variant> pending_events;
-MonoBoolean godot_icall_NodePath_is_absolute(NodePath *p_ptr);
+ InAppStoreProductDelegate *products_request_delegate;
+ InAppStoreTransactionObserver *transactions_observer;
-uint32_t godot_icall_NodePath_get_name_count(NodePath *p_ptr);
+public:
+ Error request_product_info(Dictionary p_params);
+ Error restore_purchases();
+ Error purchase(Dictionary p_params);
-MonoString *godot_icall_NodePath_get_name(NodePath *p_ptr, uint32_t p_idx);
+ int get_pending_event_count();
+ Variant pop_pending_event();
+ void finish_transaction(String product_id);
+ void set_auto_finish_transaction(bool b);
-uint32_t godot_icall_NodePath_get_subname_count(NodePath *p_ptr);
+ void _post_event(Variant p_event);
+ void _record_purchase(String product_id);
-MonoString *godot_icall_NodePath_get_subname(NodePath *p_ptr, uint32_t p_idx);
+ static InAppStore *get_singleton();
-MonoString *godot_icall_NodePath_get_concatenated_subnames(NodePath *p_ptr);
+ InAppStore();
+ ~InAppStore();
+};
-NodePath *godot_icall_NodePath_get_as_property_path(NodePath *p_ptr);
-
-MonoBoolean godot_icall_NodePath_is_empty(NodePath *p_ptr);
-
-// Register internal calls
-
-void godot_register_nodepath_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // NODEPATH_GLUE_H
+#endif
diff --git a/modules/inappstore/in_app_store.mm b/modules/inappstore/in_app_store.mm
new file mode 100644
index 0000000000..427808ae75
--- /dev/null
+++ b/modules/inappstore/in_app_store.mm
@@ -0,0 +1,411 @@
+/*************************************************************************/
+/* in_app_store.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "in_app_store.h"
+
+#import <Foundation/Foundation.h>
+#import <StoreKit/StoreKit.h>
+
+InAppStore *InAppStore::instance = NULL;
+
+@interface SKProduct (LocalizedPrice)
+
+@property(nonatomic, readonly) NSString *localizedPrice;
+
+@end
+
+//----------------------------------//
+// SKProduct extension
+//----------------------------------//
+@implementation SKProduct (LocalizedPrice)
+
+- (NSString *)localizedPrice {
+ NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
+ [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
+ [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
+ [numberFormatter setLocale:self.priceLocale];
+ NSString *formattedString = [numberFormatter stringFromNumber:self.price];
+ return formattedString;
+}
+
+@end
+
+@interface GodotProductsDelegate : NSObject <SKProductsRequestDelegate>
+
+@property(nonatomic, strong) NSMutableArray *loadedProducts;
+@property(nonatomic, strong) NSMutableArray *pendingRequests;
+
+- (void)performRequestWithProductIDs:(NSSet *)productIDs;
+- (Error)purchaseProductWithProductID:(NSString *)productID;
+- (void)reset;
+
+@end
+
+@implementation GodotProductsDelegate
+
+- (instancetype)init {
+ self = [super init];
+
+ if (self) {
+ [self godot_commonInit];
+ }
+
+ return self;
+}
+
+- (void)godot_commonInit {
+ self.loadedProducts = [NSMutableArray new];
+ self.pendingRequests = [NSMutableArray new];
+}
+
+- (void)performRequestWithProductIDs:(NSSet *)productIDs {
+ SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIDs];
+
+ request.delegate = self;
+ [self.pendingRequests addObject:request];
+ [request start];
+}
+
+- (Error)purchaseProductWithProductID:(NSString *)productID {
+ SKProduct *product = nil;
+
+ NSLog(@"searching for product!");
+
+ if (self.loadedProducts) {
+ for (SKProduct *storedProduct in self.loadedProducts) {
+ if ([storedProduct.productIdentifier isEqualToString:productID]) {
+ product = storedProduct;
+ break;
+ }
+ }
+ }
+
+ if (!product) {
+ return ERR_INVALID_PARAMETER;
+ }
+
+ NSLog(@"product found!");
+
+ SKPayment *payment = [SKPayment paymentWithProduct:product];
+ [[SKPaymentQueue defaultQueue] addPayment:payment];
+
+ NSLog(@"purchase sent!");
+
+ return OK;
+}
+
+- (void)reset {
+ [self.loadedProducts removeAllObjects];
+ [self.pendingRequests removeAllObjects];
+}
+
+- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
+ [self.pendingRequests removeObject:request];
+
+ Dictionary ret;
+ ret["type"] = "product_info";
+ ret["result"] = "error";
+ ret["error"] = String::utf8([error.localizedDescription UTF8String]);
+
+ InAppStore::get_singleton()->_post_event(ret);
+}
+
+- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
+ [self.pendingRequests removeObject:request];
+
+ NSArray *products = response.products;
+ [self.loadedProducts addObjectsFromArray:products];
+
+ Dictionary ret;
+ ret["type"] = "product_info";
+ ret["result"] = "ok";
+ PackedStringArray titles;
+ PackedStringArray descriptions;
+ PackedFloat32Array prices;
+ PackedStringArray ids;
+ PackedStringArray localized_prices;
+ PackedStringArray currency_codes;
+
+ for (NSUInteger i = 0; i < [products count]; i++) {
+ SKProduct *product = [products objectAtIndex:i];
+
+ const char *str = [product.localizedTitle UTF8String];
+ titles.push_back(String::utf8(str != NULL ? str : ""));
+
+ str = [product.localizedDescription UTF8String];
+ descriptions.push_back(String::utf8(str != NULL ? str : ""));
+ prices.push_back([product.price doubleValue]);
+ ids.push_back(String::utf8([product.productIdentifier UTF8String]));
+ localized_prices.push_back(String::utf8([product.localizedPrice UTF8String]));
+ currency_codes.push_back(String::utf8([[[product priceLocale] objectForKey:NSLocaleCurrencyCode] UTF8String]));
+ }
+
+ ret["titles"] = titles;
+ ret["descriptions"] = descriptions;
+ ret["prices"] = prices;
+ ret["ids"] = ids;
+ ret["localized_prices"] = localized_prices;
+ ret["currency_codes"] = currency_codes;
+
+ PackedStringArray invalid_ids;
+
+ for (NSString *ipid in response.invalidProductIdentifiers) {
+ invalid_ids.push_back(String::utf8([ipid UTF8String]));
+ }
+
+ ret["invalid_ids"] = invalid_ids;
+
+ InAppStore::get_singleton()->_post_event(ret);
+}
+
+@end
+
+@interface GodotTransactionsObserver : NSObject <SKPaymentTransactionObserver>
+
+@property(nonatomic, assign) BOOL shouldAutoFinishTransactions;
+@property(nonatomic, strong) NSMutableDictionary *pendingTransactions;
+
+- (void)finishTransactionWithProductID:(NSString *)productID;
+- (void)reset;
+
+@end
+
+@implementation GodotTransactionsObserver
+
+- (instancetype)init {
+ self = [super init];
+
+ if (self) {
+ [self godot_commonInit];
+ }
+
+ return self;
+}
+
+- (void)godot_commonInit {
+ self.pendingTransactions = [NSMutableDictionary new];
+}
+
+- (void)finishTransactionWithProductID:(NSString *)productID {
+ SKPaymentTransaction *transaction = self.pendingTransactions[productID];
+
+ if (transaction) {
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ }
+
+ self.pendingTransactions[productID] = nil;
+}
+
+- (void)reset {
+ [self.pendingTransactions removeAllObjects];
+}
+
+- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
+ printf("transactions updated!\n");
+ for (SKPaymentTransaction *transaction in transactions) {
+ switch (transaction.transactionState) {
+ case SKPaymentTransactionStatePurchased: {
+ printf("status purchased!\n");
+ String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
+ String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]);
+ InAppStore::get_singleton()->_record_purchase(pid);
+ Dictionary ret;
+ ret["type"] = "purchase";
+ ret["result"] = "ok";
+ ret["product_id"] = pid;
+ ret["transaction_id"] = transactionId;
+
+ NSData *receipt = nil;
+ int sdk_version = [[[UIDevice currentDevice] systemVersion] intValue];
+
+ NSBundle *bundle = [NSBundle mainBundle];
+ // Get the transaction receipt file path location in the app bundle.
+ NSURL *receiptFileURL = [bundle appStoreReceiptURL];
+
+ // Read in the contents of the transaction file.
+ receipt = [NSData dataWithContentsOfURL:receiptFileURL];
+
+ NSString *receipt_to_send = nil;
+
+ if (receipt != nil) {
+ receipt_to_send = [receipt base64EncodedStringWithOptions:0];
+ }
+ Dictionary receipt_ret;
+ receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
+ receipt_ret["sdk"] = sdk_version;
+ ret["receipt"] = receipt_ret;
+
+ InAppStore::get_singleton()->_post_event(ret);
+
+ if (self.shouldAutoFinishTransactions) {
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } else {
+ self.pendingTransactions[transaction.payment.productIdentifier] = transaction;
+ }
+
+ } break;
+ case SKPaymentTransactionStateFailed: {
+ printf("status transaction failed!\n");
+ String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
+ Dictionary ret;
+ ret["type"] = "purchase";
+ ret["result"] = "error";
+ ret["product_id"] = pid;
+ ret["error"] = String::utf8([transaction.error.localizedDescription UTF8String]);
+ InAppStore::get_singleton()->_post_event(ret);
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } break;
+ case SKPaymentTransactionStateRestored: {
+ printf("status transaction restored!\n");
+ String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
+ InAppStore::get_singleton()->_record_purchase(pid);
+ Dictionary ret;
+ ret["type"] = "restore";
+ ret["result"] = "ok";
+ ret["product_id"] = pid;
+ InAppStore::get_singleton()->_post_event(ret);
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } break;
+ default: {
+ printf("status default %i!\n", (int)transaction.transactionState);
+ } break;
+ }
+ }
+}
+
+@end
+
+void InAppStore::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("request_product_info"), &InAppStore::request_product_info);
+ ClassDB::bind_method(D_METHOD("restore_purchases"), &InAppStore::restore_purchases);
+ ClassDB::bind_method(D_METHOD("purchase"), &InAppStore::purchase);
+
+ ClassDB::bind_method(D_METHOD("get_pending_event_count"), &InAppStore::get_pending_event_count);
+ ClassDB::bind_method(D_METHOD("pop_pending_event"), &InAppStore::pop_pending_event);
+ ClassDB::bind_method(D_METHOD("finish_transaction"), &InAppStore::finish_transaction);
+ ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction);
+}
+
+Error InAppStore::request_product_info(Dictionary p_params) {
+ ERR_FAIL_COND_V(!p_params.has("product_ids"), ERR_INVALID_PARAMETER);
+
+ PackedStringArray pids = p_params["product_ids"];
+ printf("************ request product info! %i\n", pids.size());
+
+ NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:pids.size()];
+ for (int i = 0; i < pids.size(); i++) {
+ printf("******** adding %s to product list\n", pids[i].utf8().get_data());
+ NSString *pid = [[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()];
+ [array addObject:pid];
+ };
+
+ NSSet *products = [[NSSet alloc] initWithArray:array];
+
+ [products_request_delegate performRequestWithProductIDs:products];
+
+ return OK;
+}
+
+Error InAppStore::restore_purchases() {
+ printf("restoring purchases!\n");
+ [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
+
+ return OK;
+}
+
+Error InAppStore::purchase(Dictionary p_params) {
+ ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
+ if (![SKPaymentQueue canMakePayments]) {
+ return ERR_UNAVAILABLE;
+ }
+
+ printf("purchasing!\n");
+ Dictionary params = p_params;
+ ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER);
+
+ NSString *pid = [[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()];
+
+ return [products_request_delegate purchaseProductWithProductID:pid];
+}
+
+int InAppStore::get_pending_event_count() {
+ return pending_events.size();
+}
+
+Variant InAppStore::pop_pending_event() {
+ Variant front = pending_events.front()->get();
+ pending_events.pop_front();
+
+ return front;
+}
+
+void InAppStore::_post_event(Variant p_event) {
+ pending_events.push_back(p_event);
+}
+
+void InAppStore::_record_purchase(String product_id) {
+ String skey = "purchased/" + product_id;
+ NSString *key = [[NSString alloc] initWithUTF8String:skey.utf8().get_data()];
+ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
+ [[NSUserDefaults standardUserDefaults] synchronize];
+}
+
+InAppStore *InAppStore::get_singleton() {
+ return instance;
+}
+
+InAppStore::InAppStore() {
+ ERR_FAIL_COND(instance != NULL);
+ instance = this;
+
+ products_request_delegate = [[GodotProductsDelegate alloc] init];
+ transactions_observer = [[GodotTransactionsObserver alloc] init];
+
+ [[SKPaymentQueue defaultQueue] addTransactionObserver:transactions_observer];
+}
+
+void InAppStore::finish_transaction(String product_id) {
+ NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
+
+ [transactions_observer finishTransactionWithProductID:prod_id];
+}
+
+void InAppStore::set_auto_finish_transaction(bool b) {
+ transactions_observer.shouldAutoFinishTransactions = b;
+}
+
+InAppStore::~InAppStore() {
+ [products_request_delegate reset];
+ [transactions_observer reset];
+
+ products_request_delegate = nil;
+ [[SKPaymentQueue defaultQueue] removeTransactionObserver:transactions_observer];
+ transactions_observer = nil;
+}
diff --git a/modules/inappstore/in_app_store_module.cpp b/modules/inappstore/in_app_store_module.cpp
new file mode 100644
index 0000000000..c89735cd1c
--- /dev/null
+++ b/modules/inappstore/in_app_store_module.cpp
@@ -0,0 +1,48 @@
+/*************************************************************************/
+/* in_app_store_module.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "in_app_store_module.h"
+
+#include "core/config/engine.h"
+
+#include "in_app_store.h"
+
+InAppStore *store_kit;
+
+void register_inappstore_types() {
+ store_kit = memnew(InAppStore);
+ Engine::get_singleton()->add_singleton(Engine::Singleton("InAppStore", store_kit));
+}
+
+void unregister_inappstore_types() {
+ if (store_kit) {
+ memdelete(store_kit);
+ }
+}
diff --git a/modules/inappstore/in_app_store_module.h b/modules/inappstore/in_app_store_module.h
new file mode 100644
index 0000000000..dc38969825
--- /dev/null
+++ b/modules/inappstore/in_app_store_module.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* in_app_store_module.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+void register_inappstore_types();
+void unregister_inappstore_types();
diff --git a/modules/inappstore/inappstore.gdip b/modules/inappstore/inappstore.gdip
new file mode 100644
index 0000000000..7a5efb8ad3
--- /dev/null
+++ b/modules/inappstore/inappstore.gdip
@@ -0,0 +1,17 @@
+[config]
+name="InAppStore"
+binary="inappstore_lib.a"
+
+initialization="register_inappstore_types"
+deinitialization="unregister_inappstore_types"
+
+[dependencies]
+linked=[]
+embedded=[]
+system=["StoreKit.framework"]
+
+capabilities=[]
+
+files=[]
+
+[plist]
diff --git a/modules/jpg/SCsub b/modules/jpg/SCsub
index 8ee8e6dd6e..7c6ceeea29 100644
--- a/modules/jpg/SCsub
+++ b/modules/jpg/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_jpg = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
# Not unbundled for now as they are not commonly available as shared library
thirdparty_dir = "#thirdparty/jpeg-compressor/"
thirdparty_sources = [
@@ -17,7 +20,15 @@ env_jpg.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_jpg.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_jpg.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_jpg.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp
index 9e87d11ac1..7daf6a3a57 100644
--- a/modules/jpg/image_loader_jpegd.cpp
+++ b/modules/jpg/image_loader_jpegd.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,13 +31,12 @@
#include "image_loader_jpegd.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include <jpgd.h>
#include <string.h>
Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p_buffer_len) {
-
jpgd::jpeg_decoder_mem_stream mem_stream(p_buffer, p_buffer_len);
jpgd::jpeg_decoder decoder(&mem_stream);
@@ -49,11 +48,13 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
const int image_width = decoder.get_width();
const int image_height = decoder.get_height();
const int comps = decoder.get_num_components();
- if (comps != 1 && comps != 3)
+ if (comps != 1 && comps != 3) {
return ERR_FILE_CORRUPT;
+ }
- if (decoder.begin_decoding() != jpgd::JPGD_SUCCESS)
+ if (decoder.begin_decoding() != jpgd::JPGD_SUCCESS) {
return ERR_FILE_CORRUPT;
+ }
const int dst_bpl = image_width * comps;
@@ -91,18 +92,18 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
//all good
Image::Format fmt;
- if (comps == 1)
+ if (comps == 1) {
fmt = Image::FORMAT_L8;
- else
+ } else {
fmt = Image::FORMAT_RGB8;
+ }
- p_image->create(image_width, image_height, 0, fmt, data);
+ p_image->create(image_width, image_height, false, fmt, data);
return OK;
}
Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
Vector<uint8_t> src_image;
int src_image_len = f->get_len();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
@@ -120,13 +121,11 @@ Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
}
void ImageLoaderJPG::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("jpg");
p_extensions->push_back("jpeg");
}
static Ref<Image> _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) {
-
Ref<Image> img;
img.instance();
Error err = jpeg_load_image_from_buffer(img.ptr(), p_png, p_size);
@@ -135,6 +134,5 @@ static Ref<Image> _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) {
}
ImageLoaderJPG::ImageLoaderJPG() {
-
Image::_jpg_mem_loader_func = _jpegd_mem_loader_func;
}
diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h
index 9ef37ae303..be265b280c 100644
--- a/modules/jpg/image_loader_jpegd.h
+++ b/modules/jpg/image_loader_jpegd.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/io/image_loader.h"
class ImageLoaderJPG : public ImageFormatLoader {
-
public:
virtual Error load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/jpg/register_types.cpp b/modules/jpg/register_types.cpp
index 61375fef10..a6ae96635f 100644
--- a/modules/jpg/register_types.cpp
+++ b/modules/jpg/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
static ImageLoaderJPG *image_loader_jpg = nullptr;
void register_jpg_types() {
-
image_loader_jpg = memnew(ImageLoaderJPG);
ImageLoader::add_image_format_loader(image_loader_jpg);
}
void unregister_jpg_types() {
-
memdelete(image_loader_jpg);
}
diff --git a/modules/jpg/register_types.h b/modules/jpg/register_types.h
index 52cd378b3a..577e9b06f7 100644
--- a/modules/jpg/register_types.h
+++ b/modules/jpg/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/jsonrpc/jsonrpc.cpp b/modules/jsonrpc/jsonrpc.cpp
index 393269d422..306c0ff087 100644
--- a/modules/jsonrpc/jsonrpc.cpp
+++ b/modules/jsonrpc/jsonrpc.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -98,6 +98,10 @@ Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elem
if (p_action.get_type() == Variant::DICTIONARY) {
Dictionary dict = p_action;
String method = dict.get("method", "");
+ if (method.begins_with("$/")) {
+ return ret;
+ }
+
Array args;
if (dict.has("params")) {
Variant params = dict.get("params", Variant());
@@ -120,7 +124,7 @@ Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elem
}
if (object == nullptr || !object->has_method(method)) {
- ret = make_response_error(JSONRPC::METHOD_NOT_FOUND, "Method not found", id);
+ ret = make_response_error(JSONRPC::METHOD_NOT_FOUND, "Method not found: " + method, id);
} else {
Variant call_ret = object->callv(method, args);
if (id.get_type() != Variant::NIL) {
@@ -147,8 +151,9 @@ Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elem
}
String JSONRPC::process_string(const String &p_input) {
-
- if (p_input.empty()) return String();
+ if (p_input.is_empty()) {
+ return String();
+ }
Variant ret;
Variant input;
diff --git a/modules/jsonrpc/jsonrpc.h b/modules/jsonrpc/jsonrpc.h
index e2b7ab0975..9fd016602d 100644
--- a/modules/jsonrpc/jsonrpc.h
+++ b/modules/jsonrpc/jsonrpc.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef GODOT_JSON_RPC_H
#define GODOT_JSON_RPC_H
-#include "core/object.h"
-#include "core/variant.h"
+#include "core/object/class_db.h"
+#include "core/variant/variant.h"
class JSONRPC : public Object {
GDCLASS(JSONRPC, Object)
diff --git a/modules/jsonrpc/register_types.cpp b/modules/jsonrpc/register_types.cpp
index 0d3e446e3e..d6b565ba84 100644
--- a/modules/jsonrpc/register_types.cpp
+++ b/modules/jsonrpc/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,7 +29,7 @@
/*************************************************************************/
#include "register_types.h"
-#include "core/class_db.h"
+#include "core/object/class_db.h"
#include "jsonrpc.h"
void register_jsonrpc_types() {
diff --git a/modules/jsonrpc/register_types.h b/modules/jsonrpc/register_types.h
index 854d73a21f..6a21a12444 100644
--- a/modules/jsonrpc/register_types.h
+++ b/modules/jsonrpc/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/lightmapper_rd/SCsub b/modules/lightmapper_rd/SCsub
new file mode 100644
index 0000000000..2f04f1833e
--- /dev/null
+++ b/modules/lightmapper_rd/SCsub
@@ -0,0 +1,12 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_lightmapper_rd = env_modules.Clone()
+env_lightmapper_rd.GLSL_HEADER("lm_raster.glsl")
+env_lightmapper_rd.GLSL_HEADER("lm_compute.glsl")
+env_lightmapper_rd.GLSL_HEADER("lm_blendseams.glsl")
+
+# Godot source files
+env_lightmapper_rd.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/assimp/config.py b/modules/lightmapper_rd/config.py
index 53b8f2f2e3..d22f9454ed 100644
--- a/modules/assimp/config.py
+++ b/modules/lightmapper_rd/config.py
@@ -1,5 +1,5 @@
def can_build(env, platform):
- return env["tools"]
+ return True
def configure(env):
diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp
new file mode 100644
index 0000000000..3067e002d8
--- /dev/null
+++ b/modules/lightmapper_rd/lightmapper_rd.cpp
@@ -0,0 +1,1751 @@
+/*************************************************************************/
+/* lightmapper_rd.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "lightmapper_rd.h"
+#include "core/config/project_settings.h"
+#include "core/math/geometry_2d.h"
+#include "lm_blendseams.glsl.gen.h"
+#include "lm_compute.glsl.gen.h"
+#include "lm_raster.glsl.gen.h"
+#include "servers/rendering/rendering_device_binds.h"
+
+//uncomment this if you want to see textures from all the process saved
+//#define DEBUG_TEXTURES
+
+void LightmapperRD::add_mesh(const MeshData &p_mesh) {
+ ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
+ ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
+ ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
+ ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
+ ERR_FAIL_COND(p_mesh.points.size() == 0);
+ MeshInstance mi;
+ mi.data = p_mesh;
+ mesh_instances.push_back(mi);
+}
+
+void LightmapperRD::add_directional_light(bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_angular_distance) {
+ Light l;
+ l.type = LIGHT_TYPE_DIRECTIONAL;
+ l.direction[0] = p_direction.x;
+ l.direction[1] = p_direction.y;
+ l.direction[2] = p_direction.z;
+ l.color[0] = p_color.r;
+ l.color[1] = p_color.g;
+ l.color[2] = p_color.b;
+ l.energy = p_energy;
+ l.static_bake = p_static;
+ l.size = p_angular_distance;
+ lights.push_back(l);
+}
+
+void LightmapperRD::add_omni_light(bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_size) {
+ Light l;
+ l.type = LIGHT_TYPE_OMNI;
+ l.position[0] = p_position.x;
+ l.position[1] = p_position.y;
+ l.position[2] = p_position.z;
+ l.range = p_range;
+ l.attenuation = p_attenuation;
+ l.color[0] = p_color.r;
+ l.color[1] = p_color.g;
+ l.color[2] = p_color.b;
+ l.energy = p_energy;
+ l.static_bake = p_static;
+ l.size = p_size;
+ lights.push_back(l);
+}
+
+void LightmapperRD::add_spot_light(bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size) {
+ Light l;
+ l.type = LIGHT_TYPE_SPOT;
+ l.position[0] = p_position.x;
+ l.position[1] = p_position.y;
+ l.position[2] = p_position.z;
+ l.direction[0] = p_direction.x;
+ l.direction[1] = p_direction.y;
+ l.direction[2] = p_direction.z;
+ l.range = p_range;
+ l.attenuation = p_attenuation;
+ l.spot_angle = Math::deg2rad(p_spot_angle);
+ l.spot_attenuation = p_spot_attenuation;
+ l.color[0] = p_color.r;
+ l.color[1] = p_color.g;
+ l.color[2] = p_color.b;
+ l.energy = p_energy;
+ l.static_bake = p_static;
+ l.size = p_size;
+ lights.push_back(l);
+}
+
+void LightmapperRD::add_probe(const Vector3 &p_position) {
+ Probe probe;
+ probe.position[0] = p_position.x;
+ probe.position[1] = p_position.y;
+ probe.position[2] = p_position.z;
+ probe.position[3] = 0;
+ probe_positions.push_back(probe);
+}
+
+void LightmapperRD::_plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[3], uint32_t p_triangle_index, LocalVector<TriangleSort> &triangles, uint32_t p_grid_size) {
+ int half_size = p_size / 2;
+
+ for (int i = 0; i < 8; i++) {
+ AABB aabb = p_bounds;
+ aabb.size *= 0.5;
+ Vector3i n = p_ofs;
+
+ if (i & 1) {
+ aabb.position.x += aabb.size.x;
+ n.x += half_size;
+ }
+ if (i & 2) {
+ aabb.position.y += aabb.size.y;
+ n.y += half_size;
+ }
+ if (i & 4) {
+ aabb.position.z += aabb.size.z;
+ n.z += half_size;
+ }
+
+ {
+ Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
+
+ if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
+ //does not fit in child, go on
+ continue;
+ }
+ }
+
+ if (half_size == 1) {
+ //got to the end
+ TriangleSort ts;
+ ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
+ ts.triangle_index = p_triangle_index;
+ triangles.push_back(ts);
+ } else {
+ _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, triangles, p_grid_size);
+ }
+ }
+}
+
+Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, BakeStepFunc p_step_function, void *p_bake_userdata) {
+ Vector<Size2i> sizes;
+
+ for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
+ MeshInstance &mi = mesh_instances.write[m_i];
+ Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
+ sizes.push_back(s);
+ atlas_size.width = MAX(atlas_size.width, s.width);
+ atlas_size.height = MAX(atlas_size.height, s.height);
+ }
+
+ int max = nearest_power_of_2_templated(atlas_size.width);
+ max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
+
+ if (max > p_max_texture_size) {
+ return BAKE_ERROR_LIGHTMAP_TOO_SMALL;
+ }
+
+ if (p_step_function) {
+ p_step_function(0.1, TTR("Determining optimal atlas size"), p_bake_userdata, true);
+ }
+
+ atlas_size = Size2i(max, max);
+
+ Size2i best_atlas_size;
+ int best_atlas_slices = 0;
+ int best_atlas_memory = 0x7FFFFFFF;
+ Vector<Vector3i> best_atlas_offsets;
+
+ //determine best texture array atlas size by bruteforce fitting
+ while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
+ Vector<Vector2i> source_sizes = sizes;
+ Vector<int> source_indices;
+ source_indices.resize(source_sizes.size());
+ for (int i = 0; i < source_indices.size(); i++) {
+ source_indices.write[i] = i;
+ }
+ Vector<Vector3i> atlas_offsets;
+ atlas_offsets.resize(source_sizes.size());
+
+ int slices = 0;
+
+ while (source_sizes.size() > 0) {
+ Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
+ Vector<int> new_indices;
+ Vector<Vector2i> new_sources;
+ for (int i = 0; i < offsets.size(); i++) {
+ Vector3i ofs = offsets[i];
+ int sidx = source_indices[i];
+ if (ofs.z > 0) {
+ //valid
+ ofs.z = slices;
+ atlas_offsets.write[sidx] = ofs;
+ } else {
+ new_indices.push_back(sidx);
+ new_sources.push_back(source_sizes[i]);
+ }
+ }
+
+ source_sizes = new_sources;
+ source_indices = new_indices;
+ slices++;
+ }
+
+ int mem_used = atlas_size.x * atlas_size.y * slices;
+ if (mem_used < best_atlas_memory) {
+ best_atlas_size = atlas_size;
+ best_atlas_offsets = atlas_offsets;
+ best_atlas_slices = slices;
+ best_atlas_memory = mem_used;
+ }
+
+ if (atlas_size.width == atlas_size.height) {
+ atlas_size.width *= 2;
+ } else {
+ atlas_size.height *= 2;
+ }
+ }
+ atlas_size = best_atlas_size;
+ atlas_slices = best_atlas_slices;
+
+ // apply the offsets and slice to all images, and also blit albedo and emission
+ albedo_images.resize(atlas_slices);
+ emission_images.resize(atlas_slices);
+
+ if (p_step_function) {
+ p_step_function(0.2, TTR("Blitting albedo and emission"), p_bake_userdata, true);
+ }
+
+ for (int i = 0; i < atlas_slices; i++) {
+ Ref<Image> albedo;
+ albedo.instance();
+ albedo->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
+ albedo->set_as_black();
+ albedo_images.write[i] = albedo;
+
+ Ref<Image> emission;
+ emission.instance();
+ emission->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
+ emission->set_as_black();
+ emission_images.write[i] = emission;
+ }
+
+ //assign uv positions
+
+ for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
+ MeshInstance &mi = mesh_instances.write[m_i];
+ mi.offset.x = best_atlas_offsets[m_i].x;
+ mi.offset.y = best_atlas_offsets[m_i].y;
+ mi.slice = best_atlas_offsets[m_i].z;
+ albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2(Vector2(), Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height())), mi.offset);
+ emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2(), Size2i(mi.data.emission_on_uv2->get_width(), mi.data.emission_on_uv2->get_height())), mi.offset);
+ }
+
+ return BAKE_OK;
+}
+
+void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &grid_texture_sdf, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {
+ HashMap<Vertex, uint32_t, VertexHash> vertex_map;
+
+ //fill triangles array and vertex array
+ LocalVector<Triangle> triangles;
+ LocalVector<Vertex> vertex_array;
+ LocalVector<Box> box_array;
+ LocalVector<Seam> seams;
+
+ slice_triangle_count.resize(atlas_slices);
+ slice_seam_count.resize(atlas_slices);
+
+ for (int i = 0; i < atlas_slices; i++) {
+ slice_triangle_count.write[i] = 0;
+ slice_seam_count.write[i] = 0;
+ }
+
+ bounds = AABB();
+
+ for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
+ if (p_step_function) {
+ float p = float(m_i + 1) / mesh_instances.size() * 0.1;
+ p_step_function(0.3 + p, vformat(TTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false);
+ }
+
+ HashMap<Edge, EdgeUV2, EdgeHash> edges;
+
+ MeshInstance &mi = mesh_instances.write[m_i];
+
+ Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
+ Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
+ if (m_i == 0) {
+ bounds.position = mi.data.points[0];
+ }
+
+ for (int i = 0; i < mi.data.points.size(); i += 3) {
+ Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
+ Vector2 uvs[3] = { mi.data.uv2[i + 0] * uv_scale + uv_offset, mi.data.uv2[i + 1] * uv_scale + uv_offset, mi.data.uv2[i + 2] * uv_scale + uv_offset };
+ Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
+
+ AABB taabb;
+ Triangle t;
+ t.slice = mi.slice;
+ for (int k = 0; k < 3; k++) {
+ bounds.expand_to(vtxs[k]);
+
+ Vertex v;
+ v.position[0] = vtxs[k].x;
+ v.position[1] = vtxs[k].y;
+ v.position[2] = vtxs[k].z;
+ v.uv[0] = uvs[k].x;
+ v.uv[1] = uvs[k].y;
+ v.normal_xy[0] = normal[k].x;
+ v.normal_xy[1] = normal[k].y;
+ v.normal_z = normal[k].z;
+
+ uint32_t *indexptr = vertex_map.getptr(v);
+
+ if (indexptr) {
+ t.indices[k] = *indexptr;
+ } else {
+ uint32_t new_index = vertex_map.size();
+ t.indices[k] = new_index;
+ vertex_map[v] = new_index;
+ vertex_array.push_back(v);
+ }
+
+ if (k == 0) {
+ taabb.position = vtxs[k];
+ } else {
+ taabb.expand_to(vtxs[k]);
+ }
+ }
+
+ //compute seams that will need to be blended later
+ for (int k = 0; k < 3; k++) {
+ int n = (k + 1) % 3;
+
+ Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
+ Vector2i edge_indices(t.indices[k], t.indices[n]);
+ EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
+
+ if (edge.b == edge.a) {
+ continue; //degenerate, somehow
+ }
+ if (edge.b < edge.a) {
+ SWAP(edge.a, edge.b);
+ SWAP(edge.na, edge.nb);
+ SWAP(uv2.a, uv2.b);
+ SWAP(edge_indices.x, edge_indices.y);
+ }
+
+ EdgeUV2 *euv2 = edges.getptr(edge);
+ if (!euv2) {
+ edges[edge] = uv2;
+ } else {
+ if (*euv2 == uv2) {
+ continue; // seam shared UV space, no need to blend
+ }
+ if (euv2->seam_found) {
+ continue; //bad geometry
+ }
+
+ Seam seam;
+ seam.a = edge_indices;
+ seam.b = euv2->indices;
+ seam.slice = mi.slice;
+ seams.push_back(seam);
+ slice_seam_count.write[mi.slice]++;
+ euv2->seam_found = true;
+ }
+ }
+
+ Box box;
+ box.min_bounds[0] = taabb.position.x;
+ box.min_bounds[1] = taabb.position.y;
+ box.min_bounds[2] = taabb.position.z;
+ box.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
+ box.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
+ box.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
+ box.pad0 = box.pad1 = 0; //make valgrind not complain
+ box_array.push_back(box);
+
+ triangles.push_back(t);
+ slice_triangle_count.write[t.slice]++;
+ }
+ }
+
+ //also consider probe positions for bounds
+ for (int i = 0; i < probe_positions.size(); i++) {
+ Vector3 pp(probe_positions[i].position[0], probe_positions[i].position[1], probe_positions[i].position[2]);
+ bounds.expand_to(pp);
+ }
+ bounds.grow_by(0.1); //grow a bit to avoid numerical error
+
+ triangles.sort(); //sort by slice
+ seams.sort();
+
+ if (p_step_function) {
+ p_step_function(0.4, TTR("Optimizing acceleration structure"), p_bake_userdata, true);
+ }
+
+ //fill list of triangles in grid
+ LocalVector<TriangleSort> triangle_sort;
+ for (uint32_t i = 0; i < triangles.size(); i++) {
+ const Triangle &t = triangles[i];
+ Vector3 face[3] = {
+ Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
+ Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
+ Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
+ };
+ _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
+ }
+ //sort it
+ triangle_sort.sort();
+
+ Vector<uint32_t> triangle_indices;
+ triangle_indices.resize(triangle_sort.size());
+ Vector<uint32_t> grid_indices;
+ grid_indices.resize(grid_size * grid_size * grid_size * 2);
+ zeromem(grid_indices.ptrw(), grid_indices.size() * sizeof(uint32_t));
+ Vector<bool> solid;
+ solid.resize(grid_size * grid_size * grid_size);
+ zeromem(solid.ptrw(), solid.size() * sizeof(bool));
+
+ {
+ uint32_t *tiw = triangle_indices.ptrw();
+ uint32_t last_cell = 0xFFFFFFFF;
+ uint32_t *giw = grid_indices.ptrw();
+ bool *solidw = solid.ptrw();
+ for (uint32_t i = 0; i < triangle_sort.size(); i++) {
+ uint32_t cell = triangle_sort[i].cell_index;
+ if (cell != last_cell) {
+ //cell changed, update pointer to indices
+ giw[cell * 2 + 1] = i;
+ solidw[cell] = true;
+ }
+ tiw[i] = triangle_sort[i].triangle_index;
+ giw[cell * 2]++; //update counter
+ last_cell = cell;
+ }
+ }
+#if 0
+ for (int i = 0; i < grid_size; i++) {
+ for (int j = 0; j < grid_size; j++) {
+ for (int k = 0; k < grid_size; k++) {
+ uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
+ grid_indices.write[index * 2] = float(i) / grid_size * 255;
+ grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
+ }
+ }
+ }
+#endif
+
+#if 0
+ for (int i = 0; i < grid_size; i++) {
+ Vector<uint8_t> grid_usage;
+ grid_usage.resize(grid_size * grid_size);
+ for (int j = 0; j < grid_usage.size(); j++) {
+ uint32_t ofs = i * grid_size * grid_size + j;
+ uint32_t count = grid_indices[ofs * 2];
+ grid_usage.write[j] = count > 0 ? 255 : 0;
+ }
+
+ Ref<Image> img;
+ img.instance();
+ img->create(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
+ img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
+ }
+#endif
+ if (p_step_function) {
+ p_step_function(0.45, TTR("Generating Signed Distance Field"), p_bake_userdata, true);
+ }
+
+ //generate SDF for raytracing
+ Vector<uint32_t> euclidean_pos = Geometry3D::generate_edf(solid, Vector3i(grid_size, grid_size, grid_size), false);
+ Vector<uint32_t> euclidean_neg = Geometry3D::generate_edf(solid, Vector3i(grid_size, grid_size, grid_size), true);
+ Vector<int8_t> sdf8 = Geometry3D::generate_sdf8(euclidean_pos, euclidean_neg);
+
+ /*****************************/
+ /*** CREATE GPU STRUCTURES ***/
+ /*****************************/
+
+ lights.sort();
+
+ Vector<Vector2i> seam_buffer_vec;
+ seam_buffer_vec.resize(seams.size() * 2);
+ for (uint32_t i = 0; i < seams.size(); i++) {
+ seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
+ seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
+ }
+
+ { //buffers
+ Vector<uint8_t> vb = vertex_array.to_byte_array();
+ vertex_buffer = rd->storage_buffer_create(vb.size(), vb);
+
+ Vector<uint8_t> tb = triangles.to_byte_array();
+ triangle_buffer = rd->storage_buffer_create(tb.size(), tb);
+
+ Vector<uint8_t> bb = box_array.to_byte_array();
+ box_buffer = rd->storage_buffer_create(bb.size(), bb);
+
+ Vector<uint8_t> tib = triangle_indices.to_byte_array();
+ triangle_cell_indices_buffer = rd->storage_buffer_create(tib.size(), tib);
+
+ Vector<uint8_t> lb = lights.to_byte_array();
+ if (lb.size() == 0) {
+ lb.resize(sizeof(Light)); //even if no lights, the buffer must exist
+ }
+ lights_buffer = rd->storage_buffer_create(lb.size(), lb);
+
+ Vector<uint8_t> sb = seam_buffer_vec.to_byte_array();
+ if (sb.size() == 0) {
+ sb.resize(sizeof(Vector2i) * 2); //even if no seams, the buffer must exist
+ }
+ seams_buffer = rd->storage_buffer_create(sb.size(), sb);
+
+ Vector<uint8_t> pb = probe_positions.to_byte_array();
+ if (pb.size() == 0) {
+ pb.resize(sizeof(Probe));
+ }
+ probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
+ }
+
+ { //grid
+
+ RD::TextureFormat tf;
+ tf.width = grid_size;
+ tf.height = grid_size;
+ tf.depth = grid_size;
+ tf.texture_type = RD::TEXTURE_TYPE_3D;
+ tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
+
+ Vector<Vector<uint8_t>> texdata;
+ texdata.resize(1);
+ //grid and indices
+ tf.format = RD::DATA_FORMAT_R32G32_UINT;
+ texdata.write[0] = grid_indices.to_byte_array();
+ grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
+ //sdf
+ tf.format = RD::DATA_FORMAT_R8_SNORM;
+ texdata.write[0] = sdf8.to_byte_array();
+ grid_texture_sdf = rd->texture_create(tf, RD::TextureView(), texdata);
+ }
+}
+
+void LightmapperRD::_raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform) {
+ Vector<RID> framebuffers;
+
+ for (int i = 0; i < atlas_slices; i++) {
+ RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
+ RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
+ RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
+ Vector<RID> fb;
+ fb.push_back(slice_pos_tex);
+ fb.push_back(slice_norm_tex);
+ fb.push_back(slice_unoc_tex);
+ fb.push_back(raster_depth_buffer);
+ framebuffers.push_back(rd->framebuffer_create(fb));
+ }
+
+ RD::PipelineDepthStencilState ds;
+ ds.enable_depth_test = true;
+ ds.enable_depth_write = true;
+ ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
+
+ RID raster_pipeline = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
+ RID raster_pipeline_wire;
+ {
+ RD::PipelineRasterizationState rw;
+ rw.wireframe = true;
+ raster_pipeline_wire = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, rw, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);
+ }
+
+ uint32_t triangle_offset = 0;
+ Vector<Color> clear_colors;
+ clear_colors.push_back(Color(0, 0, 0, 0));
+ clear_colors.push_back(Color(0, 0, 0, 0));
+ clear_colors.push_back(Color(0, 0, 0, 0));
+
+ for (int i = 0; i < atlas_slices; i++) {
+ RasterPushConstant raster_push_constant;
+ raster_push_constant.atlas_size[0] = atlas_size.x;
+ raster_push_constant.atlas_size[1] = atlas_size.y;
+ raster_push_constant.base_triangle = triangle_offset;
+ raster_push_constant.to_cell_offset[0] = bounds.position.x;
+ raster_push_constant.to_cell_offset[1] = bounds.position.y;
+ raster_push_constant.to_cell_offset[2] = bounds.position.z;
+ raster_push_constant.bias = p_bias;
+ raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
+ raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
+ raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
+ raster_push_constant.grid_size[0] = grid_size;
+ raster_push_constant.grid_size[1] = grid_size;
+ raster_push_constant.grid_size[2] = grid_size;
+ raster_push_constant.uv_offset[0] = 0;
+ raster_push_constant.uv_offset[1] = 0;
+
+ RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
+ //draw opaque
+ rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
+ rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
+ rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
+ rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
+ //draw wire
+ rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
+ rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
+ rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
+ rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
+
+ rd->draw_list_end();
+
+ triangle_offset += slice_triangle_count[i];
+ }
+}
+
+LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bias, int p_max_texture_size, bool p_bake_sh, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata) {
+ if (p_step_function) {
+ p_step_function(0.0, TTR("Begin Bake"), p_bake_userdata, true);
+ }
+ bake_textures.clear();
+ int grid_size = 128;
+
+ /* STEP 1: Fetch material textures and compute the bounds */
+
+ AABB bounds;
+ Size2i atlas_size;
+ int atlas_slices;
+ Vector<Ref<Image>> albedo_images;
+ Vector<Ref<Image>> emission_images;
+
+ BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_step_function, p_bake_userdata);
+ if (bake_error != BAKE_OK) {
+ return bake_error;
+ }
+
+#ifdef DEBUG_TEXTURES
+ for (int i = 0; i < atlas_slices; i++) {
+ albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
+ emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
+ }
+#endif
+
+ RenderingDevice *rd = RenderingDevice::get_singleton()->create_local_device();
+
+ RID albedo_array_tex;
+ RID emission_array_tex;
+ RID normal_tex;
+ RID position_tex;
+ RID unocclude_tex;
+ RID light_source_tex;
+ RID light_dest_tex;
+ RID light_accum_tex;
+ RID light_accum_tex2;
+ RID light_primary_dynamic_tex;
+ RID light_environment_tex;
+
+#define FREE_TEXTURES \
+ rd->free(albedo_array_tex); \
+ rd->free(emission_array_tex); \
+ rd->free(normal_tex); \
+ rd->free(position_tex); \
+ rd->free(unocclude_tex); \
+ rd->free(light_source_tex); \
+ rd->free(light_accum_tex2); \
+ rd->free(light_accum_tex); \
+ rd->free(light_primary_dynamic_tex); \
+ rd->free(light_environment_tex);
+
+ { // create all textures
+
+ Vector<Vector<uint8_t>> albedo_data;
+ Vector<Vector<uint8_t>> emission_data;
+ for (int i = 0; i < atlas_slices; i++) {
+ albedo_data.push_back(albedo_images[i]->get_data());
+ emission_data.push_back(emission_images[i]->get_data());
+ }
+
+ RD::TextureFormat tf;
+ tf.width = atlas_size.width;
+ tf.height = atlas_size.height;
+ tf.array_layers = atlas_slices;
+ tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
+ tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
+ tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
+
+ albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
+
+ tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
+
+ emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
+
+ //this will be rastered to
+ tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
+ normal_tex = rd->texture_create(tf, RD::TextureView());
+ tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
+ position_tex = rd->texture_create(tf, RD::TextureView());
+ unocclude_tex = rd->texture_create(tf, RD::TextureView());
+
+ tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
+ tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
+
+ light_source_tex = rd->texture_create(tf, RD::TextureView());
+ rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
+ light_primary_dynamic_tex = rd->texture_create(tf, RD::TextureView());
+ rd->texture_clear(light_primary_dynamic_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
+
+ if (p_bake_sh) {
+ tf.array_layers *= 4;
+ }
+ light_accum_tex = rd->texture_create(tf, RD::TextureView());
+ rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
+ light_dest_tex = rd->texture_create(tf, RD::TextureView());
+ rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
+ light_accum_tex2 = light_dest_tex;
+
+ //env
+ {
+ Ref<Image> panorama_tex;
+ if (p_environment_panorama.is_valid()) {
+ panorama_tex = p_environment_panorama;
+ panorama_tex->convert(Image::FORMAT_RGBAF);
+ } else {
+ panorama_tex.instance();
+ panorama_tex->create(8, 8, false, Image::FORMAT_RGBAF);
+ for (int i = 0; i < 8; i++) {
+ for (int j = 0; j < 8; j++) {
+ panorama_tex->set_pixel(i, j, Color(0, 0, 0, 1));
+ }
+ }
+ }
+
+ RD::TextureFormat tfp;
+ tfp.width = panorama_tex->get_width();
+ tfp.height = panorama_tex->get_height();
+ tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
+ tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
+
+ Vector<Vector<uint8_t>> tdata;
+ tdata.push_back(panorama_tex->get_data());
+ light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
+
+#ifdef DEBUG_TEXTURES
+ panorama_tex->convert(Image::FORMAT_RGB8);
+ panorama_tex->save_png("res://0_panorama.png");
+#endif
+ }
+ }
+
+ /* STEP 2: create the acceleration structure for the GPU*/
+
+ Vector<int> slice_triangle_count;
+ RID vertex_buffer;
+ RID triangle_buffer;
+ RID box_buffer;
+ RID lights_buffer;
+ RID triangle_cell_indices_buffer;
+ RID grid_texture;
+ RID grid_texture_sdf;
+ RID seams_buffer;
+ RID probe_positions_buffer;
+
+ Vector<int> slice_seam_count;
+
+#define FREE_BUFFERS \
+ rd->free(vertex_buffer); \
+ rd->free(triangle_buffer); \
+ rd->free(box_buffer); \
+ rd->free(lights_buffer); \
+ rd->free(triangle_cell_indices_buffer); \
+ rd->free(grid_texture); \
+ rd->free(grid_texture_sdf); \
+ rd->free(seams_buffer); \
+ rd->free(probe_positions_buffer);
+
+ _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, box_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, grid_texture_sdf, seams_buffer, p_step_function, p_bake_userdata);
+
+ if (p_step_function) {
+ p_step_function(0.47, TTR("Preparing shaders"), p_bake_userdata, true);
+ }
+
+ //shaders
+ Ref<RDShaderFile> raster_shader;
+ raster_shader.instance();
+ Error err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
+ if (err != OK) {
+ raster_shader->print_errors("raster_shader");
+
+ FREE_TEXTURES
+ FREE_BUFFERS
+
+ memdelete(rd);
+ }
+ ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
+
+ RID rasterize_shader = rd->shader_create_from_bytecode(raster_shader->get_bytecode());
+
+ ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
+
+ RID sampler;
+ {
+ RD::SamplerState s;
+ s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
+ s.min_filter = RD::SAMPLER_FILTER_LINEAR;
+ s.max_lod = 0;
+
+ sampler = rd->sampler_create(s);
+ }
+
+ Vector<RD::Uniform> base_uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 1;
+ u.ids.push_back(vertex_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 2;
+ u.ids.push_back(triangle_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 3;
+ u.ids.push_back(box_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 4;
+ u.ids.push_back(triangle_cell_indices_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 5;
+ u.ids.push_back(lights_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 6;
+ u.ids.push_back(seams_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 7;
+ u.ids.push_back(probe_positions_buffer);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 8;
+ u.ids.push_back(grid_texture);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 9;
+ u.ids.push_back(grid_texture_sdf);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 10;
+ u.ids.push_back(albedo_array_tex);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 11;
+ u.ids.push_back(emission_array_tex);
+ base_uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
+ u.binding = 12;
+ u.ids.push_back(sampler);
+ base_uniforms.push_back(u);
+ }
+ }
+
+ RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
+ RID raster_depth_buffer;
+ {
+ RD::TextureFormat tf;
+ tf.width = atlas_size.width;
+ tf.height = atlas_size.height;
+ tf.depth = 1;
+ tf.texture_type = RD::TEXTURE_TYPE_2D;
+ tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
+ tf.format = RD::DATA_FORMAT_D32_SFLOAT;
+
+ raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
+ }
+
+ rd->submit();
+ rd->sync();
+
+ /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
+
+ _raster_geometry(rd, atlas_size, atlas_slices, grid_size, bounds, p_bias, slice_triangle_count, position_tex, unocclude_tex, normal_tex, raster_depth_buffer, rasterize_shader, raster_base_uniform);
+
+#ifdef DEBUG_TEXTURES
+
+ for (int i = 0; i < atlas_slices; i++) {
+ Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://1_position_" + itos(i) + ".png");
+
+ s = rd->texture_get_data(normal_tex, i);
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://1_normal_" + itos(i) + ".png");
+ }
+#endif
+
+#define FREE_RASTER_RESOURCES \
+ rd->free(rasterize_shader); \
+ rd->free(sampler); \
+ rd->free(raster_depth_buffer);
+
+ /* Plot direct light */
+
+ Ref<RDShaderFile> compute_shader;
+ compute_shader.instance();
+ err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, p_bake_sh ? "\n#define USE_SH_LIGHTMAPS\n" : "");
+ if (err != OK) {
+ FREE_TEXTURES
+ FREE_BUFFERS
+ FREE_RASTER_RESOURCES
+ memdelete(rd);
+ compute_shader->print_errors("compute_shader");
+ }
+ ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
+
+ //unoccluder
+ RID compute_shader_unocclude = rd->shader_create_from_bytecode(compute_shader->get_bytecode("unocclude"));
+ ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
+ RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
+
+ //direct light
+ RID compute_shader_primary = rd->shader_create_from_bytecode(compute_shader->get_bytecode("primary"));
+ ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
+ RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
+
+ //indirect light
+ RID compute_shader_secondary = rd->shader_create_from_bytecode(compute_shader->get_bytecode("secondary"));
+ ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
+ RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
+
+ //dilate
+ RID compute_shader_dilate = rd->shader_create_from_bytecode(compute_shader->get_bytecode("dilate"));
+ ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
+ RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
+
+ //dilate
+ RID compute_shader_light_probes = rd->shader_create_from_bytecode(compute_shader->get_bytecode("light_probes"));
+ ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
+ RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
+
+ RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
+
+#define FREE_COMPUTE_RESOURCES \
+ rd->free(compute_shader_unocclude); \
+ rd->free(compute_shader_primary); \
+ rd->free(compute_shader_secondary); \
+ rd->free(compute_shader_dilate); \
+ rd->free(compute_shader_light_probes);
+
+ PushConstant push_constant;
+ {
+ //set defaults
+ push_constant.atlas_size[0] = atlas_size.width;
+ push_constant.atlas_size[1] = atlas_size.height;
+ push_constant.world_size[0] = bounds.size.x;
+ push_constant.world_size[1] = bounds.size.y;
+ push_constant.world_size[2] = bounds.size.z;
+ push_constant.to_cell_offset[0] = bounds.position.x;
+ push_constant.to_cell_offset[1] = bounds.position.y;
+ push_constant.to_cell_offset[2] = bounds.position.z;
+ push_constant.bias = p_bias;
+ push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
+ push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
+ push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
+ push_constant.light_count = lights.size();
+ push_constant.grid_size = grid_size;
+ push_constant.atlas_slice = 0;
+ push_constant.region_ofs[0] = 0;
+ push_constant.region_ofs[1] = 0;
+ push_constant.environment_xform[0] = p_environment_transform.elements[0][0];
+ push_constant.environment_xform[1] = p_environment_transform.elements[1][0];
+ push_constant.environment_xform[2] = p_environment_transform.elements[2][0];
+ push_constant.environment_xform[3] = 0;
+ push_constant.environment_xform[4] = p_environment_transform.elements[0][1];
+ push_constant.environment_xform[5] = p_environment_transform.elements[1][1];
+ push_constant.environment_xform[6] = p_environment_transform.elements[2][1];
+ push_constant.environment_xform[7] = 0;
+ push_constant.environment_xform[8] = p_environment_transform.elements[0][2];
+ push_constant.environment_xform[9] = p_environment_transform.elements[1][2];
+ push_constant.environment_xform[10] = p_environment_transform.elements[2][2];
+ push_constant.environment_xform[11] = 0;
+ }
+
+ Vector3i group_size((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1);
+ rd->submit();
+ rd->sync();
+
+ if (p_step_function) {
+ p_step_function(0.49, TTR("Un-occluding geometry"), p_bake_userdata, true);
+ }
+
+ /* UNOCCLUDE */
+ {
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 0;
+ u.ids.push_back(position_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 1;
+ u.ids.push_back(unocclude_tex); //will be unused
+ uniforms.push_back(u);
+ }
+ }
+
+ RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
+
+ RD::ComputeListID compute_list = rd->compute_list_begin();
+ rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
+ rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
+ rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
+
+ for (int i = 0; i < atlas_slices; i++) {
+ push_constant.atlas_slice = i;
+ rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
+ rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
+ //no barrier, let them run all together
+ }
+ rd->compute_list_end(); //done
+ }
+
+ if (p_step_function) {
+ p_step_function(0.5, TTR("Plot direct lighting"), p_bake_userdata, true);
+ }
+
+ /* PRIMARY (direct) LIGHT PASS */
+ {
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 0;
+ u.ids.push_back(light_source_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 1;
+ u.ids.push_back(light_dest_tex); //will be unused
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 2;
+ u.ids.push_back(position_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 3;
+ u.ids.push_back(normal_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 4;
+ u.ids.push_back(light_accum_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 5;
+ u.ids.push_back(light_primary_dynamic_tex);
+ uniforms.push_back(u);
+ }
+ }
+
+ RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
+
+ RD::ComputeListID compute_list = rd->compute_list_begin();
+ rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
+ rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
+ rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
+
+ for (int i = 0; i < atlas_slices; i++) {
+ push_constant.atlas_slice = i;
+ rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
+ rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
+ //no barrier, let them run all together
+ }
+ rd->compute_list_end(); //done
+ }
+
+#ifdef DEBUG_TEXTURES
+
+ for (int i = 0; i < atlas_slices; i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://2_light_primary_" + itos(i) + ".png");
+ }
+#endif
+
+ /* SECONDARY (indirect) LIGHT PASS(ES) */
+ if (p_step_function) {
+ p_step_function(0.6, TTR("Integrate indirect lighting"), p_bake_userdata, true);
+ }
+
+ if (p_bounces > 0) {
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 0;
+ u.ids.push_back(light_dest_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 1;
+ u.ids.push_back(light_source_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 2;
+ u.ids.push_back(position_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 3;
+ u.ids.push_back(normal_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 4;
+ u.ids.push_back(light_accum_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 5;
+ u.ids.push_back(unocclude_tex); //reuse unocclude tex
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 6;
+ u.ids.push_back(light_environment_tex); //reuse unocclude tex
+ uniforms.push_back(u);
+ }
+ }
+
+ RID secondary_uniform_set[2];
+ secondary_uniform_set[0] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
+ uniforms.write[0].ids.write[0] = light_source_tex;
+ uniforms.write[1].ids.write[0] = light_dest_tex;
+ secondary_uniform_set[1] = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
+
+ switch (p_quality) {
+ case BAKE_QUALITY_LOW: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/low_quality_ray_count");
+ } break;
+ case BAKE_QUALITY_MEDIUM: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/medium_quality_ray_count");
+ } break;
+ case BAKE_QUALITY_HIGH: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/high_quality_ray_count");
+ } break;
+ case BAKE_QUALITY_ULTRA: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/ultra_quality_ray_count");
+ } break;
+ }
+
+ push_constant.ray_count = CLAMP(push_constant.ray_count, 16, 8192);
+
+ int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/gpu_lightmapper/performance/region_size")));
+ int max_rays = GLOBAL_GET("rendering/gpu_lightmapper/performance/max_rays_per_pass");
+
+ int x_regions = (atlas_size.width - 1) / max_region_size + 1;
+ int y_regions = (atlas_size.height - 1) / max_region_size + 1;
+ int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
+
+ rd->submit();
+ rd->sync();
+
+ for (int b = 0; b < p_bounces; b++) {
+ int count = 0;
+ if (b > 0) {
+ SWAP(light_source_tex, light_dest_tex);
+ SWAP(secondary_uniform_set[0], secondary_uniform_set[1]);
+ }
+
+ for (int s = 0; s < atlas_slices; s++) {
+ push_constant.atlas_slice = s;
+
+ for (int i = 0; i < x_regions; i++) {
+ for (int j = 0; j < y_regions; j++) {
+ int x = i * max_region_size;
+ int y = j * max_region_size;
+ int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
+ int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
+
+ push_constant.region_ofs[0] = x;
+ push_constant.region_ofs[1] = y;
+
+ group_size = Vector3i((w - 1) / 8 + 1, (h - 1) / 8 + 1, 1);
+
+ for (int k = 0; k < ray_iterations; k++) {
+ RD::ComputeListID compute_list = rd->compute_list_begin();
+ rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
+ rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
+ rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set[0], 1);
+
+ push_constant.ray_from = k * max_rays;
+ push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
+ rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
+ rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
+
+ rd->compute_list_end(); //done
+ rd->submit();
+ rd->sync();
+
+ count++;
+ if (p_step_function) {
+ int total = (atlas_slices * x_regions * y_regions * ray_iterations);
+ int percent = count * 100 / total;
+ float p = float(count) / total * 0.1;
+ p_step_function(0.6 + p, vformat(TTR("Bounce %d/%d: Integrate indirect lighting %d%%"), b + 1, p_bounces, percent), p_bake_userdata, false);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /* LIGHPROBES */
+
+ RID light_probe_buffer;
+
+ if (probe_positions.size()) {
+ light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
+
+ if (p_step_function) {
+ p_step_function(0.7, TTR("Baking lightprobes"), p_bake_userdata, true);
+ }
+
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
+ u.binding = 0;
+ u.ids.push_back(light_probe_buffer);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 1;
+ u.ids.push_back(light_dest_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 2;
+ u.ids.push_back(light_primary_dynamic_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 3;
+ u.ids.push_back(light_environment_tex);
+ uniforms.push_back(u);
+ }
+ }
+ RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
+
+ switch (p_quality) {
+ case BAKE_QUALITY_LOW: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/low_quality_probe_ray_count");
+ } break;
+ case BAKE_QUALITY_MEDIUM: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/medium_quality_probe_ray_count");
+ } break;
+ case BAKE_QUALITY_HIGH: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/high_quality_probe_ray_count");
+ } break;
+ case BAKE_QUALITY_ULTRA: {
+ push_constant.ray_count = GLOBAL_GET("rendering/gpu_lightmapper/quality/ultra_quality_probe_ray_count");
+ } break;
+ }
+
+ push_constant.atlas_size[0] = probe_positions.size();
+ push_constant.ray_count = CLAMP(push_constant.ray_count, 16, 8192);
+
+ int max_rays = GLOBAL_GET("rendering/gpu_lightmapper/performance/max_rays_per_probe_pass");
+ int ray_iterations = (push_constant.ray_count - 1) / max_rays + 1;
+
+ for (int i = 0; i < ray_iterations; i++) {
+ RD::ComputeListID compute_list = rd->compute_list_begin();
+ rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
+ rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
+ rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
+
+ push_constant.ray_from = i * max_rays;
+ push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
+ rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
+ rd->compute_list_dispatch(compute_list, (probe_positions.size() - 1) / 64 + 1, 1, 1);
+
+ rd->compute_list_end(); //done
+ rd->submit();
+ rd->sync();
+
+ if (p_step_function) {
+ int percent = i * 100 / ray_iterations;
+ float p = float(i) / ray_iterations * 0.1;
+ p_step_function(0.7 + p, vformat(TTR("Integrating light probes %d%%"), percent), p_bake_userdata, false);
+ }
+ }
+
+ push_constant.atlas_size[0] = atlas_size.x; //restore
+ }
+
+#if 0
+ for (int i = 0; i < probe_positions.size(); i++) {
+ Ref<Image> img;
+ img.instance();
+ img->create(6, 4, false, Image::FORMAT_RGB8);
+ for (int j = 0; j < 6; j++) {
+ Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
+ Ref<Image> img2;
+ img2.instance();
+ img2->create(2, 2, false, Image::FORMAT_RGBAF, s);
+ img2->convert(Image::FORMAT_RGB8);
+ img->blit_rect(img2, Rect2(0, 0, 2, 2), Point2((j % 3) * 2, (j / 3) * 2));
+ }
+ img->save_png("res://3_light_probe_" + itos(i) + ".png");
+ }
+#endif
+
+ /* DENOISE */
+
+ if (p_use_denoiser) {
+ if (p_step_function) {
+ p_step_function(0.8, TTR("Denoising"), p_bake_userdata, true);
+ }
+
+ Ref<LightmapDenoiser> denoiser = LightmapDenoiser::create();
+ if (denoiser.is_valid()) {
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+
+ Ref<Image> denoised = denoiser->denoise_image(img);
+ if (denoised != img) {
+ denoised->convert(Image::FORMAT_RGBAH);
+ Vector<uint8_t> ds = denoised->get_data();
+ denoised.unref(); //avoid copy on write
+ { //restore alpha
+ uint32_t count = s.size() / 2; //uint16s
+ const uint16_t *src = (const uint16_t *)s.ptr();
+ uint16_t *dst = (uint16_t *)ds.ptrw();
+ for (uint32_t j = 0; j < count; j += 4) {
+ dst[j + 3] = src[j + 3];
+ }
+ }
+ rd->texture_update(light_accum_tex, i, ds, true);
+ }
+ }
+ }
+ }
+
+#ifdef DEBUG_TEXTURES
+
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://4_light_secondary_" + itos(i) + ".png");
+ }
+#endif
+
+ /* DILATE LIGHTMAP */
+ {
+ SWAP(light_accum_tex, light_accum_tex2);
+
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
+ u.binding = 0;
+ u.ids.push_back(light_accum_tex);
+ uniforms.push_back(u);
+ }
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 1;
+ u.ids.push_back(light_accum_tex2);
+ uniforms.push_back(u);
+ }
+ }
+
+ RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
+
+ RD::ComputeListID compute_list = rd->compute_list_begin();
+ rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
+ rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
+ rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
+ push_constant.region_ofs[0] = 0;
+ push_constant.region_ofs[1] = 0;
+ group_size = Vector3i((atlas_size.x - 1) / 8 + 1, (atlas_size.y - 1) / 8 + 1, 1); //restore group size
+
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ push_constant.atlas_slice = i;
+ rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
+ rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
+ //no barrier, let them run all together
+ }
+ rd->compute_list_end();
+ }
+
+#ifdef DEBUG_TEXTURES
+
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://5_dilated_" + itos(i) + ".png");
+ }
+#endif
+
+ /* BLEND SEAMS */
+ //shaders
+ Ref<RDShaderFile> blendseams_shader;
+ blendseams_shader.instance();
+ err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
+ if (err != OK) {
+ FREE_TEXTURES
+ FREE_BUFFERS
+ FREE_RASTER_RESOURCES
+ FREE_COMPUTE_RESOURCES
+ memdelete(rd);
+ blendseams_shader->print_errors("blendseams_shader");
+ }
+ ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
+
+ RID blendseams_line_raster_shader = rd->shader_create_from_bytecode(blendseams_shader->get_bytecode("lines"));
+
+ ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
+
+ RID blendseams_triangle_raster_shader = rd->shader_create_from_bytecode(blendseams_shader->get_bytecode("triangles"));
+
+ ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
+
+#define FREE_BLENDSEAMS_RESOURCES \
+ rd->free(blendseams_line_raster_shader); \
+ rd->free(blendseams_triangle_raster_shader);
+
+ {
+ //pre copy
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i, true);
+ }
+
+ Vector<RID> framebuffers;
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
+ Vector<RID> fb;
+ fb.push_back(slice_tex);
+ fb.push_back(raster_depth_buffer);
+ framebuffers.push_back(rd->framebuffer_create(fb));
+ }
+
+ Vector<RD::Uniform> uniforms;
+ {
+ {
+ RD::Uniform u;
+ u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
+ u.binding = 0;
+ u.ids.push_back(light_accum_tex2);
+ uniforms.push_back(u);
+ }
+ }
+
+ RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
+
+ bool debug = false;
+ RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
+ bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
+ bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
+
+ RD::PipelineDepthStencilState ds;
+ ds.enable_depth_test = true;
+ ds.enable_depth_write = true;
+ ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
+
+ RID blendseams_line_raster_pipeline = rd->render_pipeline_create(blendseams_line_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
+ RID blendseams_triangle_raster_pipeline = rd->render_pipeline_create(blendseams_triangle_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);
+
+ uint32_t seam_offset = 0;
+ uint32_t triangle_offset = 0;
+
+ Vector<Color> clear_colors;
+ clear_colors.push_back(Color(0, 0, 0, 1));
+ for (int i = 0; i < atlas_slices; i++) {
+ int subslices = (p_bake_sh ? 4 : 1);
+ for (int k = 0; k < subslices; k++) {
+ RasterSeamsPushConstant seams_push_constant;
+ seams_push_constant.slice = uint32_t(i * subslices + k);
+ seams_push_constant.debug = debug;
+
+ RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
+
+ rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
+ rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
+
+ const int uv_offset_count = 9;
+ static const Vector3 uv_offsets[uv_offset_count] = {
+ Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
+ Vector3(0, 1, 0.2),
+ Vector3(0, -1, 0.2),
+ Vector3(1, 0, 0.2),
+ Vector3(-1, 0, 0.2),
+ Vector3(-1, -1, 0.1),
+ Vector3(1, -1, 0.1),
+ Vector3(1, 1, 0.1),
+ Vector3(-1, 1, 0.1),
+ };
+
+ /* step 1 use lines to blend the edges */
+ {
+ seams_push_constant.base_index = seam_offset;
+ rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
+ seams_push_constant.uv_offset[0] = uv_offsets[0].x / float(atlas_size.width);
+ seams_push_constant.uv_offset[1] = uv_offsets[0].y / float(atlas_size.height);
+ seams_push_constant.blend = uv_offsets[0].z;
+
+ rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
+ rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
+ }
+
+ /* step 2 use triangles to mask the interior */
+
+ {
+ seams_push_constant.base_index = triangle_offset;
+ rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
+ seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
+
+ rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
+ rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
+ }
+ /* step 3 blend around the triangle */
+
+ rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
+
+ for (int j = 1; j < uv_offset_count; j++) {
+ seams_push_constant.base_index = seam_offset;
+ seams_push_constant.uv_offset[0] = uv_offsets[j].x / float(atlas_size.width);
+ seams_push_constant.uv_offset[1] = uv_offsets[j].y / float(atlas_size.height);
+ seams_push_constant.blend = uv_offsets[0].z;
+
+ rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
+ rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
+ }
+ rd->draw_list_end();
+ }
+ seam_offset += slice_seam_count[i];
+ triangle_offset += slice_triangle_count[i];
+ }
+ }
+
+#ifdef DEBUG_TEXTURES
+
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBA8);
+ img->save_png("res://5_blendseams" + itos(i) + ".png");
+ }
+#endif
+ if (p_step_function) {
+ p_step_function(0.9, TTR("Retrieving textures"), p_bake_userdata, true);
+ }
+
+ for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
+ Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
+ Ref<Image> img;
+ img.instance();
+ img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
+ img->convert(Image::FORMAT_RGBH); //remove alpha
+ bake_textures.push_back(img);
+ }
+
+ if (probe_positions.size() > 0) {
+ probe_values.resize(probe_positions.size() * 9);
+ Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
+ copymem(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
+ rd->free(light_probe_buffer);
+
+#ifdef DEBUG_TEXTURES
+ {
+ Ref<Image> img2;
+ img2.instance();
+ img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
+ img2->save_png("res://6_lightprobes.png");
+ }
+#endif
+ }
+
+ FREE_TEXTURES
+ FREE_BUFFERS
+ FREE_RASTER_RESOURCES
+ FREE_COMPUTE_RESOURCES
+ FREE_BLENDSEAMS_RESOURCES
+
+ memdelete(rd);
+
+ return BAKE_OK;
+}
+
+int LightmapperRD::get_bake_texture_count() const {
+ return bake_textures.size();
+}
+
+Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, bake_textures.size(), Ref<Image>());
+ return bake_textures[p_index];
+}
+
+int LightmapperRD::get_bake_mesh_count() const {
+ return mesh_instances.size();
+}
+
+Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
+ return mesh_instances[p_index].data.userdata;
+}
+
+Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
+ ERR_FAIL_COND_V(bake_textures.size() == 0, Rect2());
+ Rect2 uv_ofs;
+ Vector2 atlas_size = Vector2(bake_textures[0]->get_width(), bake_textures[0]->get_height());
+ uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
+ uv_ofs.size = Vector2(mesh_instances[p_index].data.albedo_on_uv2->get_width(), mesh_instances[p_index].data.albedo_on_uv2->get_height()) / atlas_size;
+ return uv_ofs;
+}
+
+int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
+ ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
+ return mesh_instances[p_index].slice;
+}
+
+int LightmapperRD::get_bake_probe_count() const {
+ return probe_positions.size();
+}
+
+Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
+ ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
+ return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
+}
+
+Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
+ ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
+ Vector<Color> ret;
+ ret.resize(9);
+ copymem(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
+ return ret;
+}
+
+LightmapperRD::LightmapperRD() {
+}
diff --git a/modules/lightmapper_rd/lightmapper_rd.h b/modules/lightmapper_rd/lightmapper_rd.h
new file mode 100644
index 0000000000..bb735baf6c
--- /dev/null
+++ b/modules/lightmapper_rd/lightmapper_rd.h
@@ -0,0 +1,258 @@
+/*************************************************************************/
+/* lightmapper_rd.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 LIGHTMAPPER_RD_H
+#define LIGHTMAPPER_RD_H
+
+#include "core/templates/local_vector.h"
+#include "scene/3d/lightmapper.h"
+#include "scene/resources/mesh.h"
+#include "servers/rendering/rendering_device.h"
+
+class LightmapperRD : public Lightmapper {
+ GDCLASS(LightmapperRD, Lightmapper)
+
+ struct MeshInstance {
+ MeshData data;
+ int slice = 0;
+ Vector2i offset;
+ };
+
+ struct Light {
+ float position[3];
+ uint32_t type = LIGHT_TYPE_DIRECTIONAL;
+ float direction[3];
+ float energy;
+ float color[3];
+ float size;
+ float range;
+ float attenuation;
+ float spot_angle;
+ float spot_attenuation;
+ uint32_t static_bake;
+ uint32_t pad[3];
+
+ bool operator<(const Light &p_light) const {
+ return type < p_light.type;
+ }
+ };
+
+ struct Vertex {
+ float position[3];
+ float normal_z;
+ float uv[2];
+ float normal_xy[2];
+
+ bool operator==(const Vertex &p_vtx) const {
+ return (position[0] == p_vtx.position[0]) &&
+ (position[1] == p_vtx.position[1]) &&
+ (position[2] == p_vtx.position[2]) &&
+ (uv[0] == p_vtx.uv[0]) &&
+ (uv[1] == p_vtx.uv[1]) &&
+ (normal_xy[0] == p_vtx.normal_xy[0]) &&
+ (normal_xy[1] == p_vtx.normal_xy[1]) &&
+ (normal_z == p_vtx.normal_z);
+ }
+ };
+
+ struct Edge {
+ Vector3 a;
+ Vector3 b;
+ Vector3 na;
+ Vector3 nb;
+ bool operator==(const Edge &p_seam) const {
+ return a == p_seam.a && b == p_seam.b && na == p_seam.na && nb == p_seam.nb;
+ }
+ Edge() {
+ }
+
+ Edge(const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_na, const Vector3 &p_nb) {
+ a = p_a;
+ b = p_b;
+ na = p_na;
+ nb = p_nb;
+ }
+ };
+
+ struct Probe {
+ float position[4];
+ };
+
+ Vector<Probe> probe_positions;
+
+ struct EdgeHash {
+ _FORCE_INLINE_ static uint32_t hash(const Edge &p_edge) {
+ uint32_t h = hash_djb2_one_float(p_edge.a.x);
+ h = hash_djb2_one_float(p_edge.a.y, h);
+ h = hash_djb2_one_float(p_edge.a.z, h);
+ h = hash_djb2_one_float(p_edge.b.x, h);
+ h = hash_djb2_one_float(p_edge.b.y, h);
+ h = hash_djb2_one_float(p_edge.b.z, h);
+ return h;
+ }
+ };
+ struct EdgeUV2 {
+ Vector2 a;
+ Vector2 b;
+ Vector2i indices;
+ bool operator==(const EdgeUV2 &p_uv2) const {
+ return a == p_uv2.a && b == p_uv2.b;
+ }
+ bool seam_found = false;
+ EdgeUV2(Vector2 p_a, Vector2 p_b, Vector2i p_indices) {
+ a = p_a;
+ b = p_b;
+ indices = p_indices;
+ }
+ EdgeUV2() {}
+ };
+
+ struct Seam {
+ Vector2i a;
+ Vector2i b;
+ uint32_t slice;
+ bool operator<(const Seam &p_seam) const {
+ return slice < p_seam.slice;
+ }
+ };
+
+ struct VertexHash {
+ _FORCE_INLINE_ static uint32_t hash(const Vertex &p_vtx) {
+ uint32_t h = hash_djb2_one_float(p_vtx.position[0]);
+ h = hash_djb2_one_float(p_vtx.position[1], h);
+ h = hash_djb2_one_float(p_vtx.position[2], h);
+ h = hash_djb2_one_float(p_vtx.uv[0], h);
+ h = hash_djb2_one_float(p_vtx.uv[1], h);
+ h = hash_djb2_one_float(p_vtx.normal_xy[0], h);
+ h = hash_djb2_one_float(p_vtx.normal_xy[1], h);
+ h = hash_djb2_one_float(p_vtx.normal_z, h);
+ return h;
+ }
+ };
+
+ struct Box {
+ float min_bounds[3];
+ float pad0;
+ float max_bounds[3];
+ float pad1;
+ };
+
+ struct Triangle {
+ uint32_t indices[3];
+ uint32_t slice;
+ bool operator<(const Triangle &p_triangle) const {
+ return slice < p_triangle.slice;
+ }
+ };
+
+ Vector<MeshInstance> mesh_instances;
+
+ Vector<Light> lights;
+
+ struct TriangleSort {
+ uint32_t cell_index;
+ uint32_t triangle_index;
+ bool operator<(const TriangleSort &p_triangle_sort) const {
+ return cell_index < p_triangle_sort.cell_index; //sorting by triangle index in this case makes no sense
+ }
+ };
+
+ void _plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[], uint32_t p_triangle_index, LocalVector<TriangleSort> &triangles, uint32_t p_grid_size);
+
+ struct RasterPushConstant {
+ float atlas_size[2];
+ float uv_offset[2];
+ float to_cell_size[3];
+ uint32_t base_triangle;
+ float to_cell_offset[3];
+ float bias;
+ int32_t grid_size[3];
+ uint32_t pad2;
+ };
+
+ struct RasterSeamsPushConstant {
+ uint32_t base_index;
+ uint32_t slice;
+ float uv_offset[2];
+ uint32_t debug;
+ float blend;
+ uint32_t pad[2];
+ };
+
+ struct PushConstant {
+ int32_t atlas_size[2];
+ uint32_t ray_count;
+ uint32_t ray_to;
+
+ float world_size[3];
+ float bias;
+
+ float to_cell_offset[3];
+ uint32_t ray_from;
+
+ float to_cell_size[3];
+ uint32_t light_count;
+
+ int32_t grid_size;
+ int32_t atlas_slice;
+ int32_t region_ofs[2];
+
+ float environment_xform[12];
+ };
+
+ Vector<Ref<Image>> bake_textures;
+ Vector<Color> probe_values;
+
+ BakeError _blit_meshes_into_atlas(int p_max_texture_size, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, BakeStepFunc p_step_function, void *p_bake_userdata);
+ void _create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, Vector<Probe> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &grid_texture_sdf, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata);
+ void _raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform);
+
+public:
+ virtual void add_mesh(const MeshData &p_mesh) override;
+ virtual void add_directional_light(bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_angular_distance) override;
+ virtual void add_omni_light(bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_size) override;
+ virtual void add_spot_light(bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size) override;
+ virtual void add_probe(const Vector3 &p_position) override;
+ virtual BakeError bake(BakeQuality p_quality, bool p_use_denoiser, int p_bounces, float p_bias, int p_max_texture_size, bool p_bake_sh, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function = nullptr, void *p_bake_userdata = nullptr) override;
+
+ int get_bake_texture_count() const override;
+ Ref<Image> get_bake_texture(int p_index) const override;
+ int get_bake_mesh_count() const override;
+ Variant get_bake_mesh_userdata(int p_index) const override;
+ Rect2 get_bake_mesh_uv_scale(int p_index) const override;
+ int get_bake_mesh_texture_slice(int p_index) const override;
+ int get_bake_probe_count() const override;
+ Vector3 get_bake_probe_point(int p_probe) const override;
+ Vector<Color> get_bake_probe_sh(int p_probe) const override;
+
+ LightmapperRD();
+};
+
+#endif // LIGHTMAPPER_H
diff --git a/modules/lightmapper_rd/lm_blendseams.glsl b/modules/lightmapper_rd/lm_blendseams.glsl
new file mode 100644
index 0000000000..e47e5fcc51
--- /dev/null
+++ b/modules/lightmapper_rd/lm_blendseams.glsl
@@ -0,0 +1,108 @@
+#[versions]
+
+lines = "#define MODE_LINES";
+triangles = "#define MODE_TRIANGLES";
+
+#[vertex]
+
+#version 450
+
+VERSION_DEFINES
+
+#include "lm_common_inc.glsl"
+
+layout(push_constant, binding = 0, std430) uniform Params {
+ uint base_index;
+ uint slice;
+ vec2 uv_offset;
+ bool debug;
+ float blend;
+ uint pad[2];
+}
+params;
+
+layout(location = 0) out vec3 uv_interp;
+
+void main() {
+#ifdef MODE_TRIANGLES
+ uint triangle_idx = params.base_index + gl_VertexIndex / 3;
+ uint triangle_subidx = gl_VertexIndex % 3;
+
+ vec2 uv;
+ if (triangle_subidx == 0) {
+ uv = vertices.data[triangles.data[triangle_idx].indices.x].uv;
+ } else if (triangle_subidx == 1) {
+ uv = vertices.data[triangles.data[triangle_idx].indices.y].uv;
+ } else {
+ uv = vertices.data[triangles.data[triangle_idx].indices.z].uv;
+ }
+
+ uv_interp = vec3(uv, float(params.slice));
+ gl_Position = vec4((uv + params.uv_offset) * 2.0 - 1.0, 0.0001, 1.0);
+#endif
+
+#ifdef MODE_LINES
+ uint seam_idx = params.base_index + gl_VertexIndex / 4;
+ uint seam_subidx = gl_VertexIndex % 4;
+
+ uint src_idx;
+ uint dst_idx;
+
+ if (seam_subidx == 0) {
+ src_idx = seams.data[seam_idx].b.x;
+ dst_idx = seams.data[seam_idx].a.x;
+ } else if (seam_subidx == 1) {
+ src_idx = seams.data[seam_idx].b.y;
+ dst_idx = seams.data[seam_idx].a.y;
+ } else if (seam_subidx == 2) {
+ src_idx = seams.data[seam_idx].a.x;
+ dst_idx = seams.data[seam_idx].b.x;
+ } else if (seam_subidx == 3) {
+ src_idx = seams.data[seam_idx].a.y;
+ dst_idx = seams.data[seam_idx].b.y;
+ }
+
+ vec2 src_uv = vertices.data[src_idx].uv;
+ vec2 dst_uv = vertices.data[dst_idx].uv + params.uv_offset;
+
+ uv_interp = vec3(src_uv, float(params.slice));
+ gl_Position = vec4(dst_uv * 2.0 - 1.0, 0.0001, 1.0);
+#endif
+}
+
+#[fragment]
+
+#version 450
+
+VERSION_DEFINES
+
+#include "lm_common_inc.glsl"
+
+layout(push_constant, binding = 0, std430) uniform Params {
+ uint base_index;
+ uint slice;
+ vec2 uv_offset;
+ bool debug;
+ float blend;
+ uint pad[2];
+}
+params;
+
+layout(location = 0) in vec3 uv_interp;
+
+layout(location = 0) out vec4 dst_color;
+
+layout(set = 1, binding = 0) uniform texture2DArray src_color_tex;
+
+void main() {
+ if (params.debug) {
+#ifdef MODE_TRIANGLES
+ dst_color = vec4(1, 0, 1, 1);
+#else
+ dst_color = vec4(1, 1, 0, 1);
+#endif
+ } else {
+ vec4 src_color = textureLod(sampler2DArray(src_color_tex, linear_sampler), uv_interp, 0.0);
+ dst_color = vec4(src_color.rgb, params.blend); //mix
+ }
+}
diff --git a/modules/lightmapper_rd/lm_common_inc.glsl b/modules/lightmapper_rd/lm_common_inc.glsl
new file mode 100644
index 0000000000..0ff455936e
--- /dev/null
+++ b/modules/lightmapper_rd/lm_common_inc.glsl
@@ -0,0 +1,92 @@
+
+/* SET 0, static data that does not change between any call */
+
+struct Vertex {
+ vec3 position;
+ float normal_z;
+ vec2 uv;
+ vec2 normal_xy;
+};
+
+layout(set = 0, binding = 1, std430) restrict readonly buffer Vertices {
+ Vertex data[];
+}
+vertices;
+
+struct Triangle {
+ uvec3 indices;
+ uint slice;
+};
+
+layout(set = 0, binding = 2, std430) restrict readonly buffer Triangles {
+ Triangle data[];
+}
+triangles;
+
+struct Box {
+ vec3 min_bounds;
+ uint pad0;
+ vec3 max_bounds;
+ uint pad1;
+};
+
+layout(set = 0, binding = 3, std430) restrict readonly buffer Boxes {
+ Box data[];
+}
+boxes;
+
+layout(set = 0, binding = 4, std430) restrict readonly buffer GridIndices {
+ uint data[];
+}
+grid_indices;
+
+#define LIGHT_TYPE_DIRECTIONAL 0
+#define LIGHT_TYPE_OMNI 1
+#define LIGHT_TYPE_SPOT 2
+
+struct Light {
+ vec3 position;
+ uint type;
+
+ vec3 direction;
+ float energy;
+
+ vec3 color;
+ float size;
+
+ float range;
+ float attenuation;
+ float spot_angle;
+ float spot_attenuation;
+
+ bool static_bake;
+ uint pad[3];
+};
+
+layout(set = 0, binding = 5, std430) restrict readonly buffer Lights {
+ Light data[];
+}
+lights;
+
+struct Seam {
+ uvec2 a;
+ uvec2 b;
+};
+
+layout(set = 0, binding = 6, std430) restrict readonly buffer Seams {
+ Seam data[];
+}
+seams;
+
+layout(set = 0, binding = 7, std430) restrict readonly buffer Probes {
+ vec4 data[];
+}
+probe_positions;
+
+layout(set = 0, binding = 8) uniform utexture3D grid;
+layout(set = 0, binding = 9) uniform texture3D grid_sdf;
+
+layout(set = 0, binding = 10) uniform texture2DArray albedo_tex;
+layout(set = 0, binding = 11) uniform texture2DArray emission_tex;
+
+layout(set = 0, binding = 12) uniform sampler linear_sampler;
diff --git a/modules/lightmapper_rd/lm_compute.glsl b/modules/lightmapper_rd/lm_compute.glsl
new file mode 100644
index 0000000000..8a9adbc5cc
--- /dev/null
+++ b/modules/lightmapper_rd/lm_compute.glsl
@@ -0,0 +1,653 @@
+#[versions]
+
+primary = "#define MODE_DIRECT_LIGHT";
+secondary = "#define MODE_BOUNCE_LIGHT";
+dilate = "#define MODE_DILATE";
+unocclude = "#define MODE_UNOCCLUDE";
+light_probes = "#define MODE_LIGHT_PROBES";
+
+#[compute]
+
+#version 450
+
+VERSION_DEFINES
+
+// One 2D local group focusing in one layer at a time, though all
+// in parallel (no barriers) makes more sense than a 3D local group
+// as this can take more advantage of the cache for each group.
+
+#ifdef MODE_LIGHT_PROBES
+
+layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
+
+#else
+
+layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
+
+#endif
+
+#include "lm_common_inc.glsl"
+
+#ifdef MODE_LIGHT_PROBES
+
+layout(set = 1, binding = 0, std430) restrict buffer LightProbeData {
+ vec4 data[];
+}
+light_probes;
+
+layout(set = 1, binding = 1) uniform texture2DArray source_light;
+layout(set = 1, binding = 2) uniform texture2DArray source_direct_light; //also need the direct light, which was omitted
+layout(set = 1, binding = 3) uniform texture2D environment;
+#endif
+
+#ifdef MODE_UNOCCLUDE
+
+layout(rgba32f, set = 1, binding = 0) uniform restrict image2DArray position;
+layout(rgba32f, set = 1, binding = 1) uniform restrict readonly image2DArray unocclude;
+
+#endif
+
+#if defined(MODE_DIRECT_LIGHT) || defined(MODE_BOUNCE_LIGHT)
+
+layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
+layout(set = 1, binding = 1) uniform texture2DArray source_light;
+layout(set = 1, binding = 2) uniform texture2DArray source_position;
+layout(set = 1, binding = 3) uniform texture2DArray source_normal;
+layout(rgba16f, set = 1, binding = 4) uniform restrict image2DArray accum_light;
+
+#endif
+
+#ifdef MODE_BOUNCE_LIGHT
+layout(rgba32f, set = 1, binding = 5) uniform restrict image2DArray bounce_accum;
+layout(set = 1, binding = 6) uniform texture2D environment;
+#endif
+#ifdef MODE_DIRECT_LIGHT
+layout(rgba32f, set = 1, binding = 5) uniform restrict writeonly image2DArray primary_dynamic;
+#endif
+
+#ifdef MODE_DILATE
+layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
+layout(set = 1, binding = 1) uniform texture2DArray source_light;
+#endif
+
+layout(push_constant, binding = 0, std430) uniform Params {
+ ivec2 atlas_size; // x used for light probe mode total probes
+ uint ray_count;
+ uint ray_to;
+
+ vec3 world_size;
+ float bias;
+
+ vec3 to_cell_offset;
+ uint ray_from;
+
+ vec3 to_cell_size;
+ uint light_count;
+
+ int grid_size;
+ int atlas_slice;
+ ivec2 region_ofs;
+
+ mat3x4 env_transform;
+}
+params;
+
+//check it, but also return distance and barycentric coords (for uv lookup)
+bool ray_hits_triangle(vec3 from, vec3 dir, float max_dist, vec3 p0, vec3 p1, vec3 p2, out float r_distance, out vec3 r_barycentric) {
+ const vec3 e0 = p1 - p0;
+ const vec3 e1 = p0 - p2;
+ vec3 triangleNormal = cross(e1, e0);
+
+ const vec3 e2 = (1.0 / dot(triangleNormal, dir)) * (p0 - from);
+ const vec3 i = cross(dir, e2);
+
+ r_barycentric.y = dot(i, e1);
+ r_barycentric.z = dot(i, e0);
+ r_barycentric.x = 1.0 - (r_barycentric.z + r_barycentric.y);
+ r_distance = dot(triangleNormal, e2);
+ return (r_distance > params.bias) && (r_distance < max_dist) && all(greaterThanEqual(r_barycentric, vec3(0.0)));
+}
+
+bool trace_ray(vec3 p_from, vec3 p_to
+#if defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
+ ,
+ out uint r_triangle, out vec3 r_barycentric
+#endif
+#if defined(MODE_UNOCCLUDE)
+ ,
+ out float r_distance, out vec3 r_normal
+#endif
+) {
+ /* world coords */
+
+ vec3 rel = p_to - p_from;
+ float rel_len = length(rel);
+ vec3 dir = normalize(rel);
+ vec3 inv_dir = 1.0 / dir;
+
+ /* cell coords */
+
+ vec3 from_cell = (p_from - params.to_cell_offset) * params.to_cell_size;
+ vec3 to_cell = (p_to - params.to_cell_offset) * params.to_cell_size;
+
+ //prepare DDA
+ vec3 rel_cell = to_cell - from_cell;
+ ivec3 icell = ivec3(from_cell);
+ ivec3 iendcell = ivec3(to_cell);
+ vec3 dir_cell = normalize(rel_cell);
+ vec3 delta = abs(1.0 / dir_cell); //vec3(length(rel_cell)) / rel_cell);
+ ivec3 step = ivec3(sign(rel_cell));
+ vec3 side = (sign(rel_cell) * (vec3(icell) - from_cell) + (sign(rel_cell) * 0.5) + 0.5) * delta;
+
+ uint iters = 0;
+ while (all(greaterThanEqual(icell, ivec3(0))) && all(lessThan(icell, ivec3(params.grid_size))) && iters < 1000) {
+ uvec2 cell_data = texelFetch(usampler3D(grid, linear_sampler), icell, 0).xy;
+ if (cell_data.x > 0) { //triangles here
+ bool hit = false;
+#if defined(MODE_UNOCCLUDE)
+ bool hit_backface = false;
+#endif
+ float best_distance = 1e20;
+
+ for (uint i = 0; i < cell_data.x; i++) {
+ uint tidx = grid_indices.data[cell_data.y + i];
+
+ //Ray-Box test
+ vec3 t0 = (boxes.data[tidx].min_bounds - p_from) * inv_dir;
+ vec3 t1 = (boxes.data[tidx].max_bounds - p_from) * inv_dir;
+ vec3 tmin = min(t0, t1), tmax = max(t0, t1);
+
+ if (max(tmin.x, max(tmin.y, tmin.z)) <= min(tmax.x, min(tmax.y, tmax.z))) {
+ continue; //ray box failed
+ }
+
+ //prepare triangle vertices
+ vec3 vtx0 = vertices.data[triangles.data[tidx].indices.x].position;
+ vec3 vtx1 = vertices.data[triangles.data[tidx].indices.y].position;
+ vec3 vtx2 = vertices.data[triangles.data[tidx].indices.z].position;
+#if defined(MODE_UNOCCLUDE)
+ vec3 normal = -normalize(cross((vtx0 - vtx1), (vtx0 - vtx2)));
+
+ bool backface = dot(normal, dir) >= 0.0;
+#endif
+ float distance;
+ vec3 barycentric;
+
+ if (ray_hits_triangle(p_from, dir, rel_len, vtx0, vtx1, vtx2, distance, barycentric)) {
+#ifdef MODE_DIRECT_LIGHT
+ return true; //any hit good
+#endif
+
+#if defined(MODE_UNOCCLUDE)
+ if (!backface) {
+ // the case of meshes having both a front and back face in the same plane is more common than
+ // expected, so if this is a front-face, bias it closer to the ray origin, so it always wins over the back-face
+ distance = max(params.bias, distance - params.bias);
+ }
+
+ hit = true;
+
+ if (distance < best_distance) {
+ hit_backface = backface;
+ best_distance = distance;
+ r_distance = distance;
+ r_normal = normal;
+ }
+
+#endif
+
+#if defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
+
+ hit = true;
+ if (distance < best_distance) {
+ best_distance = distance;
+ r_triangle = tidx;
+ r_barycentric = barycentric;
+ }
+#endif
+ }
+ }
+#if defined(MODE_UNOCCLUDE)
+
+ if (hit) {
+ return hit_backface;
+ }
+#endif
+#if defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
+ if (hit) {
+ return true;
+ }
+#endif
+ }
+
+ if (icell == iendcell) {
+ break;
+ }
+
+ bvec3 mask = lessThanEqual(side.xyz, min(side.yzx, side.zxy));
+ side += vec3(mask) * delta;
+ icell += ivec3(vec3(mask)) * step;
+
+ iters++;
+ }
+
+ return false;
+}
+
+const float PI = 3.14159265f;
+const float GOLDEN_ANGLE = PI * (3.0 - sqrt(5.0));
+
+vec3 vogel_hemisphere(uint p_index, uint p_count, float p_offset) {
+ float r = sqrt(float(p_index) + 0.5f) / sqrt(float(p_count));
+ float theta = float(p_index) * GOLDEN_ANGLE + p_offset;
+ float y = cos(r * PI * 0.5);
+ float l = sin(r * PI * 0.5);
+ return vec3(l * cos(theta), l * sin(theta), y);
+}
+
+float quick_hash(vec2 pos) {
+ return fract(sin(dot(pos * 19.19, vec2(49.5791, 97.413))) * 49831.189237);
+}
+
+float get_omni_attenuation(float distance, float inv_range, float decay) {
+ float nd = distance * inv_range;
+ nd *= nd;
+ nd *= nd; // nd^4
+ nd = max(1.0 - nd, 0.0);
+ nd *= nd; // nd^2
+ return nd * pow(max(distance, 0.0001), -decay);
+}
+
+void main() {
+#ifdef MODE_LIGHT_PROBES
+ int probe_index = int(gl_GlobalInvocationID.x);
+ if (probe_index >= params.atlas_size.x) { //too large, do nothing
+ return;
+ }
+
+#else
+ ivec2 atlas_pos = ivec2(gl_GlobalInvocationID.xy) + params.region_ofs;
+ if (any(greaterThanEqual(atlas_pos, params.atlas_size))) { //too large, do nothing
+ return;
+ }
+#endif
+
+#ifdef MODE_DIRECT_LIGHT
+
+ vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
+ if (length(normal) < 0.5) {
+ return; //empty texel, no process
+ }
+ vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
+
+ //go through all lights
+ //start by own light (emissive)
+ vec3 static_light = vec3(0.0);
+ vec3 dynamic_light = vec3(0.0);
+
+#ifdef USE_SH_LIGHTMAPS
+ vec4 sh_accum[4] = vec4[](
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0));
+#endif
+
+ for (uint i = 0; i < params.light_count; i++) {
+ vec3 light_pos;
+ float attenuation;
+ if (lights.data[i].type == LIGHT_TYPE_DIRECTIONAL) {
+ vec3 light_vec = lights.data[i].direction;
+ light_pos = position - light_vec * length(params.world_size);
+ attenuation = 1.0;
+ } else {
+ light_pos = lights.data[i].position;
+ float d = distance(position, light_pos);
+ if (d > lights.data[i].range) {
+ continue;
+ }
+
+ d /= lights.data[i].range;
+
+ attenuation = get_omni_attenuation(d, 1.0 / lights.data[i].range, lights.data[i].attenuation);
+
+ if (lights.data[i].type == LIGHT_TYPE_SPOT) {
+ vec3 rel = normalize(position - light_pos);
+ float angle = acos(dot(rel, lights.data[i].direction));
+ if (angle > lights.data[i].spot_angle) {
+ continue; //invisible, dont try
+ }
+
+ float d = clamp(angle / lights.data[i].spot_angle, 0, 1);
+ attenuation *= pow(1.0 - d, lights.data[i].spot_attenuation);
+ }
+ }
+
+ vec3 light_dir = normalize(light_pos - position);
+ attenuation *= max(0.0, dot(normal, light_dir));
+
+ if (attenuation <= 0.0001) {
+ continue; //no need to do anything
+ }
+
+ if (!trace_ray(position + light_dir * params.bias, light_pos)) {
+ vec3 light = lights.data[i].color * lights.data[i].energy * attenuation;
+ if (lights.data[i].static_bake) {
+ static_light += light;
+#ifdef USE_SH_LIGHTMAPS
+
+ float c[4] = float[](
+ 0.282095, //l0
+ 0.488603 * light_dir.y, //l1n1
+ 0.488603 * light_dir.z, //l1n0
+ 0.488603 * light_dir.x //l1p1
+ );
+
+ for (uint j = 0; j < 4; j++) {
+ sh_accum[j].rgb += light * c[j] * (1.0 / 3.0);
+ }
+#endif
+
+ } else {
+ dynamic_light += light;
+ }
+ }
+ }
+
+ vec3 albedo = texelFetch(sampler2DArray(albedo_tex, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).rgb;
+ vec3 emissive = texelFetch(sampler2DArray(emission_tex, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).rgb;
+
+ dynamic_light *= albedo; //if it will bounce, must multiply by albedo
+ dynamic_light += emissive;
+
+ //keep for lightprobes
+ imageStore(primary_dynamic, ivec3(atlas_pos, params.atlas_slice), vec4(dynamic_light, 1.0));
+
+ dynamic_light += static_light * albedo; //send for bounces
+ imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), vec4(dynamic_light, 1.0));
+
+#ifdef USE_SH_LIGHTMAPS
+ //keep for adding at the end
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 0), sh_accum[0]);
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 1), sh_accum[1]);
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 2), sh_accum[2]);
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 3), sh_accum[3]);
+
+#else
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), vec4(static_light, 1.0));
+#endif
+
+#endif
+
+#ifdef MODE_BOUNCE_LIGHT
+
+ vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
+ if (length(normal) < 0.5) {
+ return; //empty texel, no process
+ }
+
+ vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
+
+ vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
+ vec3 tangent = normalize(cross(v0, normal));
+ vec3 bitangent = normalize(cross(tangent, normal));
+ mat3 normal_mat = mat3(tangent, bitangent, normal);
+
+#ifdef USE_SH_LIGHTMAPS
+ vec4 sh_accum[4] = vec4[](
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0),
+ vec4(0.0, 0.0, 0.0, 1.0));
+#endif
+ vec3 light_average = vec3(0.0);
+ for (uint i = params.ray_from; i < params.ray_to; i++) {
+ vec3 ray_dir = normal_mat * vogel_hemisphere(i, params.ray_count, quick_hash(vec2(atlas_pos)));
+
+ uint tidx;
+ vec3 barycentric;
+
+ vec3 light;
+ if (trace_ray(position + ray_dir * params.bias, position + ray_dir * length(params.world_size), tidx, barycentric)) {
+ //hit a triangle
+ vec2 uv0 = vertices.data[triangles.data[tidx].indices.x].uv;
+ vec2 uv1 = vertices.data[triangles.data[tidx].indices.y].uv;
+ vec2 uv2 = vertices.data[triangles.data[tidx].indices.z].uv;
+ vec3 uvw = vec3(barycentric.x * uv0 + barycentric.y * uv1 + barycentric.z * uv2, float(triangles.data[tidx].slice));
+
+ light = textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb;
+ } else {
+ //did not hit a triangle, reach out for the sky
+ vec3 sky_dir = normalize(mat3(params.env_transform) * ray_dir);
+
+ vec2 st = vec2(
+ atan(sky_dir.x, sky_dir.z),
+ acos(sky_dir.y));
+
+ if (st.x < 0.0)
+ st.x += PI * 2.0;
+
+ st /= vec2(PI * 2.0, PI);
+
+ light = textureLod(sampler2D(environment, linear_sampler), st, 0.0).rgb;
+ }
+
+ light_average += light;
+
+#ifdef USE_SH_LIGHTMAPS
+
+ float c[4] = float[](
+ 0.282095, //l0
+ 0.488603 * ray_dir.y, //l1n1
+ 0.488603 * ray_dir.z, //l1n0
+ 0.488603 * ray_dir.x //l1p1
+ );
+
+ for (uint j = 0; j < 4; j++) {
+ sh_accum[j].rgb += light * c[j] * (8.0 / float(params.ray_count));
+ }
+#endif
+ }
+
+ vec3 light_total;
+ if (params.ray_from == 0) {
+ light_total = vec3(0.0);
+ } else {
+ light_total = imageLoad(bounce_accum, ivec3(atlas_pos, params.atlas_slice)).rgb;
+ }
+
+ light_total += light_average;
+
+#ifdef USE_SH_LIGHTMAPS
+
+ for (int i = 0; i < 4; i++) {
+ vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i));
+ accum.rgb += sh_accum[i].rgb;
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i), accum);
+ }
+
+#endif
+ if (params.ray_to == params.ray_count) {
+ light_total /= float(params.ray_count);
+ imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), vec4(light_total, 1.0));
+#ifndef USE_SH_LIGHTMAPS
+ vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice));
+ accum.rgb += light_total;
+ imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), accum);
+#endif
+ } else {
+ imageStore(bounce_accum, ivec3(atlas_pos, params.atlas_slice), vec4(light_total, 1.0));
+ }
+
+#endif
+
+#ifdef MODE_UNOCCLUDE
+
+ //texel_size = 0.5;
+ //compute tangents
+
+ vec4 position_alpha = imageLoad(position, ivec3(atlas_pos, params.atlas_slice));
+ if (position_alpha.a < 0.5) {
+ return;
+ }
+
+ vec3 vertex_pos = position_alpha.xyz;
+ vec4 normal_tsize = imageLoad(unocclude, ivec3(atlas_pos, params.atlas_slice));
+
+ vec3 face_normal = normal_tsize.xyz;
+ float texel_size = normal_tsize.w;
+
+ vec3 v0 = abs(face_normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
+ vec3 tangent = normalize(cross(v0, face_normal));
+ vec3 bitangent = normalize(cross(tangent, face_normal));
+ vec3 base_pos = vertex_pos + face_normal * params.bias; //raise a bit
+
+ vec3 rays[4] = vec3[](tangent, bitangent, -tangent, -bitangent);
+ float min_d = 1e20;
+ for (int i = 0; i < 4; i++) {
+ vec3 ray_to = base_pos + rays[i] * texel_size;
+ float d;
+ vec3 norm;
+
+ if (trace_ray(base_pos, ray_to, d, norm)) {
+ if (d < min_d) {
+ vertex_pos = base_pos + rays[i] * d + norm * params.bias * 10.0; //this bias needs to be greater than the regular bias, because otherwise later, rays will go the other side when pointing back.
+ min_d = d;
+ }
+ }
+ }
+
+ position_alpha.xyz = vertex_pos;
+
+ imageStore(position, ivec3(atlas_pos, params.atlas_slice), position_alpha);
+
+#endif
+
+#ifdef MODE_LIGHT_PROBES
+
+ vec3 position = probe_positions.data[probe_index].xyz;
+
+ vec4 probe_sh_accum[9] = vec4[](
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0),
+ vec4(0.0));
+
+ for (uint i = params.ray_from; i < params.ray_to; i++) {
+ vec3 ray_dir = vogel_hemisphere(i, params.ray_count, quick_hash(vec2(float(probe_index), 0.0)));
+ if (bool(i & 1)) {
+ //throw to both sides, so alternate them
+ ray_dir.z *= -1.0;
+ }
+
+ uint tidx;
+ vec3 barycentric;
+ vec3 light;
+
+ if (trace_ray(position + ray_dir * params.bias, position + ray_dir * length(params.world_size), tidx, barycentric)) {
+ vec2 uv0 = vertices.data[triangles.data[tidx].indices.x].uv;
+ vec2 uv1 = vertices.data[triangles.data[tidx].indices.y].uv;
+ vec2 uv2 = vertices.data[triangles.data[tidx].indices.z].uv;
+ vec3 uvw = vec3(barycentric.x * uv0 + barycentric.y * uv1 + barycentric.z * uv2, float(triangles.data[tidx].slice));
+
+ light = textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb;
+ light += textureLod(sampler2DArray(source_direct_light, linear_sampler), uvw, 0.0).rgb;
+ } else {
+ //did not hit a triangle, reach out for the sky
+ vec3 sky_dir = normalize(mat3(params.env_transform) * ray_dir);
+
+ vec2 st = vec2(
+ atan(sky_dir.x, sky_dir.z),
+ acos(sky_dir.y));
+
+ if (st.x < 0.0)
+ st.x += PI * 2.0;
+
+ st /= vec2(PI * 2.0, PI);
+
+ light = textureLod(sampler2D(environment, linear_sampler), st, 0.0).rgb;
+ }
+
+ {
+ float c[9] = float[](
+ 0.282095, //l0
+ 0.488603 * ray_dir.y, //l1n1
+ 0.488603 * ray_dir.z, //l1n0
+ 0.488603 * ray_dir.x, //l1p1
+ 1.092548 * ray_dir.x * ray_dir.y, //l2n2
+ 1.092548 * ray_dir.y * ray_dir.z, //l2n1
+ //0.315392 * (ray_dir.x * ray_dir.x + ray_dir.y * ray_dir.y + 2.0 * ray_dir.z * ray_dir.z), //l20
+ 0.315392 * (3.0 * ray_dir.z * ray_dir.z - 1.0), //l20
+ 1.092548 * ray_dir.x * ray_dir.z, //l2p1
+ 0.546274 * (ray_dir.x * ray_dir.x - ray_dir.y * ray_dir.y) //l2p2
+ );
+
+ for (uint j = 0; j < 9; j++) {
+ probe_sh_accum[j].rgb += light * c[j];
+ }
+ }
+ }
+
+ if (params.ray_from > 0) {
+ for (uint j = 0; j < 9; j++) { //accum from existing
+ probe_sh_accum[j] += light_probes.data[probe_index * 9 + j];
+ }
+ }
+
+ if (params.ray_to == params.ray_count) {
+ for (uint j = 0; j < 9; j++) { //accum from existing
+ probe_sh_accum[j] *= 4.0 / float(params.ray_count);
+ }
+ }
+
+ for (uint j = 0; j < 9; j++) { //accum from existing
+ light_probes.data[probe_index * 9 + j] = probe_sh_accum[j];
+ }
+
+#endif
+
+#ifdef MODE_DILATE
+
+ vec4 c = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0);
+ //sides first, as they are closer
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 0), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, 1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 0), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, -1), params.atlas_slice), 0);
+ //endpoints second
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, -1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, -1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 1), params.atlas_slice), 0);
+
+ //far sides third
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 0), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, 2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 0), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, -2), params.atlas_slice), 0);
+
+ //far-mid endpoints
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, -1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, -1), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 1), params.atlas_slice), 0);
+
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, -2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, -2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 2), params.atlas_slice), 0);
+ //far endpoints
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, -2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, -2), params.atlas_slice), 0);
+ c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 2), params.atlas_slice), 0);
+
+ imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), c);
+
+#endif
+}
diff --git a/modules/lightmapper_rd/lm_raster.glsl b/modules/lightmapper_rd/lm_raster.glsl
new file mode 100644
index 0000000000..6c2904192b
--- /dev/null
+++ b/modules/lightmapper_rd/lm_raster.glsl
@@ -0,0 +1,157 @@
+#[vertex]
+
+#version 450
+
+VERSION_DEFINES
+
+#include "lm_common_inc.glsl"
+
+layout(location = 0) out vec3 vertex_interp;
+layout(location = 1) out vec3 normal_interp;
+layout(location = 2) out vec2 uv_interp;
+layout(location = 3) out vec3 barycentric;
+layout(location = 4) flat out uvec3 vertex_indices;
+layout(location = 5) flat out vec3 face_normal;
+
+layout(push_constant, binding = 0, std430) uniform Params {
+ vec2 atlas_size;
+ vec2 uv_offset;
+ vec3 to_cell_size;
+ uint base_triangle;
+ vec3 to_cell_offset;
+ float bias;
+ ivec3 grid_size;
+ uint pad2;
+}
+params;
+
+void main() {
+ uint triangle_idx = params.base_triangle + gl_VertexIndex / 3;
+ uint triangle_subidx = gl_VertexIndex % 3;
+
+ vertex_indices = triangles.data[triangle_idx].indices;
+
+ uint vertex_idx;
+ if (triangle_subidx == 0) {
+ vertex_idx = vertex_indices.x;
+ barycentric = vec3(1, 0, 0);
+ } else if (triangle_subidx == 1) {
+ vertex_idx = vertex_indices.y;
+ barycentric = vec3(0, 1, 0);
+ } else {
+ vertex_idx = vertex_indices.z;
+ barycentric = vec3(0, 0, 1);
+ }
+
+ vertex_interp = vertices.data[vertex_idx].position;
+ uv_interp = vertices.data[vertex_idx].uv;
+ normal_interp = vec3(vertices.data[vertex_idx].normal_xy, vertices.data[vertex_idx].normal_z);
+
+ face_normal = -normalize(cross((vertices.data[vertex_indices.x].position - vertices.data[vertex_indices.y].position), (vertices.data[vertex_indices.x].position - vertices.data[vertex_indices.z].position)));
+
+ gl_Position = vec4((uv_interp + params.uv_offset) * 2.0 - 1.0, 0.0001, 1.0);
+}
+
+#[fragment]
+
+#version 450
+
+VERSION_DEFINES
+
+#include "lm_common_inc.glsl"
+
+layout(push_constant, binding = 0, std430) uniform Params {
+ vec2 atlas_size;
+ vec2 uv_offset;
+ vec3 to_cell_size;
+ uint base_triangle;
+ vec3 to_cell_offset;
+ float bias;
+ ivec3 grid_size;
+ uint pad2;
+}
+params;
+
+layout(location = 0) in vec3 vertex_interp;
+layout(location = 1) in vec3 normal_interp;
+layout(location = 2) in vec2 uv_interp;
+layout(location = 3) in vec3 barycentric;
+layout(location = 4) in flat uvec3 vertex_indices;
+layout(location = 5) in flat vec3 face_normal;
+
+layout(location = 0) out vec4 position;
+layout(location = 1) out vec4 normal;
+layout(location = 2) out vec4 unocclude;
+
+void main() {
+ vec3 vertex_pos = vertex_interp;
+
+ {
+ // smooth out vertex position by interpolating its projection in the 3 normal planes (normal plane is created by vertex pos and normal)
+ // because we don't want to interpolate inwards, normals found pointing inwards are pushed out.
+ vec3 pos_a = vertices.data[vertex_indices.x].position;
+ vec3 pos_b = vertices.data[vertex_indices.y].position;
+ vec3 pos_c = vertices.data[vertex_indices.z].position;
+ vec3 center = (pos_a + pos_b + pos_c) * 0.3333333;
+ vec3 norm_a = vec3(vertices.data[vertex_indices.x].normal_xy, vertices.data[vertex_indices.x].normal_z);
+ vec3 norm_b = vec3(vertices.data[vertex_indices.y].normal_xy, vertices.data[vertex_indices.y].normal_z);
+ vec3 norm_c = vec3(vertices.data[vertex_indices.z].normal_xy, vertices.data[vertex_indices.z].normal_z);
+
+ {
+ vec3 dir_a = normalize(pos_a - center);
+ float d_a = dot(dir_a, norm_a);
+ if (d_a < 0) {
+ //pointing inwards
+ norm_a = normalize(norm_a - dir_a * d_a);
+ }
+ }
+ {
+ vec3 dir_b = normalize(pos_b - center);
+ float d_b = dot(dir_b, norm_b);
+ if (d_b < 0) {
+ //pointing inwards
+ norm_b = normalize(norm_b - dir_b * d_b);
+ }
+ }
+ {
+ vec3 dir_c = normalize(pos_c - center);
+ float d_c = dot(dir_c, norm_c);
+ if (d_c < 0) {
+ //pointing inwards
+ norm_c = normalize(norm_c - dir_c * d_c);
+ }
+ }
+
+ float d_a = dot(norm_a, pos_a);
+ float d_b = dot(norm_b, pos_b);
+ float d_c = dot(norm_c, pos_c);
+
+ vec3 proj_a = vertex_pos - norm_a * (dot(norm_a, vertex_pos) - d_a);
+ vec3 proj_b = vertex_pos - norm_b * (dot(norm_b, vertex_pos) - d_b);
+ vec3 proj_c = vertex_pos - norm_c * (dot(norm_c, vertex_pos) - d_c);
+
+ vec3 smooth_position = proj_a * barycentric.x + proj_b * barycentric.y + proj_c * barycentric.z;
+
+ if (dot(face_normal, smooth_position) > dot(face_normal, vertex_pos)) { //only project outwards
+ vertex_pos = smooth_position;
+ }
+ }
+
+ {
+ // unocclusion technique based on:
+ // https://ndotl.wordpress.com/2018/08/29/baking-artifact-free-lightmaps/
+
+ /* compute texel size */
+ vec3 delta_uv = max(abs(dFdx(vertex_interp)), abs(dFdy(vertex_interp)));
+ float texel_size = max(delta_uv.x, max(delta_uv.y, delta_uv.z));
+ texel_size *= sqrt(2.0); //expand to unit box edge length (again, worst case)
+
+ unocclude.xyz = face_normal;
+ unocclude.w = texel_size;
+
+ //continued on lm_compute.glsl
+ }
+
+ position = vec4(vertex_pos, 1.0);
+ normal = vec4(normalize(normal_interp), 1.0);
+}
diff --git a/modules/lightmapper_rd/register_types.cpp b/modules/lightmapper_rd/register_types.cpp
new file mode 100644
index 0000000000..a7b8c063fd
--- /dev/null
+++ b/modules/lightmapper_rd/register_types.cpp
@@ -0,0 +1,63 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "core/config/project_settings.h"
+#include "lightmapper_rd.h"
+#include "scene/3d/lightmapper.h"
+
+#ifndef _3D_DISABLED
+static Lightmapper *create_lightmapper_rd() {
+ return memnew(LightmapperRD);
+}
+#endif
+
+void register_lightmapper_rd_types() {
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/low_quality_ray_count", 16);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/medium_quality_ray_count", 64);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/high_quality_ray_count", 256);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/ultra_quality_ray_count", 1024);
+ GLOBAL_DEF("rendering/gpu_lightmapper/performance/max_rays_per_pass", 32);
+ GLOBAL_DEF("rendering/gpu_lightmapper/performance/region_size", 512);
+
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/low_quality_probe_ray_count", 64);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/medium_quality_probe_ray_count", 256);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/high_quality_probe_ray_count", 512);
+ GLOBAL_DEF("rendering/gpu_lightmapper/quality/ultra_quality_probe_ray_count", 2048);
+ GLOBAL_DEF("rendering/gpu_lightmapper/performance/max_rays_per_probe_pass", 64);
+#ifndef _3D_DISABLED
+ ClassDB::register_class<LightmapperRD>();
+ Lightmapper::create_gpu = create_lightmapper_rd;
+#endif
+}
+
+void unregister_lightmapper_rd_types() {
+}
diff --git a/modules/lightmapper_rd/register_types.h b/modules/lightmapper_rd/register_types.h
new file mode 100644
index 0000000000..622d6e37a7
--- /dev/null
+++ b/modules/lightmapper_rd/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 LIGHTMAPPER_RD_REGISTER_TYPES_H
+#define LIGHTMAPPER_RD_REGISTER_TYPES_H
+
+void register_lightmapper_rd_types();
+void unregister_lightmapper_rd_types();
+
+#endif // XATLAS_UNWRAP_REGISTER_TYPES_H
diff --git a/modules/mbedtls/SCsub b/modules/mbedtls/SCsub
index 5f5d25a3ee..4fcbe8fb43 100755
--- a/modules/mbedtls/SCsub
+++ b/modules/mbedtls/SCsub
@@ -5,8 +5,11 @@ Import("env_modules")
env_mbed_tls = env_modules.Clone()
+# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_mbedtls"]:
- # Thirdparty source files
thirdparty_sources = [
"aes.c",
"aesni.c",
@@ -96,7 +99,21 @@ if env["builtin_mbedtls"]:
env_thirdparty = env_mbed_tls.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_mbed_tls.add_source_files(module_obj, "*.cpp")
+
+if env["tests"]:
+ env_mbed_tls.Append(CPPDEFINES=["TESTS_ENABLED"])
+ env_mbed_tls.add_source_files(module_obj, "./tests/*.cpp")
+
+env.modules_sources += module_obj
-# Module sources
-env_mbed_tls.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp
index a47a4503a5..73931b0365 100644
--- a/modules/mbedtls/crypto_mbedtls.cpp
+++ b/modules/mbedtls/crypto_mbedtls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,10 +32,10 @@
#include "core/os/file_access.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
+#include "core/config/project_settings.h"
#include "core/io/certs_compressed.gen.h"
#include "core/io/compression.h"
-#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
@@ -43,14 +43,15 @@
#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
#define PEM_END_CRT "-----END CERTIFICATE-----\n"
-#include "mbedtls/pem.h"
#include <mbedtls/debug.h>
+#include <mbedtls/md.h>
+#include <mbedtls/pem.h>
CryptoKey *CryptoKeyMbedTLS::create() {
return memnew(CryptoKeyMbedTLS);
}
-Error CryptoKeyMbedTLS::load(String p_path) {
+Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) {
ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use");
PackedByteArray out;
@@ -59,42 +60,81 @@ Error CryptoKeyMbedTLS::load(String p_path) {
int flen = f->get_len();
out.resize(flen + 1);
- {
- uint8_t *w = out.ptrw();
- f->get_buffer(w, flen);
- w[flen] = 0; //end f string
- }
+ f->get_buffer(out.ptrw(), flen);
+ out.write[flen] = 0; // string terminator
memdelete(f);
- int ret = mbedtls_pk_parse_key(&pkey, out.ptr(), out.size(), nullptr, 0);
+ int ret = 0;
+ if (p_public_only) {
+ ret = mbedtls_pk_parse_public_key(&pkey, out.ptr(), out.size());
+ } else {
+ ret = mbedtls_pk_parse_key(&pkey, out.ptr(), out.size(), nullptr, 0);
+ }
// We MUST zeroize the memory for safety!
mbedtls_platform_zeroize(out.ptrw(), out.size());
- ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing private key '" + itos(ret) + "'.");
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
+ public_only = p_public_only;
return OK;
}
-Error CryptoKeyMbedTLS::save(String p_path) {
+Error CryptoKeyMbedTLS::save(String p_path, bool p_public_only) {
FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'.");
unsigned char w[16000];
memset(w, 0, sizeof(w));
- int ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
+ int ret = 0;
+ if (p_public_only) {
+ ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
+ } else {
+ ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
+ }
if (ret != 0) {
memdelete(f);
- memset(w, 0, sizeof(w)); // Zeroize anything we might have written.
+ mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written.
ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'.");
}
size_t len = strlen((char *)w);
f->store_buffer(w, len);
memdelete(f);
- memset(w, 0, sizeof(w)); // Zeroize temporary buffer.
+ mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer.
return OK;
}
+Error CryptoKeyMbedTLS::load_from_string(String p_string_key, bool p_public_only) {
+ int ret = 0;
+ if (p_public_only) {
+ ret = mbedtls_pk_parse_public_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size());
+ } else {
+ ret = mbedtls_pk_parse_key(&pkey, (unsigned char *)p_string_key.utf8().get_data(), p_string_key.utf8().size(), nullptr, 0);
+ }
+ ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing key '" + itos(ret) + "'.");
+
+ public_only = p_public_only;
+ return OK;
+}
+
+String CryptoKeyMbedTLS::save_to_string(bool p_public_only) {
+ unsigned char w[16000];
+ memset(w, 0, sizeof(w));
+
+ int ret = 0;
+ if (p_public_only) {
+ ret = mbedtls_pk_write_pubkey_pem(&pkey, w, sizeof(w));
+ } else {
+ ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w));
+ }
+ if (ret != 0) {
+ mbedtls_platform_zeroize(w, sizeof(w));
+ ERR_FAIL_V_MSG("", "Error saving key '" + itos(ret) + "'.");
+ }
+ String s = String::utf8((char *)w);
+ return s;
+}
+
X509Certificate *X509CertificateMbedTLS::create() {
return memnew(X509CertificateMbedTLS);
}
@@ -108,11 +148,8 @@ Error X509CertificateMbedTLS::load(String p_path) {
int flen = f->get_len();
out.resize(flen + 1);
- {
- uint8_t *w = out.ptrw();
- f->get_buffer(w, flen);
- w[flen] = 0; //end f string
- }
+ f->get_buffer(out.ptrw(), flen);
+ out.write[flen] = 0; // string terminator
memdelete(f);
int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size());
@@ -150,12 +187,73 @@ Error X509CertificateMbedTLS::save(String p_path) {
return OK;
}
+bool HMACContextMbedTLS::is_md_type_allowed(mbedtls_md_type_t p_md_type) {
+ switch (p_md_type) {
+ case MBEDTLS_MD_SHA1:
+ case MBEDTLS_MD_SHA256:
+ return true;
+ default:
+ return false;
+ }
+}
+
+HMACContext *HMACContextMbedTLS::create() {
+ return memnew(HMACContextMbedTLS);
+}
+
+Error HMACContextMbedTLS::start(HashingContext::HashType p_hash_type, PackedByteArray p_key) {
+ ERR_FAIL_COND_V_MSG(ctx != nullptr, ERR_FILE_ALREADY_IN_USE, "HMACContext already started.");
+
+ // HMAC keys can be any size.
+ ERR_FAIL_COND_V_MSG(p_key.is_empty(), ERR_INVALID_PARAMETER, "Key must not be empty.");
+
+ hash_type = p_hash_type;
+ mbedtls_md_type_t ht = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, hash_len);
+
+ bool allowed = HMACContextMbedTLS::is_md_type_allowed(ht);
+ ERR_FAIL_COND_V_MSG(!allowed, ERR_INVALID_PARAMETER, "Unsupported hash type.");
+
+ ctx = memalloc(sizeof(mbedtls_md_context_t));
+ mbedtls_md_init((mbedtls_md_context_t *)ctx);
+
+ mbedtls_md_setup((mbedtls_md_context_t *)ctx, mbedtls_md_info_from_type((mbedtls_md_type_t)ht), 1);
+ int ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, (const uint8_t *)p_key.ptr(), (size_t)p_key.size());
+ return ret ? FAILED : OK;
+}
+
+Error HMACContextMbedTLS::update(PackedByteArray p_data) {
+ ERR_FAIL_COND_V_MSG(ctx == nullptr, ERR_INVALID_DATA, "Start must be called before update.");
+
+ ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_PARAMETER, "Src must not be empty.");
+
+ int ret = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, (const uint8_t *)p_data.ptr(), (size_t)p_data.size());
+ return ret ? FAILED : OK;
+}
+
+PackedByteArray HMACContextMbedTLS::finish() {
+ ERR_FAIL_COND_V_MSG(ctx == nullptr, PackedByteArray(), "Start must be called before finish.");
+ ERR_FAIL_COND_V_MSG(hash_len == 0, PackedByteArray(), "Unsupported hash type.");
+
+ PackedByteArray out;
+ out.resize(hash_len);
+
+ unsigned char *out_ptr = (unsigned char *)out.ptrw();
+ int ret = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out_ptr);
+
+ mbedtls_md_free((mbedtls_md_context_t *)ctx);
+ memfree((mbedtls_md_context_t *)ctx);
+ ctx = nullptr;
+ hash_len = 0;
+
+ ERR_FAIL_COND_V_MSG(ret, PackedByteArray(), "Error received while finishing HMAC");
+ return out;
+}
+
Crypto *CryptoMbedTLS::create() {
return memnew(CryptoMbedTLS);
}
void CryptoMbedTLS::initialize_crypto() {
-
#ifdef DEBUG_ENABLED
mbedtls_debug_set_threshold(1);
#endif
@@ -164,6 +262,7 @@ void CryptoMbedTLS::initialize_crypto() {
Crypto::_load_default_certificates = load_default_certificates;
X509CertificateMbedTLS::make_default();
CryptoKeyMbedTLS::make_default();
+ HMACContextMbedTLS::make_default();
}
void CryptoMbedTLS::finalize_crypto() {
@@ -175,6 +274,7 @@ void CryptoMbedTLS::finalize_crypto() {
}
X509CertificateMbedTLS::finalize();
CryptoKeyMbedTLS::finalize();
+ HMACContextMbedTLS::finalize();
}
CryptoMbedTLS::CryptoMbedTLS() {
@@ -212,9 +312,8 @@ void CryptoMbedTLS::load_default_certificates(String p_path) {
// Use builtin certs only if user did not override it in project settings.
PackedByteArray out;
out.resize(_certs_uncompressed_size + 1);
- uint8_t *w = out.ptrw();
- Compression::decompress(w, _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
- w[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
+ Compression::decompress(out.ptrw(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
+ out.write[_certs_uncompressed_size] = 0; // Make sure it ends with string terminator
#ifdef DEBUG_ENABLED
print_verbose("Loaded builtin certs");
#endif
@@ -229,6 +328,7 @@ Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) {
int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
ERR_FAIL_COND_V(ret != 0, nullptr);
ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537);
+ out->public_only = false;
ERR_FAIL_COND_V(ret != 0, nullptr);
return out;
}
@@ -259,20 +359,15 @@ Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoK
unsigned char buf[4096];
memset(buf, 0, 4096);
- Ref<X509CertificateMbedTLS> out;
- out.instance();
- mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
-
- int err = mbedtls_x509_crt_parse(&(out->cert), buf, 4096);
- if (err != 0) {
- mbedtls_mpi_free(&serial);
- mbedtls_x509write_crt_free(&crt);
- ERR_PRINT("Generated invalid certificate: " + itos(err));
- return nullptr;
- }
-
+ int ret = mbedtls_x509write_crt_pem(&crt, buf, 4096, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_mpi_free(&serial);
mbedtls_x509write_crt_free(&crt);
+ ERR_FAIL_COND_V_MSG(ret != 0, nullptr, "Failed to generate certificate: " + itos(ret));
+ buf[4095] = '\0'; // Make sure strlen can't fail.
+
+ Ref<X509CertificateMbedTLS> out;
+ out.instance();
+ out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size.
return out;
}
@@ -282,3 +377,75 @@ PackedByteArray CryptoMbedTLS::generate_random_bytes(int p_bytes) {
mbedtls_ctr_drbg_random(&ctr_drbg, out.ptrw(), p_bytes);
return out;
}
+
+mbedtls_md_type_t CryptoMbedTLS::md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size) {
+ switch (p_hash_type) {
+ case HashingContext::HASH_MD5:
+ r_size = 16;
+ return MBEDTLS_MD_MD5;
+ case HashingContext::HASH_SHA1:
+ r_size = 20;
+ return MBEDTLS_MD_SHA1;
+ case HashingContext::HASH_SHA256:
+ r_size = 32;
+ return MBEDTLS_MD_SHA256;
+ default:
+ r_size = 0;
+ ERR_FAIL_V_MSG(MBEDTLS_MD_NONE, "Invalid hash type.");
+ }
+}
+
+Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key) {
+ int size;
+ mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
+ ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, Vector<uint8_t>(), "Invalid hash type.");
+ ERR_FAIL_COND_V_MSG(p_hash.size() != size, Vector<uint8_t>(), "Invalid hash provided. Size must be " + itos(size));
+ Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
+ ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
+ ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot sign with public_only keys.");
+ size_t sig_size = 0;
+ unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
+ Vector<uint8_t> out;
+ int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf, &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg);
+ ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret));
+ out.resize(sig_size);
+ copymem(out.ptrw(), buf, sig_size);
+ return out;
+}
+
+bool CryptoMbedTLS::verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key) {
+ int size;
+ mbedtls_md_type_t type = CryptoMbedTLS::md_type_from_hashtype(p_hash_type, size);
+ ERR_FAIL_COND_V_MSG(type == MBEDTLS_MD_NONE, false, "Invalid hash type.");
+ ERR_FAIL_COND_V_MSG(p_hash.size() != size, false, "Invalid hash provided. Size must be " + itos(size));
+ Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
+ ERR_FAIL_COND_V_MSG(!key.is_valid(), false, "Invalid key provided.");
+ return mbedtls_pk_verify(&(key->pkey), type, p_hash.ptr(), size, p_signature.ptr(), p_signature.size()) == 0;
+}
+
+Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext) {
+ Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
+ ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
+ uint8_t buf[1024];
+ size_t size;
+ Vector<uint8_t> out;
+ int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
+ ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret));
+ out.resize(size);
+ copymem(out.ptrw(), buf, size);
+ return out;
+}
+
+Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext) {
+ Ref<CryptoKeyMbedTLS> key = static_cast<Ref<CryptoKeyMbedTLS>>(p_key);
+ ERR_FAIL_COND_V_MSG(!key.is_valid(), Vector<uint8_t>(), "Invalid key provided.");
+ ERR_FAIL_COND_V_MSG(key->is_public_only(), Vector<uint8_t>(), "Invalid key provided. Cannot decrypt using a public_only key.");
+ uint8_t buf[2048];
+ size_t size;
+ Vector<uint8_t> out;
+ int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg);
+ ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret));
+ out.resize(size);
+ copymem(out.ptrw(), buf, size);
+ return out;
+}
diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h
index db3d00a5e3..5ced4d136c 100644
--- a/modules/mbedtls/crypto_mbedtls.h
+++ b/modules/mbedtls/crypto_mbedtls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define CRYPTO_MBEDTLS_H
#include "core/crypto/crypto.h"
-#include "core/resource.h"
+#include "core/io/resource.h"
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
@@ -41,18 +41,21 @@
class CryptoMbedTLS;
class SSLContextMbedTLS;
class CryptoKeyMbedTLS : public CryptoKey {
-
private:
mbedtls_pk_context pkey;
- int locks;
+ int locks = 0;
+ bool public_only = true;
public:
static CryptoKey *create();
static void make_default() { CryptoKey::_create = create; }
static void finalize() { CryptoKey::_create = nullptr; }
- virtual Error load(String p_path);
- virtual Error save(String p_path);
+ virtual Error load(String p_path, bool p_public_only);
+ virtual Error save(String p_path, bool p_public_only);
+ virtual String save_to_string(bool p_public_only);
+ virtual Error load_from_string(String p_string_key, bool p_public_only);
+ virtual bool is_public_only() const { return public_only; };
CryptoKeyMbedTLS() {
mbedtls_pk_init(&pkey);
@@ -70,7 +73,6 @@ public:
};
class X509CertificateMbedTLS : public X509Certificate {
-
private:
mbedtls_x509_crt cert;
int locks;
@@ -99,8 +101,27 @@ public:
friend class SSLContextMbedTLS;
};
-class CryptoMbedTLS : public Crypto {
+class HMACContextMbedTLS : public HMACContext {
+private:
+ HashingContext::HashType hash_type;
+ int hash_len = 0;
+ void *ctx = nullptr;
+public:
+ static HMACContext *create();
+ static void make_default() { HMACContext::_create = create; }
+ static void finalize() { HMACContext::_create = nullptr; }
+
+ static bool is_md_type_allowed(mbedtls_md_type_t p_md_type);
+
+ virtual Error start(HashingContext::HashType p_hash_type, PackedByteArray p_key);
+ virtual Error update(PackedByteArray p_data);
+ virtual PackedByteArray finish();
+
+ HMACContextMbedTLS() {}
+};
+
+class CryptoMbedTLS : public Crypto {
private:
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
@@ -112,10 +133,15 @@ public:
static void finalize_crypto();
static X509CertificateMbedTLS *get_default_certificates();
static void load_default_certificates(String p_path);
+ static mbedtls_md_type_t md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size);
virtual PackedByteArray generate_random_bytes(int p_bytes);
virtual Ref<CryptoKey> generate_rsa(int p_bytes);
virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
+ virtual Vector<uint8_t> sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key);
+ virtual bool verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key);
+ virtual Vector<uint8_t> encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext);
+ virtual Vector<uint8_t> decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext);
CryptoMbedTLS();
~CryptoMbedTLS();
diff --git a/modules/mbedtls/dtls_server_mbedtls.cpp b/modules/mbedtls/dtls_server_mbedtls.cpp
index f31f067f4e..5d895d8579 100644
--- a/modules/mbedtls/dtls_server_mbedtls.cpp
+++ b/modules/mbedtls/dtls_server_mbedtls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -54,12 +54,10 @@ Ref<PacketPeerDTLS> DTLSServerMbedTLS::take_connection(Ref<PacketPeerUDP> p_udp_
}
DTLSServer *DTLSServerMbedTLS::_create_func() {
-
return memnew(DTLSServerMbedTLS);
}
void DTLSServerMbedTLS::initialize() {
-
_create = _create_func;
available = true;
}
diff --git a/modules/mbedtls/dtls_server_mbedtls.h b/modules/mbedtls/dtls_server_mbedtls.h
index d61ab3179e..9f0c9670e7 100644
--- a/modules/mbedtls/dtls_server_mbedtls.h
+++ b/modules/mbedtls/dtls_server_mbedtls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
#include "ssl_context_mbedtls.h"
class DTLSServerMbedTLS : public DTLSServer {
-
private:
static DTLSServer *_create_func();
Ref<CryptoKey> _key;
diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp
index b2aa5f5827..b2f8d668bf 100755..100644
--- a/modules/mbedtls/packet_peer_mbed_dtls.cpp
+++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,8 +35,9 @@
#include "core/os/file_access.h"
int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) {
-
- if (buf == nullptr || len <= 0) return 0;
+ if (buf == nullptr || len <= 0) {
+ return 0;
+ }
PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx;
@@ -52,8 +53,9 @@ int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len
}
int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
-
- if (buf == nullptr || len <= 0) return 0;
+ if (buf == nullptr || len <= 0) {
+ return 0;
+ }
PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx;
@@ -77,7 +79,6 @@ int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
}
void PacketPeerMbedDTLS::_cleanup() {
-
ssl_ctx->clear();
base = Ref<PacketPeer>();
status = STATUS_DISCONNECTED;
@@ -114,7 +115,6 @@ Error PacketPeerMbedDTLS::_do_handshake() {
}
Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) {
-
ERR_FAIL_COND_V(!p_base.is_valid() || !p_base->is_connected_to_host(), ERR_INVALID_PARAMETER);
base = p_base;
@@ -139,7 +139,6 @@ Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_vali
}
Error PacketPeerMbedDTLS::accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain, Ref<CookieContextMbedTLS> p_cookies) {
-
Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert, p_cookies);
ERR_FAIL_COND_V(err != OK, err);
@@ -168,11 +167,11 @@ Error PacketPeerMbedDTLS::accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey>
}
Error PacketPeerMbedDTLS::put_packet(const uint8_t *p_buffer, int p_bytes) {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
- if (p_bytes == 0)
+ if (p_bytes == 0) {
return OK;
+ }
int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_buffer, p_bytes);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
@@ -187,7 +186,6 @@ Error PacketPeerMbedDTLS::put_packet(const uint8_t *p_buffer, int p_bytes) {
}
Error PacketPeerMbedDTLS::get_packet(const uint8_t **r_buffer, int &r_bytes) {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
r_bytes = 0;
@@ -213,7 +211,6 @@ Error PacketPeerMbedDTLS::get_packet(const uint8_t **r_buffer, int &r_bytes) {
}
void PacketPeerMbedDTLS::poll() {
-
if (status == STATUS_HANDSHAKING) {
_do_handshake();
return;
@@ -238,19 +235,16 @@ void PacketPeerMbedDTLS::poll() {
}
int PacketPeerMbedDTLS::get_available_packet_count() const {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0);
return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)) > 0 ? 1 : 0;
}
int PacketPeerMbedDTLS::get_max_packet_size() const {
-
return 488; // 512 (UDP in Godot) - 24 (DTLS header)
}
PacketPeerMbedDTLS::PacketPeerMbedDTLS() {
-
ssl_ctx.instance();
status = STATUS_DISCONNECTED;
}
@@ -260,33 +254,30 @@ PacketPeerMbedDTLS::~PacketPeerMbedDTLS() {
}
void PacketPeerMbedDTLS::disconnect_from_peer() {
-
- if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING)
+ if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) {
return;
+ }
if (status == STATUS_CONNECTED) {
int ret = 0;
// Send SSL close notification, blocking, but ignore other errors.
- do
+ do {
ret = mbedtls_ssl_close_notify(ssl_ctx->get_context());
- while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
+ } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
}
_cleanup();
}
PacketPeerMbedDTLS::Status PacketPeerMbedDTLS::get_status() const {
-
return status;
}
PacketPeerDTLS *PacketPeerMbedDTLS::_create_func() {
-
return memnew(PacketPeerMbedDTLS);
}
void PacketPeerMbedDTLS::initialize_dtls() {
-
_create = _create_func;
available = true;
}
diff --git a/modules/mbedtls/packet_peer_mbed_dtls.h b/modules/mbedtls/packet_peer_mbed_dtls.h
index b958fa3b95..0feec04c6e 100755
--- a/modules/mbedtls/packet_peer_mbed_dtls.h
+++ b/modules/mbedtls/packet_peer_mbed_dtls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp
index d39af7fe87..e483030b94 100755..100644
--- a/modules/mbedtls/register_types.cpp
+++ b/modules/mbedtls/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,8 +35,11 @@
#include "packet_peer_mbed_dtls.h"
#include "stream_peer_mbedtls.h"
-void register_mbedtls_types() {
+#ifdef TESTS_ENABLED
+#include "tests/test_crypto_mbedtls.h"
+#endif
+void register_mbedtls_types() {
CryptoMbedTLS::initialize_crypto();
StreamPeerMbedTLS::initialize_ssl();
PacketPeerMbedDTLS::initialize_dtls();
@@ -44,7 +47,6 @@ void register_mbedtls_types() {
}
void unregister_mbedtls_types() {
-
DTLSServerMbedTLS::finalize();
PacketPeerMbedDTLS::finalize_dtls();
StreamPeerMbedTLS::finalize_ssl();
diff --git a/modules/mbedtls/register_types.h b/modules/mbedtls/register_types.h
index 90c81b1682..46ffb8522b 100755
--- a/modules/mbedtls/register_types.h
+++ b/modules/mbedtls/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/ssl_context_mbedtls.cpp
index 1ffb9bda05..046f30588a 100644
--- a/modules/mbedtls/ssl_context_mbedtls.cpp
+++ b/modules/mbedtls/ssl_context_mbedtls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
static void my_debug(void *ctx, int level,
const char *file, int line,
const char *str) {
-
printf("%s:%04d: %s", file, line, str);
fflush(stdout);
}
@@ -68,8 +67,9 @@ Error CookieContextMbedTLS::setup() {
}
void CookieContextMbedTLS::clear() {
- if (!inited)
+ if (!inited) {
return;
+ }
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
mbedtls_ssl_cookie_free(&cookie_ctx);
@@ -121,10 +121,12 @@ Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<Crypto
// Locking key and certificate(s)
pkey = p_pkey;
certs = p_cert;
- if (pkey.is_valid())
+ if (pkey.is_valid()) {
pkey->lock();
- if (certs.is_valid())
+ }
+ if (certs.is_valid()) {
certs->lock();
+ }
// Adding key and certificate
int ret = mbedtls_ssl_conf_own_cert(&conf, &(certs->cert), &(pkey->pkey));
@@ -176,19 +178,22 @@ Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509Ce
}
void SSLContextMbedTLS::clear() {
- if (!inited)
+ if (!inited) {
return;
+ }
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
// Unlock and key and certificates
- if (certs.is_valid())
+ if (certs.is_valid()) {
certs->unlock();
+ }
certs = Ref<X509Certificate>();
- if (pkey.is_valid())
+ if (pkey.is_valid()) {
pkey->unlock();
+ }
pkey = Ref<CryptoKeyMbedTLS>();
cookies = Ref<CookieContextMbedTLS>();
inited = false;
diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h
index d3e1f87a8e..d243185726 100644
--- a/modules/mbedtls/ssl_context_mbedtls.h
+++ b/modules/mbedtls/ssl_context_mbedtls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,7 @@
#include "core/os/file_access.h"
-#include "core/reference.h"
+#include "core/object/reference.h"
#include <mbedtls/config.h>
#include <mbedtls/ctr_drbg.h>
@@ -47,7 +47,6 @@
class SSLContextMbedTLS;
class CookieContextMbedTLS : public Reference {
-
friend class SSLContextMbedTLS;
protected:
@@ -65,7 +64,6 @@ public:
};
class SSLContextMbedTLS : public Reference {
-
protected:
bool inited;
diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp
index 983095c536..1332d0923c 100755..100644
--- a/modules/mbedtls/stream_peer_mbedtls.cpp
+++ b/modules/mbedtls/stream_peer_mbedtls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,8 +34,9 @@
#include "core/os/file_access.h"
int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) {
-
- if (buf == nullptr || len <= 0) return 0;
+ if (buf == nullptr || len <= 0) {
+ return 0;
+ }
StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx;
@@ -53,8 +54,9 @@ int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len)
}
int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
-
- if (buf == nullptr || len <= 0) return 0;
+ if (buf == nullptr || len <= 0) {
+ return 0;
+ }
StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx;
@@ -72,7 +74,6 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
}
void StreamPeerMbedTLS::_cleanup() {
-
ssl_ctx->clear();
base = Ref<StreamPeer>();
status = STATUS_DISCONNECTED;
@@ -102,7 +103,6 @@ Error StreamPeerMbedTLS::_do_handshake() {
}
Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname, Ref<X509Certificate> p_ca_certs) {
-
ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
base = p_base;
@@ -125,7 +125,6 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
}
Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) {
-
ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert);
@@ -144,8 +143,8 @@ Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_
status = STATUS_CONNECTED;
return OK;
}
-Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
+Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
Error err;
@@ -166,13 +165,13 @@ Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
}
Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
r_sent = 0;
- if (p_bytes == 0)
+ if (p_bytes == 0) {
return OK;
+ }
int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
@@ -193,14 +192,12 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in
}
Error StreamPeerMbedTLS::get_data(uint8_t *p_buffer, int p_bytes) {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
Error err;
int got = 0;
while (p_bytes > 0) {
-
err = get_partial_data(p_buffer, p_bytes, got);
if (err != OK) {
@@ -215,7 +212,6 @@ Error StreamPeerMbedTLS::get_data(uint8_t *p_buffer, int p_bytes) {
}
Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
r_received = 0;
@@ -238,7 +234,6 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r
}
void StreamPeerMbedTLS::poll() {
-
ERR_FAIL_COND(status != STATUS_CONNECTED && status != STATUS_HANDSHAKING);
ERR_FAIL_COND(!base.is_valid());
@@ -272,13 +267,12 @@ void StreamPeerMbedTLS::poll() {
}
int StreamPeerMbedTLS::get_available_bytes() const {
-
ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0);
return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl));
}
-StreamPeerMbedTLS::StreamPeerMbedTLS() {
+StreamPeerMbedTLS::StreamPeerMbedTLS() {
ssl_ctx.instance();
status = STATUS_DISCONNECTED;
}
@@ -288,9 +282,9 @@ StreamPeerMbedTLS::~StreamPeerMbedTLS() {
}
void StreamPeerMbedTLS::disconnect_from_stream() {
-
- if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING)
+ if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING) {
return;
+ }
Ref<StreamPeerTCP> tcp = base;
if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
@@ -302,23 +296,19 @@ void StreamPeerMbedTLS::disconnect_from_stream() {
}
StreamPeerMbedTLS::Status StreamPeerMbedTLS::get_status() const {
-
return status;
}
StreamPeerSSL *StreamPeerMbedTLS::_create_func() {
-
return memnew(StreamPeerMbedTLS);
}
void StreamPeerMbedTLS::initialize_ssl() {
-
_create = _create_func;
available = true;
}
void StreamPeerMbedTLS::finalize_ssl() {
-
available = false;
_create = nullptr;
}
diff --git a/modules/mbedtls/stream_peer_mbedtls.h b/modules/mbedtls/stream_peer_mbedtls.h
index 68b03ae995..ccbbebe4f8 100755
--- a/modules/mbedtls/stream_peer_mbedtls.h
+++ b/modules/mbedtls/stream_peer_mbedtls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mono/editor/csharp_project.cpp b/modules/mbedtls/tests/test_crypto_mbedtls.cpp
index e5c2d023d3..4217497082 100644
--- a/modules/mono/editor/csharp_project.cpp
+++ b/modules/mbedtls/tests/test_crypto_mbedtls.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* csharp_project.cpp */
+/* test_crypto_mbedtls.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,42 +28,35 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "csharp_project.h"
+#include "modules/mbedtls/tests/test_crypto_mbedtls.h"
-#include "core/io/json.h"
-#include "core/os/dir_access.h"
-#include "core/os/file_access.h"
-#include "core/os/os.h"
-#include "core/project_settings.h"
+#include "modules/mbedtls/crypto_mbedtls.h"
+#include "tests/test_macros.h"
-#include "../csharp_script.h"
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../utils/string_utils.h"
-#include "script_class_parser.h"
+namespace TestCryptoMbedTLS {
-namespace CSharpProject {
-
-void add_item(const String &p_project_path, const String &p_item_type, const String &p_include) {
-
- if (!GLOBAL_DEF("mono/project/auto_update_project", true))
- return;
-
- GDMonoAssembly *tools_project_editor_assembly = GDMono::get_singleton()->get_tools_project_editor_assembly();
-
- GDMonoClass *klass = tools_project_editor_assembly->get_class("GodotTools.ProjectEditor", "ProjectUtils");
-
- Variant project_path = p_project_path;
- Variant item_type = p_item_type;
- Variant include = p_include;
- const Variant *args[3] = { &project_path, &item_type, &include };
- MonoException *exc = nullptr;
- klass->get_method("AddItemToProjectChecked", 3)->invoke(nullptr, args, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL();
- }
+void hmac_digest_test(HashingContext::HashType ht, String expected_hex) {
+ CryptoMbedTLS crypto;
+ PackedByteArray key = String("supersecretkey").to_utf8_buffer();
+ PackedByteArray msg = String("Return of the MAC!").to_utf8_buffer();
+ PackedByteArray digest = crypto.hmac_digest(ht, key, msg);
+ String hex = String::hex_encode_buffer(digest.ptr(), digest.size());
+ CHECK(hex == expected_hex);
}
-} // namespace CSharpProject
+void hmac_context_digest_test(HashingContext::HashType ht, String expected_hex) {
+ HMACContextMbedTLS ctx;
+ PackedByteArray key = String("supersecretkey").to_utf8_buffer();
+ PackedByteArray msg1 = String("Return of ").to_utf8_buffer();
+ PackedByteArray msg2 = String("the MAC!").to_utf8_buffer();
+ Error err = ctx.start(ht, key);
+ CHECK(err == OK);
+ err = ctx.update(msg1);
+ CHECK(err == OK);
+ err = ctx.update(msg2);
+ CHECK(err == OK);
+ PackedByteArray digest = ctx.finish();
+ String hex = String::hex_encode_buffer(digest.ptr(), digest.size());
+ CHECK(hex == expected_hex);
+}
+} // namespace TestCryptoMbedTLS
diff --git a/modules/mbedtls/tests/test_crypto_mbedtls.h b/modules/mbedtls/tests/test_crypto_mbedtls.h
new file mode 100644
index 0000000000..b798717e52
--- /dev/null
+++ b/modules/mbedtls/tests/test_crypto_mbedtls.h
@@ -0,0 +1,61 @@
+/*************************************************************************/
+/* test_crypto_mbedtls.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEST_CRYPTO_MBEDTLS_H
+#define TEST_CRYPTO_MBEDTLS_H
+
+#include "core/crypto/hashing_context.h"
+
+#include "tests/test_macros.h"
+
+namespace TestCryptoMbedTLS {
+
+void hmac_digest_test(HashingContext::HashType ht, String expected_hex);
+
+TEST_CASE("[CryptoMbedTLS] HMAC digest") {
+ // SHA-256
+ hmac_digest_test(HashingContext::HashType::HASH_SHA256, "fe442023f8a7d36a810e1e7cd8a8e2816457f350a008fbf638296afa12085e59");
+
+ // SHA-1
+ hmac_digest_test(HashingContext::HashType::HASH_SHA1, "a0ac4cd68a2f4812c355983d94e8d025afe7dddf");
+}
+
+void hmac_context_digest_test(HashingContext::HashType ht, String expected_hex);
+
+TEST_CASE("[HMACContext] HMAC digest") {
+ // SHA-256
+ hmac_context_digest_test(HashingContext::HashType::HASH_SHA256, "fe442023f8a7d36a810e1e7cd8a8e2816457f350a008fbf638296afa12085e59");
+
+ // SHA-1
+ hmac_context_digest_test(HashingContext::HashType::HASH_SHA1, "a0ac4cd68a2f4812c355983d94e8d025afe7dddf");
+}
+} // namespace TestCryptoMbedTLS
+
+#endif // TEST_CRYPTO_MBEDTLS_H
diff --git a/modules/meshoptimizer/SCsub b/modules/meshoptimizer/SCsub
new file mode 100644
index 0000000000..3f86bb4f00
--- /dev/null
+++ b/modules/meshoptimizer/SCsub
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_meshoptimizer = env_modules.Clone()
+
+# Thirdparty source files
+
+thirdparty_obj = []
+
+thirdparty_dir = "#thirdparty/meshoptimizer/"
+thirdparty_sources = [
+ "allocator.cpp",
+ "clusterizer.cpp",
+ "indexcodec.cpp",
+ "indexgenerator.cpp",
+ "overdrawanalyzer.cpp",
+ "overdrawoptimizer.cpp",
+ "simplifier.cpp",
+ "spatialorder.cpp",
+ "stripifier.cpp",
+ "vcacheanalyzer.cpp",
+ "vcacheoptimizer.cpp",
+ "vertexcodec.cpp",
+ "vertexfilter.cpp",
+ "vfetchanalyzer.cpp",
+ "vfetchoptimizer.cpp",
+]
+thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+env_thirdparty = env_meshoptimizer.Clone()
+env_thirdparty.disable_warnings()
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_meshoptimizer.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/meshoptimizer/config.py b/modules/meshoptimizer/config.py
new file mode 100644
index 0000000000..82e4e43397
--- /dev/null
+++ b/modules/meshoptimizer/config.py
@@ -0,0 +1,7 @@
+def can_build(env, platform):
+ # Having this on release by default, it's small and a lot of users like to do procedural stuff
+ return True
+
+
+def configure(env):
+ pass
diff --git a/modules/meshoptimizer/register_types.cpp b/modules/meshoptimizer/register_types.cpp
new file mode 100644
index 0000000000..a03310f518
--- /dev/null
+++ b/modules/meshoptimizer/register_types.cpp
@@ -0,0 +1,47 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+#include "scene/resources/surface_tool.h"
+#include "thirdparty/meshoptimizer/meshoptimizer.h"
+
+void register_meshoptimizer_types() {
+ SurfaceTool::optimize_vertex_cache_func = meshopt_optimizeVertexCache;
+ SurfaceTool::simplify_func = meshopt_simplify;
+ SurfaceTool::simplify_scale_func = meshopt_simplifyScale;
+ SurfaceTool::simplify_sloppy_func = meshopt_simplifySloppy;
+}
+
+void unregister_meshoptimizer_types() {
+ SurfaceTool::optimize_vertex_cache_func = nullptr;
+ SurfaceTool::simplify_func = nullptr;
+ SurfaceTool::simplify_scale_func = nullptr;
+ SurfaceTool::simplify_sloppy_func = nullptr;
+}
diff --git a/modules/meshoptimizer/register_types.h b/modules/meshoptimizer/register_types.h
new file mode 100644
index 0000000000..5b15503acd
--- /dev/null
+++ b/modules/meshoptimizer/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 MESHOPTIMIZER_REGISTER_TYPES_H
+#define MESHOPTIMIZER_REGISTER_TYPES_H
+
+void register_meshoptimizer_types();
+void unregister_meshoptimizer_types();
+
+#endif // PVR_REGISTER_TYPES_H
diff --git a/modules/minimp3/SCsub b/modules/minimp3/SCsub
new file mode 100644
index 0000000000..f4d1605d55
--- /dev/null
+++ b/modules/minimp3/SCsub
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_minimp3 = env_modules.Clone()
+
+thirdparty_dir = "#thirdparty/minimp3/"
+
+# Treat minimp3 headers as system headers to avoid raising warnings. Not supported on MSVC.
+if not env.msvc:
+ env_minimp3.Append(CPPFLAGS=["-isystem", Dir(thirdparty_dir).path])
+else:
+ env_minimp3.Prepend(CPPPATH=[thirdparty_dir])
+
+# Godot's own source files
+env_minimp3.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/minimp3/audio_stream_mp3.cpp b/modules/minimp3/audio_stream_mp3.cpp
new file mode 100644
index 0000000000..8627f71987
--- /dev/null
+++ b/modules/minimp3/audio_stream_mp3.cpp
@@ -0,0 +1,231 @@
+/*************************************************************************/
+/* audio_stream_mp3.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#define MINIMP3_ONLY_MP3
+#define MINIMP3_FLOAT_OUTPUT
+#define MINIMP3_IMPLEMENTATION
+#define MINIMP3_NO_STDIO
+
+#include "audio_stream_mp3.h"
+
+#include "core/os/file_access.h"
+
+void AudioStreamPlaybackMP3::_mix_internal(AudioFrame *p_buffer, int p_frames) {
+ ERR_FAIL_COND(!active);
+
+ int todo = p_frames;
+
+ while (todo && active) {
+ mp3dec_frame_info_t frame_info;
+ mp3d_sample_t *buf_frame = nullptr;
+
+ int samples_mixed = mp3dec_ex_read_frame(mp3d, &buf_frame, &frame_info, mp3_stream->channels);
+
+ if (samples_mixed) {
+ p_buffer[p_frames - todo] = AudioFrame(buf_frame[0], buf_frame[samples_mixed - 1]);
+ --todo;
+ ++frames_mixed;
+ }
+
+ else {
+ //EOF
+ if (mp3_stream->loop) {
+ seek(mp3_stream->loop_offset);
+ loops++;
+ } else {
+ //fill remainder with silence
+ for (int i = p_frames - todo; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
+ }
+ active = false;
+ todo = 0;
+ }
+ }
+ }
+}
+
+float AudioStreamPlaybackMP3::get_stream_sampling_rate() {
+ return mp3_stream->sample_rate;
+}
+
+void AudioStreamPlaybackMP3::start(float p_from_pos) {
+ active = true;
+ seek(p_from_pos);
+ loops = 0;
+ _begin_resample();
+}
+
+void AudioStreamPlaybackMP3::stop() {
+ active = false;
+}
+
+bool AudioStreamPlaybackMP3::is_playing() const {
+ return active;
+}
+
+int AudioStreamPlaybackMP3::get_loop_count() const {
+ return loops;
+}
+
+float AudioStreamPlaybackMP3::get_playback_position() const {
+ return float(frames_mixed) / mp3_stream->sample_rate;
+}
+
+void AudioStreamPlaybackMP3::seek(float p_time) {
+ if (!active)
+ return;
+
+ if (p_time >= mp3_stream->get_length()) {
+ p_time = 0;
+ }
+
+ frames_mixed = uint32_t(mp3_stream->sample_rate * p_time);
+ mp3dec_ex_seek(mp3d, frames_mixed * mp3_stream->channels);
+}
+
+AudioStreamPlaybackMP3::~AudioStreamPlaybackMP3() {
+ if (mp3d) {
+ mp3dec_ex_close(mp3d);
+ memfree(mp3d);
+ }
+}
+
+Ref<AudioStreamPlayback> AudioStreamMP3::instance_playback() {
+ Ref<AudioStreamPlaybackMP3> mp3s;
+
+ ERR_FAIL_COND_V_MSG(data == nullptr, mp3s,
+ "This AudioStreamMP3 does not have an audio file assigned "
+ "to it. AudioStreamMP3 should not be created from the "
+ "inspector or with `.new()`. Instead, load an audio file.");
+
+ mp3s.instance();
+ mp3s->mp3_stream = Ref<AudioStreamMP3>(this);
+ mp3s->mp3d = (mp3dec_ex_t *)memalloc(sizeof(mp3dec_ex_t));
+
+ int errorcode = mp3dec_ex_open_buf(mp3s->mp3d, (const uint8_t *)data, data_len, MP3D_SEEK_TO_SAMPLE);
+
+ mp3s->frames_mixed = 0;
+ mp3s->active = false;
+ mp3s->loops = 0;
+
+ if (errorcode) {
+ ERR_FAIL_COND_V(errorcode, Ref<AudioStreamPlaybackMP3>());
+ }
+
+ return mp3s;
+}
+
+String AudioStreamMP3::get_stream_name() const {
+ return ""; //return stream_name;
+}
+
+void AudioStreamMP3::clear_data() {
+ if (data) {
+ memfree(data);
+ data = nullptr;
+ data_len = 0;
+ }
+}
+
+void AudioStreamMP3::set_data(const Vector<uint8_t> &p_data) {
+ int src_data_len = p_data.size();
+ const uint8_t *src_datar = p_data.ptr();
+
+ mp3dec_ex_t mp3d;
+ mp3dec_ex_open_buf(&mp3d, src_datar, src_data_len, MP3D_SEEK_TO_SAMPLE);
+
+ channels = mp3d.info.channels;
+ sample_rate = mp3d.info.hz;
+ length = float(mp3d.samples) / (sample_rate * float(channels));
+
+ mp3dec_ex_close(&mp3d);
+
+ clear_data();
+
+ data = memalloc(src_data_len);
+ copymem(data, src_datar, src_data_len);
+ data_len = src_data_len;
+}
+
+Vector<uint8_t> AudioStreamMP3::get_data() const {
+ Vector<uint8_t> vdata;
+
+ if (data_len && data) {
+ vdata.resize(data_len);
+ {
+ uint8_t *w = vdata.ptrw();
+ copymem(w, data, data_len);
+ }
+ }
+
+ return vdata;
+}
+
+void AudioStreamMP3::set_loop(bool p_enable) {
+ loop = p_enable;
+}
+
+bool AudioStreamMP3::has_loop() const {
+ return loop;
+}
+
+void AudioStreamMP3::set_loop_offset(float p_seconds) {
+ loop_offset = p_seconds;
+}
+
+float AudioStreamMP3::get_loop_offset() const {
+ return loop_offset;
+}
+
+float AudioStreamMP3::get_length() const {
+ return length;
+}
+
+void AudioStreamMP3::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamMP3::set_data);
+ ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamMP3::get_data);
+
+ ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamMP3::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamMP3::has_loop);
+
+ ClassDB::bind_method(D_METHOD("set_loop_offset", "seconds"), &AudioStreamMP3::set_loop_offset);
+ ClassDB::bind_method(D_METHOD("get_loop_offset"), &AudioStreamMP3::get_loop_offset);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "loop_offset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop_offset", "get_loop_offset");
+}
+
+AudioStreamMP3::AudioStreamMP3() {
+}
+
+AudioStreamMP3::~AudioStreamMP3() {
+ clear_data();
+}
diff --git a/modules/minimp3/audio_stream_mp3.h b/modules/minimp3/audio_stream_mp3.h
new file mode 100644
index 0000000000..de02ba6003
--- /dev/null
+++ b/modules/minimp3/audio_stream_mp3.h
@@ -0,0 +1,110 @@
+/*************************************************************************/
+/* audio_stream_mp3.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 AUDIO_STREAM_MP3_H
+#define AUDIO_STREAM_MP3_H
+
+#include "core/io/resource_loader.h"
+#include "servers/audio/audio_stream.h"
+
+#include "minimp3_ex.h"
+
+class AudioStreamMP3;
+
+class AudioStreamPlaybackMP3 : public AudioStreamPlaybackResampled {
+ GDCLASS(AudioStreamPlaybackMP3, AudioStreamPlaybackResampled);
+
+ mp3dec_ex_t *mp3d = nullptr;
+ uint32_t frames_mixed = 0;
+ bool active = false;
+ int loops = 0;
+
+ friend class AudioStreamMP3;
+
+ Ref<AudioStreamMP3> mp3_stream;
+
+protected:
+ virtual void _mix_internal(AudioFrame *p_buffer, int p_frames) override;
+ virtual float get_stream_sampling_rate() override;
+
+public:
+ virtual void start(float p_from_pos = 0.0) override;
+ virtual void stop() override;
+ virtual bool is_playing() const override;
+
+ virtual int get_loop_count() const override; //times it looped
+
+ virtual float get_playback_position() const override;
+ virtual void seek(float p_time) override;
+
+ AudioStreamPlaybackMP3() {}
+ ~AudioStreamPlaybackMP3();
+};
+
+class AudioStreamMP3 : public AudioStream {
+ GDCLASS(AudioStreamMP3, AudioStream);
+ OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged
+ RES_BASE_EXTENSION("mp3str");
+
+ friend class AudioStreamPlaybackMP3;
+
+ void *data = nullptr;
+ uint32_t data_len = 0;
+
+ float sample_rate = 1;
+ int channels = 1;
+ float length = 0;
+ bool loop = false;
+ float loop_offset = 0;
+ void clear_data();
+
+protected:
+ static void _bind_methods();
+
+public:
+ void set_loop(bool p_enable);
+ bool has_loop() const;
+
+ void set_loop_offset(float p_seconds);
+ float get_loop_offset() const;
+
+ virtual Ref<AudioStreamPlayback> instance_playback() override;
+ virtual String get_stream_name() const override;
+
+ void set_data(const Vector<uint8_t> &p_data);
+ Vector<uint8_t> get_data() const;
+
+ virtual float get_length() const override;
+
+ AudioStreamMP3();
+ virtual ~AudioStreamMP3();
+};
+
+#endif // AUDIO_STREAM_MP3_H
diff --git a/modules/minimp3/config.py b/modules/minimp3/config.py
new file mode 100644
index 0000000000..bd35d099b9
--- /dev/null
+++ b/modules/minimp3/config.py
@@ -0,0 +1,16 @@
+def can_build(env, platform):
+ return True
+
+
+def configure(env):
+ pass
+
+
+def get_doc_classes():
+ return [
+ "AudioStreamMP3",
+ ]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/minimp3/doc_classes/AudioStreamMP3.xml b/modules/minimp3/doc_classes/AudioStreamMP3.xml
new file mode 100644
index 0000000000..92e777ca0f
--- /dev/null
+++ b/modules/minimp3/doc_classes/AudioStreamMP3.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="AudioStreamMP3" inherits="AudioStream" version="4.0">
+ <brief_description>
+ MP3 audio stream driver.
+ </brief_description>
+ <description>
+ MP3 audio stream driver.
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ </methods>
+ <members>
+ <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray( )">
+ Contains the audio data in bytes.
+ </member>
+ <member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false">
+ If [code]true[/code], the stream will automatically loop when it reaches the end.
+ </member>
+ <member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset" default="0.0">
+ Time in seconds at which the stream starts after being looped.
+ </member>
+ </members>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/minimp3/register_types.cpp b/modules/minimp3/register_types.cpp
new file mode 100644
index 0000000000..4ab4c743d6
--- /dev/null
+++ b/modules/minimp3/register_types.cpp
@@ -0,0 +1,52 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "audio_stream_mp3.h"
+
+#ifdef TOOLS_ENABLED
+#include "core/config/engine.h"
+#include "resource_importer_mp3.h"
+#endif
+
+void register_minimp3_types() {
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ Ref<ResourceImporterMP3> mp3_import;
+ mp3_import.instance();
+ ResourceFormatImporter::get_singleton()->add_importer(mp3_import);
+ }
+#endif
+ ClassDB::register_class<AudioStreamMP3>();
+}
+
+void unregister_minimp3_types() {
+}
diff --git a/modules/minimp3/register_types.h b/modules/minimp3/register_types.h
new file mode 100644
index 0000000000..96227c272e
--- /dev/null
+++ b/modules/minimp3/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 MINIMP3_REGISTER_TYPES_H
+#define MINIMP3_REGISTER_TYPES_H
+
+void register_minimp3_types();
+void unregister_minimp3_types();
+
+#endif // MINIMP3_REGISTER_TYPES_H
diff --git a/modules/minimp3/resource_importer_mp3.cpp b/modules/minimp3/resource_importer_mp3.cpp
new file mode 100644
index 0000000000..afd26fb79e
--- /dev/null
+++ b/modules/minimp3/resource_importer_mp3.cpp
@@ -0,0 +1,104 @@
+/*************************************************************************/
+/* resource_importer_mp3.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "resource_importer_mp3.h"
+
+#include "core/io/resource_saver.h"
+#include "core/os/file_access.h"
+#include "scene/resources/texture.h"
+
+String ResourceImporterMP3::get_importer_name() const {
+ return "mp3";
+}
+
+String ResourceImporterMP3::get_visible_name() const {
+ return "MP3";
+}
+
+void ResourceImporterMP3::get_recognized_extensions(List<String> *p_extensions) const {
+ p_extensions->push_back("mp3");
+}
+
+String ResourceImporterMP3::get_save_extension() const {
+ return "mp3str";
+}
+
+String ResourceImporterMP3::get_resource_type() const {
+ return "AudioStreamMP3";
+}
+
+bool ResourceImporterMP3::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
+ return true;
+}
+
+int ResourceImporterMP3::get_preset_count() const {
+ return 0;
+}
+
+String ResourceImporterMP3::get_preset_name(int p_idx) const {
+ return String();
+}
+
+void ResourceImporterMP3::get_import_options(List<ImportOption> *r_options, int p_preset) const {
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "loop"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "loop_offset"), 0));
+}
+
+Error ResourceImporterMP3::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
+ bool loop = p_options["loop"];
+ float loop_offset = p_options["loop_offset"];
+
+ FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ);
+
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
+
+ size_t len = f->get_len();
+
+ Vector<uint8_t> data;
+ data.resize(len);
+ uint8_t *w = data.ptrw();
+
+ f->get_buffer(w, len);
+
+ memdelete(f);
+
+ Ref<AudioStreamMP3> mp3_stream;
+ mp3_stream.instance();
+
+ mp3_stream->set_data(data);
+ ERR_FAIL_COND_V(!mp3_stream->get_data().size(), ERR_FILE_CORRUPT);
+ mp3_stream->set_loop(loop);
+ mp3_stream->set_loop_offset(loop_offset);
+
+ return ResourceSaver::save(p_save_path + ".mp3str", mp3_stream);
+}
+
+ResourceImporterMP3::ResourceImporterMP3() {
+}
diff --git a/modules/minimp3/resource_importer_mp3.h b/modules/minimp3/resource_importer_mp3.h
new file mode 100644
index 0000000000..71b51887a2
--- /dev/null
+++ b/modules/minimp3/resource_importer_mp3.h
@@ -0,0 +1,58 @@
+/*************************************************************************/
+/* resource_importer_mp3.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 RESOURCE_IMPORTER_MP3_H
+#define RESOURCE_IMPORTER_MP3_H
+
+#include "audio_stream_mp3.h"
+#include "core/io/resource_importer.h"
+
+class ResourceImporterMP3 : public ResourceImporter {
+ GDCLASS(ResourceImporterMP3, ResourceImporter);
+
+public:
+ virtual String get_importer_name() const override;
+ virtual String get_visible_name() const override;
+ virtual void get_recognized_extensions(List<String> *p_extensions) const override;
+ virtual String get_save_extension() const override;
+ virtual String get_resource_type() const override;
+
+ virtual int get_preset_count() const override;
+ virtual String get_preset_name(int p_idx) const override;
+
+ virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const override;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const override;
+
+ virtual Error import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files = nullptr, Variant *r_metadata = nullptr) override;
+
+ ResourceImporterMP3();
+};
+
+#endif // RESOURCE_IMPORTER_MP3_H
diff --git a/modules/mobile_vr/mobile_vr_interface.cpp b/modules/mobile_vr/mobile_vr_interface.cpp
index 48276c0d3d..a9073ea4a0 100644
--- a/modules/mobile_vr/mobile_vr_interface.cpp
+++ b/modules/mobile_vr/mobile_vr_interface.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -61,13 +61,25 @@ Vector3 MobileVRInterface::scale_magneto(const Vector3 &p_magnetometer) {
};
// adjust our min and max
- if (mag_raw.x > mag_next_max.x) mag_next_max.x = mag_raw.x;
- if (mag_raw.y > mag_next_max.y) mag_next_max.y = mag_raw.y;
- if (mag_raw.z > mag_next_max.z) mag_next_max.z = mag_raw.z;
+ if (mag_raw.x > mag_next_max.x) {
+ mag_next_max.x = mag_raw.x;
+ }
+ if (mag_raw.y > mag_next_max.y) {
+ mag_next_max.y = mag_raw.y;
+ }
+ if (mag_raw.z > mag_next_max.z) {
+ mag_next_max.z = mag_raw.z;
+ }
- if (mag_raw.x < mag_next_min.x) mag_next_min.x = mag_raw.x;
- if (mag_raw.y < mag_next_min.y) mag_next_min.y = mag_raw.y;
- if (mag_raw.z < mag_next_min.z) mag_next_min.z = mag_raw.z;
+ if (mag_raw.x < mag_next_min.x) {
+ mag_next_min.x = mag_raw.x;
+ }
+ if (mag_raw.y < mag_next_min.y) {
+ mag_next_min.y = mag_raw.y;
+ }
+ if (mag_raw.z < mag_next_min.z) {
+ mag_next_min.z = mag_raw.z;
+ }
// scale our x, y and z
if (!(mag_current_max.x - mag_current_min.x)) {
@@ -436,12 +448,6 @@ void MobileVRInterface::process() {
};
};
-void MobileVRInterface::notification(int p_what){
- _THREAD_SAFE_METHOD_
-
- // nothing to do here, I guess we could pauze our sensors...
-}
-
MobileVRInterface::MobileVRInterface() {
initialized = false;
diff --git a/modules/mobile_vr/mobile_vr_interface.h b/modules/mobile_vr/mobile_vr_interface.h
index 3a9ed1314a..1afa6c39b6 100644
--- a/modules/mobile_vr/mobile_vr_interface.h
+++ b/modules/mobile_vr/mobile_vr_interface.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -128,21 +128,21 @@ public:
void set_k2(const real_t p_k2);
real_t get_k2() const;
- virtual StringName get_name() const;
- virtual int get_capabilities() const;
+ virtual StringName get_name() const override;
+ virtual int get_capabilities() const override;
- virtual bool is_initialized() const;
- virtual bool initialize();
- virtual void uninitialize();
+ virtual bool is_initialized() const override;
+ virtual bool initialize() override;
+ virtual void uninitialize() override;
- virtual Size2 get_render_targetsize();
- virtual bool is_stereo();
- virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform);
- virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far);
- virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect);
+ virtual Size2 get_render_targetsize() override;
+ virtual bool is_stereo() override;
+ virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override;
+ virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override;
+ virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override;
- virtual void process();
- virtual void notification(int p_what);
+ virtual void process() override;
+ virtual void notification(int p_what) override {}
MobileVRInterface();
~MobileVRInterface();
diff --git a/modules/mobile_vr/register_types.cpp b/modules/mobile_vr/register_types.cpp
index 75638d47c4..e7d33ba8a7 100644
--- a/modules/mobile_vr/register_types.cpp
+++ b/modules/mobile_vr/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,9 +35,11 @@
void register_mobile_vr_types() {
ClassDB::register_class<MobileVRInterface>();
- Ref<MobileVRInterface> mobile_vr;
- mobile_vr.instance();
- XRServer::get_singleton()->add_interface(mobile_vr);
+ if (XRServer::get_singleton()) {
+ Ref<MobileVRInterface> mobile_vr;
+ mobile_vr.instance();
+ XRServer::get_singleton()->add_interface(mobile_vr);
+ }
}
void unregister_mobile_vr_types() {
diff --git a/modules/mobile_vr/register_types.h b/modules/mobile_vr/register_types.h
index 33f608b6ed..9f20f252a4 100644
--- a/modules/mobile_vr/register_types.h
+++ b/modules/mobile_vr/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/modules_builders.py b/modules/modules_builders.py
index e7be6380d1..2243162555 100644
--- a/modules/modules_builders.py
+++ b/modules/modules_builders.py
@@ -12,5 +12,16 @@ def generate_modules_enabled(target, source, env):
f.write("#define %s\n" % ("MODULE_" + module.upper() + "_ENABLED"))
+def generate_modules_tests(target, source, env):
+ import os
+ import glob
+
+ with open(target[0].path, "w") as f:
+ for name, path in env.module_list.items():
+ headers = glob.glob(os.path.join(path, "tests", "*.h"))
+ for h in headers:
+ f.write('#include "%s"\n' % (os.path.normpath(h)))
+
+
if __name__ == "__main__":
subprocess_main(globals())
diff --git a/modules/mono/SCsub b/modules/mono/SCsub
index c723b210cb..3b94949470 100644
--- a/modules/mono/SCsub
+++ b/modules/mono/SCsub
@@ -29,7 +29,7 @@ if env_mono["tools"] or env_mono["target"] != "release":
mono_configure.configure(env, env_mono)
-if env_mono["tools"] and env_mono["mono_glue"]:
+if env_mono["tools"] and env_mono["mono_glue"] and env_mono["build_cil"]:
# Build Godot API solution
import build_scripts.api_solution_build as api_solution_build
@@ -40,6 +40,11 @@ if env_mono["tools"] and env_mono["mono_glue"]:
godot_tools_build.build(env_mono, api_sln_cmd)
+ # Build Godot.NET.Sdk
+ import build_scripts.godot_net_sdk_build as godot_net_sdk_build
+
+ godot_net_sdk_build.build(env_mono)
+
# Add sources
env_mono.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/mono/build_scripts/godot_net_sdk_build.py b/modules/mono/build_scripts/godot_net_sdk_build.py
new file mode 100644
index 0000000000..3bfba0f0f6
--- /dev/null
+++ b/modules/mono/build_scripts/godot_net_sdk_build.py
@@ -0,0 +1,45 @@
+# Build Godot.NET.Sdk solution
+
+import os
+
+from SCons.Script import Dir
+
+
+def build_godot_net_sdk(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/Godot.NET.Sdk/Godot.NET.Sdk.sln")
+ build_config = "Release"
+
+ from .solution_builder import build_solution
+
+ extra_msbuild_args = ["/p:GodotPlatform=" + env["platform"]]
+
+ build_solution(env, solution_path, build_config, extra_msbuild_args)
+ # No need to copy targets. The Godot.NET.Sdk csproj takes care of copying them.
+
+
+def build(env_mono):
+ assert env_mono["tools"]
+
+ output_dir = Dir("#bin").abspath
+ editor_tools_dir = os.path.join(output_dir, "GodotSharp", "Tools")
+ nupkgs_dir = os.path.join(editor_tools_dir, "nupkgs")
+
+ module_dir = os.getcwd()
+
+ package_version_file = os.path.join(
+ module_dir, "editor", "Godot.NET.Sdk", "Godot.NET.Sdk", "Godot.NET.Sdk_PackageVersion.txt"
+ )
+
+ with open(package_version_file, mode="r") as f:
+ version = f.read().strip()
+
+ target_filenames = ["Godot.NET.Sdk.%s.nupkg" % version]
+
+ targets = [os.path.join(nupkgs_dir, filename) for filename in target_filenames]
+
+ cmd = env_mono.CommandNoCache(targets, [], build_godot_net_sdk, module_dir=module_dir)
+ env_mono.AlwaysBuild(cmd)
diff --git a/modules/mono/build_scripts/godot_tools_build.py b/modules/mono/build_scripts/godot_tools_build.py
index cffacf2577..3bbbf29d3b 100644
--- a/modules/mono/build_scripts/godot_tools_build.py
+++ b/modules/mono/build_scripts/godot_tools_build.py
@@ -13,13 +13,11 @@ def build_godot_tools(source, target, env):
solution_path = os.path.join(module_dir, "editor/GodotTools/GodotTools.sln")
build_config = "Debug" if env["target"] == "debug" else "Release"
- # Custom build target to make sure output is always copied to the data dir.
- extra_build_args = ["/Target:Build;GodotTools:BuildAlwaysCopyToDataDir"]
+ from .solution_builder import build_solution
- from .solution_builder import build_solution, nuget_restore
+ extra_msbuild_args = ["/p:GodotPlatform=" + env["platform"]]
- nuget_restore(env, solution_path)
- build_solution(env, solution_path, build_config, extra_build_args)
+ build_solution(env, solution_path, build_config, extra_msbuild_args)
# No need to copy targets. The GodotTools csproj takes care of copying them.
diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py
index d276d7d886..28494bff6e 100644
--- a/modules/mono/build_scripts/make_android_mono_config.py
+++ b/modules/mono/build_scripts/make_android_mono_config.py
@@ -32,17 +32,16 @@ namespace {
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() {
Vector<uint8_t> data;
data.resize(config_uncompressed_size);
uint8_t* w = data.ptrw();
- Compression::decompress(w.ptr(), config_uncompressed_size, config_compressed_data,
+ Compression::decompress(w, config_uncompressed_size, config_compressed_data,
config_compressed_size, Compression::MODE_DEFLATE);
String s;
- if (s.parse_utf8((const char *)w.ptr(), data.size())) {
+ if (s.parse_utf8((const char *)w, data.size())) {
ERR_FAIL_V(String());
}
return s;
diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py
index 23f01b3cca..309abfbff7 100644
--- a/modules/mono/build_scripts/mono_configure.py
+++ b/modules/mono/build_scripts/mono_configure.py
@@ -1,6 +1,5 @@
import os
import os.path
-import sys
import subprocess
from SCons.Script import Dir, Environment
@@ -98,6 +97,7 @@ def configure(env, env_mono):
copy_mono_root = env["copy_mono_root"]
mono_prefix = env["mono_prefix"]
+ mono_bcl = env["mono_bcl"]
mono_lib_names = ["mono-2.0-sgen", "monosgen-2.0"]
@@ -125,7 +125,8 @@ def configure(env, env_mono):
if not mono_prefix and (os.getenv("MONO32_PREFIX") or os.getenv("MONO64_PREFIX")):
print(
- "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the 'mono_prefix' SCons parameter instead"
+ "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the"
+ " 'mono_prefix' SCons parameter instead"
)
# Although we don't support building with tools for any platform where we currently use static AOT,
@@ -191,17 +192,16 @@ def configure(env, env_mono):
env.Append(LIBS=["psapi"])
env.Append(LIBS=["version"])
else:
- mono_lib_name = find_name_in_dir_files(
- mono_lib_path, mono_lib_names, prefixes=["", "lib"], extensions=lib_suffixes
- )
+ mono_lib_file = find_file_in_dir(mono_lib_path, mono_lib_names, extensions=lib_suffixes)
- if not mono_lib_name:
+ if not mono_lib_file:
raise RuntimeError("Could not find mono library in: " + mono_lib_path)
if env.msvc:
- env.Append(LINKFLAGS=mono_lib_name + ".lib")
+ env.Append(LINKFLAGS=mono_lib_file)
else:
- env.Append(LIBS=[mono_lib_name])
+ mono_lib_file_path = os.path.join(mono_lib_path, mono_lib_file)
+ env.Append(LINKFLAGS=mono_lib_file_path)
mono_bin_path = os.path.join(mono_root, "bin")
@@ -263,7 +263,8 @@ def configure(env, env_mono):
env_mono.Append(CPPDEFINES=["_REENTRANT"])
if mono_static:
- env.Append(LINKFLAGS=["-rdynamic"])
+ if not is_javascript:
+ env.Append(LINKFLAGS=["-rdynamic"])
mono_lib_file = os.path.join(mono_lib_path, "lib" + mono_lib + ".a")
@@ -397,9 +398,8 @@ def configure(env, env_mono):
mono_root = subprocess.check_output(["pkg-config", "mono-2", "--variable=prefix"]).decode("utf8").strip()
if tools_enabled:
- copy_mono_root_files(env, mono_root)
- else:
- print("Ignoring option: 'copy_mono_root'; only available for builds with 'tools' enabled.")
+ # Only supported for editor builds.
+ copy_mono_root_files(env, mono_root, mono_bcl)
def make_template_dir(env, mono_root):
@@ -432,7 +432,7 @@ def make_template_dir(env, mono_root):
copy_mono_shared_libs(env, mono_root, template_mono_root_dir)
-def copy_mono_root_files(env, mono_root):
+def copy_mono_root_files(env, mono_root, mono_bcl):
from glob import glob
from shutil import copy
from shutil import rmtree
@@ -457,7 +457,7 @@ def copy_mono_root_files(env, mono_root):
# Copy framework assemblies
- mono_framework_dir = os.path.join(mono_root, "lib", "mono", "4.5")
+ mono_framework_dir = mono_bcl or os.path.join(mono_root, "lib", "mono", "4.5")
mono_framework_facades_dir = os.path.join(mono_framework_dir, "Facades")
editor_mono_framework_dir = os.path.join(editor_mono_root_dir, "lib", "mono", "4.5")
diff --git a/modules/mono/build_scripts/mono_reg_utils.py b/modules/mono/build_scripts/mono_reg_utils.py
index 3090a4759a..0ec7e2f433 100644
--- a/modules/mono/build_scripts/mono_reg_utils.py
+++ b/modules/mono/build_scripts/mono_reg_utils.py
@@ -9,7 +9,7 @@ if os.name == "nt":
def _reg_open_key(key, subkey):
try:
return winreg.OpenKey(key, subkey)
- except (WindowsError, OSError):
+ except OSError:
if platform.architecture()[0] == "32bit":
bitness_sam = winreg.KEY_WOW64_64KEY
else:
@@ -37,7 +37,7 @@ def _find_mono_in_reg(subkey, bits):
with _reg_open_key_bits(winreg.HKEY_LOCAL_MACHINE, subkey, bits) as hKey:
value = winreg.QueryValueEx(hKey, "SdkInstallRoot")[0]
return value
- except (WindowsError, OSError):
+ except OSError:
return None
@@ -48,7 +48,7 @@ def _find_mono_in_reg_old(subkey, bits):
if default_clr:
return _find_mono_in_reg(subkey + "\\" + default_clr, bits)
return None
- except (WindowsError, EnvironmentError):
+ except OSError:
return None
@@ -97,7 +97,7 @@ def find_msbuild_tools_path_reg():
raise ValueError("Cannot find `installationPath` entry")
except ValueError as e:
print("Error reading output from vswhere: " + e.message)
- except WindowsError:
+ except OSError:
pass # Fine, vswhere not found
except (subprocess.CalledProcessError, OSError):
pass
@@ -109,5 +109,5 @@ def find_msbuild_tools_path_reg():
with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, subkey) as hKey:
value = winreg.QueryValueEx(hKey, "MSBuildToolsPath")[0]
return value
- except (WindowsError, OSError):
+ except OSError:
return ""
diff --git a/modules/mono/build_scripts/solution_builder.py b/modules/mono/build_scripts/solution_builder.py
index db6b4ff7aa..6a621c3c8b 100644
--- a/modules/mono/build_scripts/solution_builder.py
+++ b/modules/mono/build_scripts/solution_builder.py
@@ -4,91 +4,38 @@ import os
verbose = False
-def find_nuget_unix():
- import os
-
- if "NUGET_PATH" in os.environ:
- hint_path = os.environ["NUGET_PATH"]
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
- hint_path = os.path.join(hint_path, "nuget")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
-
+def find_dotnet_cli():
import os.path
- import sys
-
- hint_dirs = ["/opt/novell/mono/bin"]
- if sys.platform == "darwin":
- hint_dirs = [
- "/Library/Frameworks/Mono.framework/Versions/Current/bin",
- "/usr/local/var/homebrew/linked/mono/bin",
- ] + hint_dirs
- for hint_dir in hint_dirs:
- hint_path = os.path.join(hint_dir, "nuget")
- if os.path.isfile(hint_path):
- return hint_path
- elif os.path.isfile(hint_path + ".exe"):
- return hint_path + ".exe"
-
- for hint_dir in os.environ["PATH"].split(os.pathsep):
- hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, "nuget")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
- if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
- return hint_path + ".exe"
-
- return None
-
-
-def find_nuget_windows(env):
- import os
-
- if "NUGET_PATH" in os.environ:
- hint_path = os.environ["NUGET_PATH"]
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
- hint_path = os.path.join(hint_path, "nuget.exe")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
-
- from .mono_reg_utils import find_mono_root_dir
-
- mono_root = env["mono_prefix"] or find_mono_root_dir(env["bits"])
-
- if mono_root:
- mono_bin_dir = os.path.join(mono_root, "bin")
- nuget_mono = os.path.join(mono_bin_dir, "nuget.bat")
-
- if os.path.isfile(nuget_mono):
- return nuget_mono
-
- # Standalone NuGet
-
- for hint_dir in os.environ["PATH"].split(os.pathsep):
- hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, "nuget.exe")
- if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
- return hint_path
-
- return None
+ if os.name == "nt":
+ for hint_dir in os.environ["PATH"].split(os.pathsep):
+ hint_dir = hint_dir.strip('"')
+ hint_path = os.path.join(hint_dir, "dotnet")
+ if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
+ return hint_path
+ if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
+ return hint_path + ".exe"
+ else:
+ for hint_dir in os.environ["PATH"].split(os.pathsep):
+ hint_dir = hint_dir.strip('"')
+ hint_path = os.path.join(hint_dir, "dotnet")
+ if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
+ return hint_path
-def find_msbuild_unix(filename):
+def find_msbuild_unix():
import os.path
import sys
- hint_dirs = ["/opt/novell/mono/bin"]
+ hint_dirs = []
if sys.platform == "darwin":
- hint_dirs = [
+ hint_dirs[:0] = [
"/Library/Frameworks/Mono.framework/Versions/Current/bin",
"/usr/local/var/homebrew/linked/mono/bin",
- ] + hint_dirs
+ ]
for hint_dir in hint_dirs:
- hint_path = os.path.join(hint_dir, filename)
+ hint_path = os.path.join(hint_dir, "msbuild")
if os.path.isfile(hint_path):
return hint_path
elif os.path.isfile(hint_path + ".exe"):
@@ -96,7 +43,7 @@ def find_msbuild_unix(filename):
for hint_dir in os.environ["PATH"].split(os.pathsep):
hint_dir = hint_dir.strip('"')
- hint_path = os.path.join(hint_dir, filename)
+ hint_path = os.path.join(hint_dir, "msbuild")
if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
return hint_path
if os.path.isfile(hint_path + ".exe") and os.access(hint_path + ".exe", os.X_OK):
@@ -158,21 +105,6 @@ def run_command(command, args, env_override=None, name=None):
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")
-
-
def build_solution(env, solution_path, build_config, extra_msbuild_args=[]):
global verbose
verbose = env["verbose"]
@@ -183,38 +115,31 @@ def build_solution(env, solution_path, build_config, extra_msbuild_args=[]):
if "PLATFORM" in msbuild_env:
del msbuild_env["PLATFORM"]
- # Find MSBuild
- if os.name == "nt":
- msbuild_info = find_msbuild_windows(env)
- if msbuild_info is None:
- raise RuntimeError("Cannot find MSBuild executable")
- msbuild_path = msbuild_info[0]
- msbuild_env.update(msbuild_info[1])
- else:
- msbuild_path = find_msbuild_unix("msbuild")
- if msbuild_path is None:
- xbuild_fallback = env["xbuild_fallback"]
-
- if xbuild_fallback and os.name == "nt":
- print("Option 'xbuild_fallback' not supported on Windows")
- xbuild_fallback = False
-
- if xbuild_fallback:
- print("Cannot find MSBuild executable, trying with xbuild")
- print("Warning: xbuild is deprecated")
+ msbuild_args = []
- msbuild_path = find_msbuild_unix("xbuild")
+ dotnet_cli = find_dotnet_cli()
- if msbuild_path is None:
- raise RuntimeError("Cannot find xbuild executable")
- else:
+ if dotnet_cli:
+ msbuild_path = dotnet_cli
+ msbuild_args += ["msbuild"] # `dotnet msbuild` command
+ else:
+ # Find MSBuild
+ if os.name == "nt":
+ msbuild_info = find_msbuild_windows(env)
+ if msbuild_info is None:
+ raise RuntimeError("Cannot find MSBuild executable")
+ msbuild_path = msbuild_info[0]
+ msbuild_env.update(msbuild_info[1])
+ else:
+ msbuild_path = find_msbuild_unix()
+ if msbuild_path is None:
raise RuntimeError("Cannot find MSBuild executable")
print("MSBuild path: " + msbuild_path)
# Build solution
- msbuild_args = [solution_path, "/p:Configuration=" + build_config]
+ msbuild_args += [solution_path, "/restore", "/t:Build", "/p:Configuration=" + build_config]
msbuild_args += extra_msbuild_args
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
index 384685d04b..553c6eca53 100644
--- a/modules/mono/class_db_api_json.cpp
+++ b/modules/mono/class_db_api_json.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,9 +32,9 @@
#ifdef DEBUG_METHODS_ENABLED
+#include "core/config/project_settings.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) {
@@ -45,18 +45,17 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
const StringName *k = nullptr;
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)
+ if (t->api != p_api || !t->exposed) {
continue;
+ }
Dictionary class_dict;
classes_dict[t->name] = class_dict;
@@ -70,13 +69,13 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
k = nullptr;
while ((k = t->method_map.next(k))) {
-
String name = k->operator String();
- ERR_CONTINUE(name.empty());
+ ERR_CONTINUE(name.is_empty());
- if (name[0] == '_')
+ if (name[0] == '_') {
continue; // Ignore non-virtual methods that start with an underscore
+ }
snames.push_back(*k);
}
@@ -123,7 +122,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
method_dict["hint_flags"] = mb->get_hint_flags();
}
- if (!methods.empty()) {
+ if (!methods.is_empty()) {
class_dict["methods"] = methods;
}
}
@@ -135,7 +134,6 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
k = nullptr;
while ((k = t->constant_map.next(k))) {
-
snames.push_back(*k);
}
@@ -151,7 +149,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
constant_dict["value"] = t->constant_map[F->get()];
}
- if (!constants.empty()) {
+ if (!constants.is_empty()) {
class_dict["constants"] = constants;
}
}
@@ -163,7 +161,6 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
k = nullptr;
while ((k = t->signal_map.next(k))) {
-
snames.push_back(*k);
}
@@ -187,7 +184,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
}
}
- if (!signals.empty()) {
+ if (!signals.is_empty()) {
class_dict["signals"] = signals;
}
}
@@ -199,7 +196,6 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
k = nullptr;
while ((k = t->property_setget.next(k))) {
-
snames.push_back(*k);
}
@@ -218,7 +214,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
property_dict["getter"] = psg->getter;
}
- if (!properties.empty()) {
+ if (!properties.is_empty()) {
class_dict["property_setget"] = properties;
}
}
@@ -237,7 +233,7 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
property_dict["usage"] = F->get().usage;
}
- if (!property_list.empty()) {
+ if (!property_list.is_empty()) {
class_dict["property_list"] = property_list;
}
}
diff --git a/modules/mono/class_db_api_json.h b/modules/mono/class_db_api_json.h
index 7f016ac3d6..6698a6260f 100644
--- a/modules/mono/class_db_api_json.h
+++ b/modules/mono/class_db_api_json.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,13 +31,13 @@
#ifndef CLASS_DB_API_JSON_H
#define CLASS_DB_API_JSON_H
-// 'core/method_bind.h' defines DEBUG_METHODS_ENABLED, but it looks like we
-// cannot include it here. That's why we include it through 'core/class_db.h'.
-#include "core/class_db.h"
+// 'core/object/method_bind.h' defines DEBUG_METHODS_ENABLED, but it looks like we
+// cannot include it here. That's why we include it through 'core/object/class_db.h'.
+#include "core/object/class_db.h"
#ifdef DEBUG_METHODS_ENABLED
-#include "core/ustring.h"
+#include "core/string/ustring.h"
void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api);
diff --git a/modules/mono/config.py b/modules/mono/config.py
index 106ca6e028..4c851a2989 100644
--- a/modules/mono/config.py
+++ b/modules/mono/config.py
@@ -11,7 +11,6 @@ def configure(env):
if platform not in supported_platforms:
raise RuntimeError("This module does not currently support building for this platform")
- env.use_ptrcall = True
env.add_module_version_string("mono")
from SCons.Script import BoolVariable, PathVariable, Variables, Help
@@ -23,19 +22,25 @@ def configure(env):
envvars.Add(
PathVariable(
"mono_prefix",
- "Path to the mono installation directory for the target platform and architecture",
+ "Path to the Mono installation directory for the target platform and architecture",
"",
PathVariable.PathAccept,
)
)
- envvars.Add(BoolVariable("mono_static", "Statically link mono", default_mono_static))
- 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
+ PathVariable(
+ "mono_bcl",
+ "Path to a custom Mono BCL (Base Class Library) directory for the target platform",
+ "",
+ PathVariable.PathAccept,
)
)
- envvars.Add(BoolVariable("xbuild_fallback", "If MSBuild is not found, fallback to xbuild", False))
+ envvars.Add(BoolVariable("mono_static", "Statically link Mono", default_mono_static))
+ envvars.Add(BoolVariable("mono_glue", "Build with the Mono glue sources", True))
+ envvars.Add(BoolVariable("build_cil", "Build C# solutions", True))
+ envvars.Add(
+ BoolVariable("copy_mono_root", "Make a copy of the Mono installation directory to bundle with the editor", True)
+ )
# TODO: It would be great if this could be detected automatically instead
envvars.Add(
@@ -57,7 +62,6 @@ def configure(env):
def get_doc_classes():
return [
- "@C#",
"CSharpScript",
"GodotSharp",
]
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index f5911275c9..18fe44108f 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,6 +33,7 @@
#include <mono/metadata/threads.h>
#include <stdint.h>
+#include "core/config/project_settings.h"
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
#include "core/io/json.h"
@@ -40,11 +41,9 @@
#include "core/os/mutex.h"
#include "core/os/os.h"
#include "core/os/thread.h"
-#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "editor/bindings_generator.h"
-#include "editor/csharp_project.h"
#include "editor/editor_node.h"
#include "editor/node_dock.h"
#endif
@@ -67,7 +66,6 @@
#ifdef TOOLS_ENABLED
static bool _create_project_solution_if_needed() {
-
String sln_path = GodotSharpDirs::get_project_sln_path();
String csproj_path = GodotSharpDirs::get_project_csproj_path();
@@ -85,28 +83,23 @@ static bool _create_project_solution_if_needed() {
CSharpLanguage *CSharpLanguage::singleton = nullptr;
String CSharpLanguage::get_name() const {
-
return "C#";
}
String CSharpLanguage::get_type() const {
-
return "CSharpScript";
}
String CSharpLanguage::get_extension() const {
-
return "cs";
}
Error CSharpLanguage::execute_file(const String &p_path) {
-
// ??
return OK;
}
void CSharpLanguage::init() {
-
#ifdef DEBUG_METHODS_ENABLED
if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
@@ -131,8 +124,9 @@ void CSharpLanguage::init() {
print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'");
#endif
- if (gdmono->is_runtime_initialized())
+ if (gdmono->is_runtime_initialized()) {
gdmono->initialize_load_assemblies();
+ }
#ifdef TOOLS_ENABLED
EditorNode::add_init_callback(&_editor_init_callback);
@@ -140,9 +134,13 @@ void CSharpLanguage::init() {
}
void CSharpLanguage::finish() {
+ finalize();
+}
- if (finalized)
+void CSharpLanguage::finalize() {
+ if (finalized) {
return;
+ }
finalizing = true;
@@ -184,7 +182,6 @@ void CSharpLanguage::finish() {
}
void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
-
static const char *_reserved_words[] = {
// Reserved keywords
"abstract",
@@ -295,7 +292,7 @@ void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
"when",
"where",
"yield",
- 0
+ nullptr
};
const char **w = _reserved_words;
@@ -307,13 +304,11 @@ void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
}
void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
-
p_delimiters->push_back("//"); // single-line comment
p_delimiters->push_back("/* */"); // delimited comment
}
void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
-
p_delimiters->push_back("' '"); // character literal
p_delimiters->push_back("\" \""); // regular string literal
// Verbatim string literals (`@" "`) don't render correctly, so don't highlight them.
@@ -321,7 +316,6 @@ void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
}
static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
-
String base_class = p_base_class_name;
if (p_class_name == base_class) {
base_class = "Godot." + base_class;
@@ -330,7 +324,6 @@ static String get_base_class_name(const String &p_base_class_name, const String
}
Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
-
String script_template = "using " BINDINGS_NAMESPACE ";\n"
"using System;\n"
"\n"
@@ -353,35 +346,37 @@ Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const Strin
"// }\n"
"}\n";
- String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
+ // Replaces all spaces in p_class_name with underscores to prevent
+ // erronous C# Script templates from being generated when the object name
+ // has spaces in it.
+ String class_name_no_spaces = p_class_name.replace(" ", "_");
+ String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
script_template = script_template.replace("%BASE%", base_class_name)
- .replace("%CLASS%", p_class_name);
+ .replace("%CLASS%", class_name_no_spaces);
Ref<CSharpScript> script;
script.instance();
script->set_source_code(script_template);
- script->set_name(p_class_name);
+ script->set_name(class_name_no_spaces);
return script;
}
bool CSharpLanguage::is_using_templates() {
-
return true;
}
void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
-
String src = p_script->get_source_code();
- String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
+ String class_name_no_spaces = p_class_name.replace(" ", "_");
+ String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
src = src.replace("%BASE%", base_class_name)
- .replace("%CLASS%", p_class_name)
+ .replace("%CLASS%", class_name_no_spaces)
.replace("%TS%", _get_indentation());
p_script->set_source_code(src);
}
String CSharpLanguage::validate_path(const String &p_path) const {
-
String class_name = p_path.get_file().get_basename();
List<String> keywords;
get_reserved_words(&keywords);
@@ -392,32 +387,30 @@ String CSharpLanguage::validate_path(const String &p_path) const {
}
Script *CSharpLanguage::create_script() const {
-
return memnew(CSharpScript);
}
bool CSharpLanguage::has_named_classes() const {
-
return false;
}
bool CSharpLanguage::supports_builtin_mode() const {
-
return false;
}
#ifdef TOOLS_ENABLED
static String variant_type_to_managed_name(const String &p_var_type_name) {
-
- if (p_var_type_name.empty())
+ if (p_var_type_name.is_empty()) {
return "object";
+ }
if (!ClassDB::class_exists(p_var_type_name)) {
return p_var_type_name;
}
- if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
+ if (p_var_type_name == Variant::get_type_name(Variant::OBJECT)) {
return "Godot.Object";
+ }
if (p_var_type_name == Variant::get_type_name(Variant::FLOAT)) {
#ifdef REAL_T_IS_DOUBLE
@@ -427,36 +420,49 @@ static String variant_type_to_managed_name(const String &p_var_type_name) {
#endif
}
- if (p_var_type_name == Variant::get_type_name(Variant::STRING))
+ if (p_var_type_name == Variant::get_type_name(Variant::STRING)) {
return "string"; // I prefer this one >:[
+ }
- if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
+ if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY)) {
return "Collections.Dictionary";
+ }
- if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
+ if (p_var_type_name == Variant::get_type_name(Variant::ARRAY)) {
return "Collections.Array";
+ }
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY))
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY)) {
return "byte[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY)) {
return "int[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY)) {
return "long[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY)) {
return "float[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY)) {
return "double[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY)) {
return "string[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY)) {
return "Vector2[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY)) {
return "Vector3[]";
- if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY))
+ }
+ if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY)) {
return "Color[]";
+ }
- if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL))
+ if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL)) {
return "SignalInfo";
+ }
Variant::Type var_types[] = {
Variant::BOOL,
@@ -476,13 +482,14 @@ static String variant_type_to_managed_name(const String &p_var_type_name) {
Variant::COLOR,
Variant::STRING_NAME,
Variant::NODE_PATH,
- Variant::_RID,
+ Variant::RID,
Variant::CALLABLE
};
for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
- if (p_var_type_name == Variant::get_type_name(var_types[i]))
+ if (p_var_type_name == Variant::get_type_name(var_types[i])) {
return p_var_type_name;
+ }
}
return "object";
@@ -496,8 +503,9 @@ String CSharpLanguage::make_function(const String &, const String &p_name, const
for (int i = 0; i < p_args.size(); i++) {
const String &arg = p_args[i];
- if (i > 0)
+ if (i > 0) {
s += ", ";
+ }
s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
}
@@ -531,60 +539,60 @@ String CSharpLanguage::_get_indentation() const {
}
String CSharpLanguage::debug_get_error() const {
-
return _debug_error;
}
int CSharpLanguage::debug_get_stack_level_count() const {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return 1;
+ }
// TODO: StackTrace
return 1;
}
int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return _debug_parse_err_line;
+ }
// TODO: StackTrace
return 1;
}
String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return String();
+ }
// TODO: StackTrace
return String();
}
String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
-
- if (_debug_parse_err_line >= 0)
+ if (_debug_parse_err_line >= 0) {
return _debug_parse_err_file;
+ }
// TODO: StackTrace
return String();
}
Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
-
#ifdef DEBUG_ENABLED
// Printing an error here will result in endless recursion, so we must be careful
static thread_local bool _recursion_flag_ = false;
- if (_recursion_flag_)
+ if (_recursion_flag_) {
return Vector<StackInfo>();
+ }
_recursion_flag_ = true;
SCOPE_EXIT { _recursion_flag_ = false; };
GD_MONO_SCOPE_THREAD_ATTACH;
- if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated)
+ if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated) {
return Vector<StackInfo>();
+ }
MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
@@ -604,11 +612,11 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info()
#ifdef DEBUG_ENABLED
Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
-
// Printing an error here will result in endless recursion, so we must be careful
static thread_local bool _recursion_flag_ = false;
- if (_recursion_flag_)
+ if (_recursion_flag_) {
return Vector<StackInfo>();
+ }
_recursion_flag_ = true;
SCOPE_EXIT { _recursion_flag_ = false; };
@@ -625,8 +633,9 @@ Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObjec
int frame_count = mono_array_length(frames);
- if (frame_count <= 0)
+ if (frame_count <= 0) {
return Vector<StackInfo>();
+ }
Vector<StackInfo> si;
si.resize(frame_count);
@@ -672,13 +681,13 @@ void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
ObjectID id = p_obj->get_instance_id();
Map<ObjectID, int>::Element *elem = unsafe_object_references.find(id);
ERR_FAIL_NULL(elem);
- if (--elem->value() == 0)
+ if (--elem->value() == 0) {
unsafe_object_references.erase(elem);
+ }
#endif
}
void CSharpLanguage::frame() {
-
if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != nullptr) {
const Ref<MonoGCHandleRef> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle;
@@ -698,11 +707,11 @@ void CSharpLanguage::frame() {
}
struct CSharpScriptDepSort {
-
// must support sorting so inheritance works properly (parent must be reloaded first)
bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
- if (A == B)
+ if (A == B) {
return false; // shouldn't happen but..
+ }
GDMonoClass *I = B->base;
while (I) {
if (I == A->script_class) {
@@ -718,7 +727,6 @@ struct CSharpScriptDepSort {
};
void CSharpLanguage::reload_all_scripts() {
-
#ifdef GD_MONO_HOT_RELOAD
if (is_assembly_reloading_needed()) {
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -728,7 +736,6 @@ void CSharpLanguage::reload_all_scripts() {
}
void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
-
(void)p_script; // UNUSED
CRASH_COND(!Engine::get_singleton()->is_editor_hint());
@@ -747,15 +754,15 @@ void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft
#ifdef GD_MONO_HOT_RELOAD
bool CSharpLanguage::is_assembly_reloading_needed() {
-
- if (!gdmono->is_runtime_initialized())
+ if (!gdmono->is_runtime_initialized()) {
return false;
+ }
GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
String appname = ProjectSettings::get_singleton()->get("application/config/name");
String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- if (appname_safe.empty()) {
+ if (appname_safe.is_empty()) {
appname_safe = "UnnamedProject";
}
@@ -767,24 +774,27 @@ bool CSharpLanguage::is_assembly_reloading_needed() {
if (!FileAccess::exists(proj_asm_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(appname_safe);
- if (!FileAccess::exists(proj_asm_path))
+ if (!FileAccess::exists(proj_asm_path)) {
return false; // No assembly to load
+ }
}
- if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
+ 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(appname_safe)))
+ if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe))) {
return false; // No assembly to load
+ }
}
return true;
}
void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
-
- if (!gdmono->is_runtime_initialized())
+ if (!gdmono->is_runtime_initialized()) {
return;
+ }
// There is no soft reloading with Mono. It's always hard reloading.
@@ -849,8 +859,8 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
to_reload.push_back(script);
- if (script->get_path().empty()) {
- script->tied_class_name_for_reload = script->script_class->get_name();
+ if (script->get_path().is_empty()) {
+ script->tied_class_name_for_reload = script->script_class->get_name_for_lookup();
script->tied_class_namespace_for_reload = script->script_class->get_namespace();
}
@@ -890,8 +900,9 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
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);
+ if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) {
+ obj->get_script_instance()->call(string_names.on_before_serialize);
+ }
// Save instance info
CSharpScript::StateBackup state;
@@ -926,15 +937,14 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
Object *obj = ObjectDB::get_instance(F->key());
- if (!obj)
+ if (!obj) {
continue;
+ }
ObjectID obj_id = obj->get_instance_id();
// Use a placeholder for now to avoid losing the state when saving a scene
- obj->set_script(scr);
-
PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
obj->set_script_instance(placeholder);
@@ -961,14 +971,13 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
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;
+ script->exports_invalidated = true;
#endif
- script->signals_invalidated = true;
+ script->signals_invalidated = true;
+ if (!script->get_path().is_empty()) {
script->reload(p_soft_reload);
- script->update_exports();
if (!script->valid) {
script->pending_reload_instances.clear();
@@ -1124,8 +1133,9 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
}
// Call OnAfterDeserialization
- if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
- obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
+ if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener))) {
+ obj->get_script_instance()->call(string_names.on_after_deserialize);
+ }
}
}
@@ -1173,7 +1183,6 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
#endif
void CSharpLanguage::_load_scripts_metadata() {
-
scripts_metadata.clear();
String scripts_metadata_filename = "scripts_metadata.";
@@ -1218,24 +1227,20 @@ void CSharpLanguage::_load_scripts_metadata() {
}
void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("cs");
}
#ifdef TOOLS_ENABLED
Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
-
return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
}
bool CSharpLanguage::overrides_external_editor() {
-
return get_godotsharp_editor()->call("OverridesExternalEditor");
}
#endif
void CSharpLanguage::thread_enter() {
-
#if 0
if (gdmono->is_runtime_initialized()) {
GDMonoUtils::attach_current_thread();
@@ -1244,7 +1249,6 @@ void CSharpLanguage::thread_enter() {
}
void CSharpLanguage::thread_exit() {
-
#if 0
if (gdmono->is_runtime_initialized()) {
GDMonoUtils::detach_current_thread();
@@ -1253,7 +1257,6 @@ void CSharpLanguage::thread_exit() {
}
bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
-
// Not a parser error in our case, but it's still used for other type of errors
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
_debug_parse_err_line = p_line;
@@ -1267,7 +1270,6 @@ bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const S
}
bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
-
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
_debug_parse_err_line = -1;
_debug_parse_err_file = "";
@@ -1286,6 +1288,7 @@ void CSharpLanguage::_on_scripts_domain_unloaded() {
script_binding.inited = false;
}
+#ifdef GD_MONO_HOT_RELOAD
{
MutexLock lock(ManagedCallable::instances_mutex);
@@ -1295,13 +1298,13 @@ void CSharpLanguage::_on_scripts_domain_unloaded() {
managed_callable->delegate_invoke = nullptr;
}
}
+#endif
scripts_metadata_invalidated = true;
}
#ifdef TOOLS_ENABLED
void CSharpLanguage::_editor_init_callback() {
-
register_editor_internal_calls();
// Initialize GodotSharpEditor
@@ -1316,7 +1319,8 @@ void CSharpLanguage::_editor_init_callback() {
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));
+ EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(
+ GDMonoMarshal::mono_object_to_variant(mono_object).operator Object *());
CRASH_COND(godotsharp_editor == nullptr);
// Enable it as a plugin
@@ -1328,13 +1332,11 @@ void CSharpLanguage::_editor_init_callback() {
#endif
void CSharpLanguage::set_language_index(int p_idx) {
-
ERR_FAIL_COND(lang_idx != -1);
lang_idx = p_idx;
}
void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
-
if (!p_gchandle.is_released()) { // Do not lock unnecessarily
MutexLock lock(get_singleton()->script_gchandle_release_mutex);
p_gchandle.release();
@@ -1342,7 +1344,6 @@ void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
}
void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle) {
-
uint32_t pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(p_expected_obj); // We might lock after this, so pin it
if (!p_gchandle.is_released()) { // Do not lock unnecessarily
@@ -1363,19 +1364,16 @@ void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, MonoGCH
}
CSharpLanguage::CSharpLanguage() {
-
ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
singleton = this;
}
CSharpLanguage::~CSharpLanguage() {
-
- finish();
+ finalize();
singleton = nullptr;
}
bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
-
#ifdef DEBUG_ENABLED
// I don't trust you
if (p_object->get_script_instance()) {
@@ -1388,8 +1386,9 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b
// ¯\_(ツ)_/¯
const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
- while (classinfo && !classinfo->exposed)
+ while (classinfo && !classinfo->exposed) {
classinfo = classinfo->inherits_ptr;
+ }
ERR_FAIL_NULL_V(classinfo, false);
type_name = classinfo->name;
@@ -1424,38 +1423,38 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b
}
void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
-
MutexLock lock(language_bind_mutex);
Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
- if (match)
+ if (match) {
return (void *)match;
+ }
CSharpScriptBinding script_binding;
- if (!setup_csharp_script_binding(script_binding, p_object))
+ if (!setup_csharp_script_binding(script_binding, p_object)) {
return nullptr;
+ }
return (void *)insert_script_binding(p_object, script_binding);
}
Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
-
return script_bindings.insert(p_object, p_script_binding);
}
void CSharpLanguage::free_instance_binding_data(void *p_data) {
-
if (GDMono::get_singleton() == nullptr) {
#ifdef DEBUG_ENABLED
- CRASH_COND(!script_bindings.empty());
+ CRASH_COND(!script_bindings.is_empty());
#endif
// Mono runtime finalized, all the gchandle bindings were already released
return;
}
- if (finalizing)
+ if (finalizing) {
return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
+ }
GD_MONO_ASSERT_THREAD_ATTACHED;
@@ -1481,7 +1480,6 @@ void CSharpLanguage::free_instance_binding_data(void *p_data) {
}
void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
-
Reference *ref_owner = Object::cast_to<Reference>(p_object);
#ifdef DEBUG_ENABLED
@@ -1495,8 +1493,9 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
MonoGCHandleData &gchandle = script_binding.gchandle;
- if (!script_binding.inited)
+ 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
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1506,8 +1505,9 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
// so the owner must hold the managed side alive again to avoid it from being GCed.
MonoObject *target = gchandle.get_target();
- if (!target)
+ if (!target) {
return; // Called after the managed side was collected, so nothing to do here
+ }
// Release the current weak handle and replace it with a strong handle.
MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(target);
@@ -1517,7 +1517,6 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
}
bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
-
Reference *ref_owner = Object::cast_to<Reference>(p_object);
#ifdef DEBUG_ENABLED
@@ -1533,8 +1532,9 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
int refcount = ref_owner->reference_get_count();
- if (!script_binding.inited)
+ if (!script_binding.inited) {
return refcount == 0;
+ }
if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1543,8 +1543,9 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
// the managed instance takes responsibility of deleting the owner when GCed.
MonoObject *target = gchandle.get_target();
- if (!target)
+ if (!target) {
return refcount == 0; // Called after the managed side was collected, so nothing to do here
+ }
// Release the current strong handle and replace it with a weak handle.
MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(target);
@@ -1558,7 +1559,6 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
}
CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
-
CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
Reference *ref = Object::cast_to<Reference>(p_owner);
@@ -1567,8 +1567,9 @@ CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpS
instance->owner = p_owner;
instance->gchandle = p_gchandle;
- if (instance->base_ref)
+ if (instance->base_ref) {
instance->_reference_owner_unsafe();
+ }
p_script->instances.insert(p_owner);
@@ -1576,7 +1577,6 @@ CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpS
}
MonoObject *CSharpInstance::get_mono_object() const {
-
ERR_FAIL_COND_V(gchandle.is_released(), nullptr);
return gchandle.get_target();
}
@@ -1586,7 +1586,6 @@ Object *CSharpInstance::get_owner() {
}
bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
-
ERR_FAIL_COND_V(!script.is_valid(), false);
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1627,8 +1626,9 @@ bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
MonoObject *ret = method->invoke(mono_object, args);
- if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
+ if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret)) {
return true;
+ }
break;
}
@@ -1640,7 +1640,6 @@ bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
}
bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
-
ERR_FAIL_COND_V(!script.is_valid(), false);
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1704,7 +1703,6 @@ bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
}
void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state) {
-
List<PropertyInfo> pinfo;
get_property_list(&pinfo);
@@ -1715,8 +1713,9 @@ void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Va
ManagedType managedType;
GDMonoField *field = script->script_class->get_field(state_pair.first);
- if (!field)
+ if (!field) {
continue; // Properties ignored. We get the property baking fields instead.
+ }
managedType = field->get_type();
@@ -1729,7 +1728,6 @@ void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Va
}
void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state) {
-
MonoObject *owner_managed = get_mono_object();
ERR_FAIL_NULL(owner_managed);
@@ -1737,8 +1735,9 @@ void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName,
const CSharpScript::EventSignal &event_signal = E->value();
MonoDelegate *delegate_field_value = (MonoDelegate *)event_signal.field->get_value(owner_managed);
- if (!delegate_field_value)
+ if (!delegate_field_value) {
continue; // Empty
+ }
Array serialized_data;
MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
@@ -1760,7 +1759,6 @@ void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName,
}
void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
-
for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
p_properties->push_back(E->value());
}
@@ -1784,8 +1782,9 @@ void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
if (ret) {
Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
- for (int i = 0, size = array.size(); i < size; i++)
+ for (int i = 0, size = array.size(); i < size; i++) {
p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
+ }
return;
}
@@ -1797,23 +1796,24 @@ void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
}
Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
-
if (script->member_info.has(p_name)) {
- if (r_is_valid)
+ if (r_is_valid) {
*r_is_valid = true;
+ }
return script->member_info[p_name].type;
}
- if (r_is_valid)
+ if (r_is_valid) {
*r_is_valid = false;
+ }
return Variant::NIL;
}
bool CSharpInstance::has_method(const StringName &p_method) const {
-
- if (!script.is_valid())
+ if (!script.is_valid()) {
return false;
+ }
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1831,7 +1831,6 @@ bool CSharpInstance::has_method(const StringName &p_method) const {
}
Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
ERR_FAIL_COND_V(!script.is_valid(), Variant());
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -1868,46 +1867,7 @@ Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args,
return Variant();
}
-void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- GD_MONO_SCOPE_THREAD_ATTACH;
-
- if (script.is_valid()) {
- MonoObject *mono_object = get_mono_object();
-
- ERR_FAIL_NULL(mono_object);
-
- _call_multilevel(mono_object, p_method, p_args, p_argcount);
- }
-}
-
-void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- GD_MONO_ASSERT_THREAD_ATTACHED;
-
- GDMonoClass *top = script->script_class;
-
- while (top && top != script->native) {
- GDMonoMethod *method = top->get_method(p_method, p_argcount);
-
- if (method) {
- method->invoke(p_mono_object, p_args);
- return;
- }
-
- top = top->get_parent_class();
- }
-}
-
-void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- // Sorry, the method is the one that controls the call order
-
- call_multilevel(p_method, p_args, p_argcount);
-}
-
bool CSharpInstance::_reference_owner_unsafe() {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref);
CRASH_COND(owner == nullptr);
@@ -1929,14 +1889,14 @@ bool CSharpInstance::_reference_owner_unsafe() {
}
bool CSharpInstance::_unreference_owner_unsafe() {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref);
CRASH_COND(owner == nullptr);
#endif
- if (!unsafe_referenced)
+ if (!unsafe_referenced) {
return false; // Already unreferenced
+ }
unsafe_referenced = false;
@@ -1969,7 +1929,7 @@ MonoObject *CSharpInstance::_internal_new_managed() {
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);
+ CRASH_COND(die);
owner = nullptr;
@@ -1979,8 +1939,9 @@ MonoObject *CSharpInstance::_internal_new_managed() {
// Tie managed to unmanaged
gchandle = MonoGCHandleData::new_strong_handle(mono_object);
- if (base_ref)
+ if (base_ref) {
_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
+ }
CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
@@ -1991,7 +1952,7 @@ MonoObject *CSharpInstance::_internal_new_managed() {
}
void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
-
+ // Must make sure event signals are not left dangling
disconnect_event_signals();
#ifdef DEBUG_ENABLED
@@ -2002,12 +1963,14 @@ void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
}
void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref);
CRASH_COND(gchandle.is_released());
#endif
+ // Must make sure event signals are not left dangling
+ disconnect_event_signals();
+
r_remove_script_instance = false;
if (_unreference_owner_unsafe()) {
@@ -2063,7 +2026,6 @@ void CSharpInstance::disconnect_event_signals() {
}
void CSharpInstance::refcount_incremented() {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref);
CRASH_COND(owner == nullptr);
@@ -2086,7 +2048,6 @@ void CSharpInstance::refcount_incremented() {
}
bool CSharpInstance::refcount_decremented() {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!base_ref);
CRASH_COND(owner == nullptr);
@@ -2156,7 +2117,6 @@ MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variab
}
void CSharpInstance::notification(int p_notification) {
-
GD_MONO_SCOPE_THREAD_ATTACH;
if (p_notification == Object::NOTIFICATION_PREDELETE) {
@@ -2195,7 +2155,6 @@ void CSharpInstance::notification(int p_notification) {
}
void CSharpInstance::_call_notification(int p_notification) {
-
GD_MONO_ASSERT_THREAD_ATTACHED;
MonoObject *mono_object = get_mono_object();
@@ -2203,7 +2162,7 @@ void CSharpInstance::_call_notification(int p_notification) {
// Custom version of _call_multilevel, optimized for _notification
- uint32_t arg = p_notification;
+ int32_t arg = p_notification;
void *args[1] = { &arg };
StringName method_name = CACHED_STRING_NAME(_notification);
@@ -2227,8 +2186,9 @@ String CSharpInstance::to_string(bool *r_valid) {
MonoObject *mono_object = get_mono_object();
if (mono_object == nullptr) {
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
@@ -2237,14 +2197,16 @@ String CSharpInstance::to_string(bool *r_valid) {
if (exc) {
GDMonoUtils::set_pending_exception(exc);
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
if (result == nullptr) {
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
@@ -2252,12 +2214,10 @@ String CSharpInstance::to_string(bool *r_valid) {
}
Ref<Script> CSharpInstance::get_script() const {
-
return script;
}
ScriptLanguage *CSharpInstance::get_language() {
-
return CSharpLanguage::get_singleton();
}
@@ -2266,11 +2226,13 @@ CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
}
CSharpInstance::~CSharpInstance() {
-
GD_MONO_SCOPE_THREAD_ATTACH;
destructing_script_instance = true;
+ // Must make sure event signals are not left dangling
+ disconnect_event_signals();
+
if (!gchandle.is_released()) {
if (!predelete_notified && !ref_dying) {
// This destructor is not called from the owners destructor.
@@ -2309,7 +2271,7 @@ CSharpInstance::~CSharpInstance() {
// Unreference the owner here, before the new "instance binding" references it.
// Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
bool die = _unreference_owner_unsafe();
- CRASH_COND(die == true); // `owner_keep_alive` holds a reference, so it can't die
+ CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
CRASH_COND(data == nullptr);
@@ -2348,14 +2310,12 @@ CSharpInstance::~CSharpInstance() {
#ifdef TOOLS_ENABLED
void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
-
placeholders.erase(p_placeholder);
}
#endif
#ifdef TOOLS_ENABLED
void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
-
if (base_cache.is_valid()) {
base_cache->_update_exports_values(values, propnames);
}
@@ -2370,7 +2330,6 @@ void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List
}
void CSharpScript::_update_member_info_no_exports() {
-
if (exports_invalidated) {
GD_MONO_ASSERT_THREAD_ATTACHED;
@@ -2419,60 +2378,71 @@ void CSharpScript::_update_member_info_no_exports() {
#endif
bool CSharpScript::_update_exports() {
-
#ifdef TOOLS_ENABLED
- if (!Engine::get_singleton()->is_editor_hint())
- return false;
-
- placeholder_fallback_enabled = true; // until proven otherwise
-
- if (!valid)
+ bool is_editor = Engine::get_singleton()->is_editor_hint();
+ if (is_editor) {
+ placeholder_fallback_enabled = true; // until proven otherwise
+ }
+#endif
+ if (!valid) {
return false;
+ }
bool changed = false;
- if (exports_invalidated) {
+#ifdef TOOLS_ENABLED
+ if (exports_invalidated)
+#endif
+ {
GD_MONO_SCOPE_THREAD_ATTACH;
- exports_invalidated = false;
-
changed = true;
member_info.clear();
- exported_members_cache.clear();
- exported_members_defval_cache.clear();
- // Here we create a temporary managed instance of the class to get the initial values
+#ifdef TOOLS_ENABLED
+ MonoObject *tmp_object = nullptr;
+ Object *tmp_native = nullptr;
+ uint32_t tmp_pinned_gchandle = 0;
- MonoObject *tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
+ if (is_editor) {
+ exports_invalidated = false;
- if (!tmp_object) {
- ERR_PRINT("Failed to allocate temporary MonoObject.");
- return false;
- }
+ exported_members_cache.clear();
+ exported_members_defval_cache.clear();
- uint32_t tmp_pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(tmp_object); // pin it (not sure if needed)
+ // Here we create a temporary managed instance of the class to get the initial values
+ tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
- GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
+ if (!tmp_object) {
+ ERR_PRINT("Failed to allocate temporary MonoObject.");
+ return false;
+ }
- ERR_FAIL_NULL_V_MSG(ctor, false,
- "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");
+ tmp_pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(tmp_object); // pin it (not sure if needed)
- MonoException *ctor_exc = nullptr;
- ctor->invoke(tmp_object, nullptr, &ctor_exc);
+ GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
- Object *tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));
+ ERR_FAIL_NULL_V_MSG(ctor, false,
+ "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");
- if (ctor_exc) {
- // TODO: Should we free 'tmp_native' if the exception was thrown after its creation?
+ MonoException *ctor_exc = nullptr;
+ ctor->invoke(tmp_object, nullptr, &ctor_exc);
- GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
- tmp_object = nullptr;
+ tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));
- ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
- GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
- return false;
+ if (ctor_exc) {
+ // TODO: Should we free 'tmp_native' if the exception was thrown after its creation?
+
+ GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
+ tmp_object = nullptr;
+
+ ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
+ GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
+ return false;
+ }
}
+#endif
GDMonoClass *top = script_class;
@@ -2488,15 +2458,22 @@ bool CSharpScript::_update_exports() {
if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
StringName member_name = field->get_name();
+ member_info[member_name] = prop_info;
+
if (exported) {
- member_info[member_name] = prop_info;
- exported_members_cache.push_front(prop_info);
+#ifdef TOOLS_ENABLED
+ if (is_editor) {
+ exported_members_cache.push_front(prop_info);
- if (tmp_object) {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
+ if (tmp_object) {
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
+ }
}
- } else {
- member_info[member_name] = prop_info;
+#endif
+
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ exported_members_names.insert(member_name);
+#endif
}
}
}
@@ -2509,22 +2486,28 @@ bool CSharpScript::_update_exports() {
if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
StringName member_name = property->get_name();
+ member_info[member_name] = prop_info;
+
if (exported) {
- member_info[member_name] = prop_info;
- exported_members_cache.push_front(prop_info);
-
- if (tmp_object) {
- MonoException *exc = nullptr;
- MonoObject *ret = property->get_value(tmp_object, &exc);
- if (exc) {
- exported_members_defval_cache[member_name] = Variant();
- GDMonoUtils::debug_print_unhandled_exception(exc);
- } else {
- exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
+#ifdef TOOLS_ENABLED
+ if (is_editor) {
+ exported_members_cache.push_front(prop_info);
+ if (tmp_object) {
+ MonoException *exc = nullptr;
+ MonoObject *ret = property->get_value(tmp_object, &exc);
+ if (exc) {
+ exported_members_defval_cache[member_name] = Variant();
+ GDMonoUtils::debug_print_unhandled_exception(exc);
+ } else {
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
+ }
}
}
- } else {
- member_info[member_name] = prop_info;
+#endif
+
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ exported_members_names.insert(member_name);
+#endif
}
}
}
@@ -2532,52 +2515,57 @@ bool CSharpScript::_update_exports() {
top = top->get_parent_class();
}
- // Need to check this here, before disposal
- bool base_ref = Object::cast_to<Reference>(tmp_native) != nullptr;
+#ifdef TOOLS_ENABLED
+ if (is_editor) {
+ // Need to check this here, before disposal
+ bool base_ref = Object::cast_to<Reference>(tmp_native) != nullptr;
- // Dispose the temporary managed instance
+ // Dispose the temporary managed instance
- MonoException *exc = nullptr;
- GDMonoUtils::dispose(tmp_object, &exc);
+ MonoException *exc = nullptr;
+ GDMonoUtils::dispose(tmp_object, &exc);
- if (exc) {
- ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
- GDMonoUtils::debug_print_unhandled_exception(exc);
- }
+ if (exc) {
+ ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
+ GDMonoUtils::debug_print_unhandled_exception(exc);
+ }
- GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
- tmp_object = nullptr;
+ GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
+ tmp_object = nullptr;
- if (tmp_native && !base_ref) {
- Node *node = Object::cast_to<Node>(tmp_native);
- if (node && node->is_inside_tree()) {
- ERR_PRINT("Temporary instance was added to the scene tree.");
- } else {
- memdelete(tmp_native);
+ if (tmp_native && !base_ref) {
+ Node *node = Object::cast_to<Node>(tmp_native);
+ if (node && node->is_inside_tree()) {
+ ERR_PRINT("Temporary instance was added to the scene tree.");
+ } else {
+ memdelete(tmp_native);
+ }
}
}
+#endif
}
- placeholder_fallback_enabled = false;
+#ifdef TOOLS_ENABLED
+ if (is_editor) {
+ placeholder_fallback_enabled = false;
- if (placeholders.size()) {
- // Update placeholders if any
- Map<StringName, Variant> values;
- List<PropertyInfo> propnames;
- _update_exports_values(values, propnames);
+ if (placeholders.size()) {
+ // Update placeholders if any
+ Map<StringName, Variant> values;
+ List<PropertyInfo> propnames;
+ _update_exports_values(values, propnames);
- for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
- E->get()->update(propnames, values);
+ for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
+ E->get()->update(propnames, values);
+ }
}
}
+#endif
return changed;
-#endif
- return false;
}
void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
-
// no need to load the script's signals more than once
if (!signals_invalidated) {
return;
@@ -2595,8 +2583,9 @@ void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_nati
for (int i = delegates.size() - 1; i >= 0; --i) {
GDMonoClass *delegate = delegates[i];
- if (!delegate->has_attribute(CACHED_CLASS(SignalAttribute)))
+ if (!delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
continue;
+ }
// Arguments are accessibles as arguments of .Invoke method
GDMonoMethod *invoke_method = delegate->get_method(mono_get_delegate_invoke(delegate->get_mono_ptr()));
@@ -2629,11 +2618,13 @@ void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_nati
GDMonoClass *field_class = field->get_type().type_class;
- if (!mono_class_is_delegate(field_class->get_mono_ptr()))
+ if (!mono_class_is_delegate(field_class->get_mono_ptr())) {
continue;
+ }
- if (!found_event_signals.find(field->get_name()))
+ if (!found_event_signals.find(field->get_name())) {
continue;
+ }
GDMonoMethod *invoke_method = field_class->get_method(mono_get_delegate_invoke(field_class->get_mono_ptr()));
@@ -2679,13 +2670,11 @@ bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_in
return true;
}
-#ifdef TOOLS_ENABLED
/**
* 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, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
-
GD_MONO_ASSERT_THREAD_ATTACHED;
// Goddammit, C++. All I wanted was some nested functions.
@@ -2693,13 +2682,17 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect
(m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())
if (p_member->is_static()) {
- if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
+#ifdef TOOLS_ENABLED
+ if (p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
ERR_PRINT("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+ }
+#endif
return false;
}
- if (member_info.has(p_member->get_name()))
+ if (member_info.has(p_member->get_name())) {
return false;
+ }
ManagedType type;
@@ -2716,13 +2709,19 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect
if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
if (!property->has_getter()) {
- if (exported)
- ERR_PRINT("Read-only property cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+#ifdef TOOLS_ENABLED
+ if (exported) {
+ ERR_PRINT("Cannot export a property without a getter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+ }
+#endif
return false;
}
if (!property->has_setter()) {
- if (exported)
- ERR_PRINT("Write-only property (without getter) cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+#ifdef TOOLS_ENABLED
+ if (exported) {
+ ERR_PRINT("Cannot export a property without a setter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+ }
+#endif
return false;
}
}
@@ -2736,16 +2735,21 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect
return true;
}
+#ifdef TOOLS_ENABLED
MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
+#endif
PropertyHint hint = PROPERTY_HINT_NONE;
String hint_string;
if (variant_type == Variant::NIL && !nil_is_variant) {
+#ifdef TOOLS_ENABLED
ERR_PRINT("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
+#endif
return false;
}
+#ifdef TOOLS_ENABLED
int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);
ERR_FAIL_COND_V_MSG(hint_res == -1, false,
@@ -2756,6 +2760,7 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect
hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
}
+#endif
uint32_t prop_usage = PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE;
@@ -2772,8 +2777,8 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect
#undef MEMBER_FULL_QUALIFIED_NAME
}
+#ifdef TOOLS_ENABLED
int CSharpScript::_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) {
-
if (p_variant_type == Variant::NIL) {
// System.Object (Variant)
return 1;
@@ -2844,8 +2849,9 @@ int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, Manage
ManagedType elem_type;
- if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type))
+ if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type)) {
return 0;
+ }
Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);
@@ -2872,18 +2878,7 @@ int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, Manage
}
#endif
-void CSharpScript::_clear() {
-
- tool = false;
- valid = false;
-
- base = nullptr;
- native = nullptr;
- script_class = nullptr;
-}
-
Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
if (unlikely(GDMono::get_singleton() == nullptr)) {
// Probably not the best error but eh.
r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
@@ -2915,18 +2910,11 @@ Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, i
}
void CSharpScript::_resource_path_changed() {
-
- String path = get_path();
-
- if (!path.empty()) {
- name = get_path().get_file().get_basename();
- }
+ _update_name();
}
bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
-
if (p_name == CSharpLanguage::singleton->string_names._script_source) {
-
r_ret = get_source_code();
return true;
}
@@ -2935,9 +2923,7 @@ bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
}
bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
-
if (p_name == CSharpLanguage::singleton->string_names._script_source) {
-
set_source_code(p_value);
reload();
return true;
@@ -2947,17 +2933,14 @@ bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
}
void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
-
p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
}
void CSharpScript::_bind_methods() {
-
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
}
Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
-
// This method should not fail, only assertions allowed
CRASH_COND(p_class == nullptr);
@@ -2971,7 +2954,6 @@ Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GD
}
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 == nullptr);
@@ -2982,12 +2964,24 @@ void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMon
CRASH_COND(p_script->native == nullptr);
+ p_script->valid = true;
+
+ update_script_class_info(p_script);
+
+#ifdef TOOLS_ENABLED
+ p_script->_update_member_info_no_exports();
+#endif
+}
+
+// Extract information about the script using the mono class.
+void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
GDMonoClass *base = p_script->script_class->get_parent_class();
- if (base != p_script->native)
+ // `base` should only be set if the script is a user defined type.
+ if (base != p_script->native) {
p_script->base = base;
+ }
- p_script->valid = true;
p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
if (!p_script->tool) {
@@ -2995,7 +2989,7 @@ void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMon
p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
}
-#if TOOLS_ENABLED
+#ifdef TOOLS_ENABLED
if (!p_script->tool) {
p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
}
@@ -3011,8 +3005,9 @@ void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMon
while (native_top) {
native_top->fetch_methods_with_godot_api_checks(p_script->native);
- if (native_top == CACHED_CLASS(GodotObject))
+ if (native_top == CACHED_CLASS(GodotObject)) {
break;
+ }
native_top = native_top->get_parent_class();
}
@@ -3021,21 +3016,77 @@ void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMon
p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);
- // Need to fetch method from base classes as well
+ p_script->rpc_functions.clear();
+ p_script->rpc_variables.clear();
+
GDMonoClass *top = p_script->script_class;
while (top && top != p_script->native) {
+ // Fetch methods from base classes as well
top->fetch_methods_with_godot_api_checks(p_script->native);
+
+ // Update RPC info
+ {
+ Vector<GDMonoMethod *> methods = top->get_all_methods();
+ for (int i = 0; i < methods.size(); i++) {
+ if (!methods[i]->is_static()) {
+ MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(methods[i]);
+ if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
+ ScriptNetData nd;
+ nd.name = methods[i]->get_name();
+ nd.mode = mode;
+ if (-1 == p_script->rpc_functions.find(nd)) {
+ p_script->rpc_functions.push_back(nd);
+ }
+ }
+ }
+ }
+ }
+
+ {
+ Vector<GDMonoField *> fields = top->get_all_fields();
+ for (int i = 0; i < fields.size(); i++) {
+ if (!fields[i]->is_static()) {
+ MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(fields[i]);
+ if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
+ ScriptNetData nd;
+ nd.name = fields[i]->get_name();
+ nd.mode = mode;
+ if (-1 == p_script->rpc_variables.find(nd)) {
+ p_script->rpc_variables.push_back(nd);
+ }
+ }
+ }
+ }
+ }
+
+ {
+ Vector<GDMonoProperty *> properties = top->get_all_properties();
+ for (int i = 0; i < properties.size(); i++) {
+ if (!properties[i]->is_static()) {
+ MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(properties[i]);
+ if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
+ ScriptNetData nd;
+ nd.name = properties[i]->get_name();
+ nd.mode = mode;
+ if (-1 == p_script->rpc_variables.find(nd)) {
+ p_script->rpc_variables.push_back(nd);
+ }
+ }
+ }
+ }
+ }
+
top = top->get_parent_class();
}
+ // Sort so we are 100% that they are always the same.
+ p_script->rpc_functions.sort_custom<SortNetData>();
+ p_script->rpc_variables.sort_custom<SortNetData>();
+
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 {
-
#ifdef TOOLS_ENABLED
bool extra_cond = tool || ScriptServer::is_scripting_enabled();
#else
@@ -3059,15 +3110,14 @@ bool CSharpScript::can_instance() const {
}
StringName CSharpScript::get_instance_base_type() const {
-
- if (native)
+ if (native) {
return native->get_name();
- else
+ } else {
return StringName();
+ }
}
CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) {
-
GD_MONO_ASSERT_THREAD_ATTACHED;
/* STEP 1, CREATE */
@@ -3078,7 +3128,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
ERR_FAIL_COND_V_MSG(p_argcount == 0, nullptr,
"Cannot create script instance. The class '" + script_class->get_full_name() +
"' does not define a parameterless constructor." +
- (get_path().empty() ? String() : " Path: '" + get_path() + "'."));
+ (get_path().is_empty() ? String() : " Path: '" + get_path() + "'."));
ERR_FAIL_V_MSG(nullptr, "Constructor not found.");
}
@@ -3127,7 +3177,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
bool die = instance->_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);
+ CRASH_COND(die);
p_owner->set_script_instance(nullptr);
r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
@@ -3137,8 +3187,9 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
// Tie managed to unmanaged
instance->gchandle = MonoGCHandleData::new_strong_handle(mono_object);
- if (instance->base_ref)
+ if (instance->base_ref) {
instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
+ }
{
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
@@ -3157,7 +3208,6 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
}
Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
if (!valid) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
@@ -3193,7 +3243,6 @@ Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::Cal
}
ScriptInstance *CSharpScript::instance_create(Object *p_this) {
-
#ifdef DEBUG_ENABLED
CRASH_COND(!valid);
#endif
@@ -3218,7 +3267,6 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) {
}
PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
-
#ifdef TOOLS_ENABLED
PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
placeholders.insert(si);
@@ -3230,25 +3278,22 @@ PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_t
}
bool CSharpScript::instance_has(const Object *p_this) const {
-
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
return instances.has((Object *)p_this);
}
bool CSharpScript::has_source_code() const {
-
- return !source.empty();
+ return !source.is_empty();
}
String CSharpScript::get_source_code() const {
-
return source;
}
void CSharpScript::set_source_code(const String &p_code) {
-
- if (source == p_code)
+ if (source == p_code) {
return;
+ }
source = p_code;
#ifdef TOOLS_ENABLED
source_changed_cache = true;
@@ -3256,9 +3301,9 @@ void CSharpScript::set_source_code(const String &p_code) {
}
void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
-
- if (!script_class)
+ if (!script_class) {
return;
+ }
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -3270,9 +3315,9 @@ void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
}
bool CSharpScript::has_method(const StringName &p_method) const {
-
- if (!script_class)
+ if (!script_class) {
return false;
+ }
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -3280,9 +3325,9 @@ bool CSharpScript::has_method(const StringName &p_method) const {
}
MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
-
- if (!script_class)
+ if (!script_class) {
return MethodInfo();
+ }
GD_MONO_SCOPE_THREAD_ATTACH;
@@ -3301,7 +3346,6 @@ MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
}
Error CSharpScript::reload(bool p_keep_state) {
-
bool has_instances;
{
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
@@ -3323,9 +3367,7 @@ Error CSharpScript::reload(bool p_keep_state) {
ERR_FAIL_NULL_V(namespace_, ERR_BUG);
ERR_FAIL_NULL_V(class_name, ERR_BUG);
GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
- if (klass) {
- bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(klass);
- ERR_FAIL_COND_V(!obj_type, ERR_BUG);
+ if (klass && CACHED_CLASS(GodotObject)->is_assignable_from(klass)) {
script_class = klass;
}
} else {
@@ -3340,122 +3382,15 @@ Error CSharpScript::reload(bool p_keep_state) {
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 == nullptr);
- GDMonoClass *base_class = script_class->get_parent_class();
-
- if (base_class != native)
- base = base_class;
-
-#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_class != native) {
- GDMonoClass *native_top = native;
- while (native_top) {
- native_top->fetch_methods_with_godot_api_checks(native);
+ update_script_class_info(this);
- if (native_top == CACHED_CLASS(GodotObject))
- break;
-
- native_top = native_top->get_parent_class();
- }
- }
-#endif
-
- script_class->fetch_methods_with_godot_api_checks(native);
-
- // Need to fetch method from base classes as well
- GDMonoClass *top = script_class;
- while (top && top != native) {
- top->fetch_methods_with_godot_api_checks(native);
- top = top->get_parent_class();
- }
-
- load_script_signals(script_class, native);
_update_exports();
}
- rpc_functions.clear();
- rpc_variables.clear();
-
- GDMonoClass *top = script_class;
- while (top && top != native) {
- {
- Vector<GDMonoMethod *> methods = top->get_all_methods();
- for (int i = 0; i < methods.size(); i++) {
- if (!methods[i]->is_static()) {
- MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(methods[i]);
- if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
- ScriptNetData nd;
- nd.name = methods[i]->get_name();
- nd.mode = mode;
- if (-1 == rpc_functions.find(nd)) {
- rpc_functions.push_back(nd);
- }
- }
- }
- }
- }
-
- {
- Vector<GDMonoField *> fields = top->get_all_fields();
- for (int i = 0; i < fields.size(); i++) {
- if (!fields[i]->is_static()) {
- MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(fields[i]);
- if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
- ScriptNetData nd;
- nd.name = fields[i]->get_name();
- nd.mode = mode;
- if (-1 == rpc_variables.find(nd)) {
- rpc_variables.push_back(nd);
- }
- }
- }
- }
- }
-
- {
- Vector<GDMonoProperty *> properties = top->get_all_properties();
- for (int i = 0; i < properties.size(); i++) {
- if (!properties[i]->is_static()) {
- MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(properties[i]);
- if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
- ScriptNetData nd;
- nd.name = properties[i]->get_name();
- nd.mode = mode;
- if (-1 == rpc_variables.find(nd)) {
- rpc_variables.push_back(nd);
- }
- }
- }
- }
- }
-
- top = top->get_parent_class();
- }
-
- // Sort so we are 100% that they are always the same.
- rpc_functions.sort_custom<SortNetData>();
- rpc_variables.sort_custom<SortNetData>();
-
return OK;
}
@@ -3463,12 +3398,10 @@ Error CSharpScript::reload(bool p_keep_state) {
}
ScriptLanguage *CSharpScript::get_language() const {
-
return CSharpLanguage::get_singleton();
}
bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
-
#ifdef TOOLS_ENABLED
const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
@@ -3486,7 +3419,6 @@ bool CSharpScript::get_property_default_value(const StringName &p_property, Vari
}
void CSharpScript::update_exports() {
-
#ifdef TOOLS_ENABLED
_update_exports();
#endif
@@ -3497,7 +3429,6 @@ bool CSharpScript::has_script_signal(const StringName &p_signal) const {
}
void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
-
for (const Map<StringName, Vector<SignalParameter>>::Element *E = _signals.front(); E; E = E->next()) {
MethodInfo mi;
mi.name = E->key();
@@ -3507,8 +3438,9 @@ void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
const SignalParameter &param = params[i];
PropertyInfo arg_info = PropertyInfo(param.type, param.name);
- if (param.type == Variant::NIL && param.nil_is_variant)
+ if (param.type == Variant::NIL && param.nil_is_variant) {
arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
mi.arguments.push_back(arg_info);
}
@@ -3526,8 +3458,9 @@ void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
const SignalParameter &param = params[i];
PropertyInfo arg_info = PropertyInfo(param.type, param.name);
- if (param.type == Variant::NIL && param.nil_is_variant)
+ if (param.type == Variant::NIL && param.nil_is_variant) {
arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
mi.arguments.push_back(arg_info);
}
@@ -3542,45 +3475,52 @@ bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
return false;
}
-#ifndef _MSC_VER
-#warning TODO: Implement CSharpScript::inherits_script and other relevant changes after GH-38063.
-#endif
- return false;
+ if (script_class == nullptr || cs->script_class == nullptr) {
+ return false;
+ }
+
+ if (script_class == cs->script_class) {
+ return true;
+ }
+
+ return cs->script_class->is_assignable_from(script_class);
}
Ref<Script> CSharpScript::get_base_script() const {
-
// TODO search in metadata file once we have it, not important any way?
return Ref<Script>();
}
void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
-
for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
p_list->push_back(E->value());
}
}
int CSharpScript::get_member_line(const StringName &p_member) const {
-
// TODO omnisharp
return -1;
}
MultiplayerAPI::RPCMode CSharpScript::_member_get_rpc_mode(IMonoClassMember *p_member) const {
-
- if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
+ if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute))) {
return MultiplayerAPI::RPC_MODE_REMOTE;
- if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
+ }
+ if (p_member->has_attribute(CACHED_CLASS(MasterAttribute))) {
return MultiplayerAPI::RPC_MODE_MASTER;
- if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
+ }
+ if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute))) {
return MultiplayerAPI::RPC_MODE_PUPPET;
- if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
+ }
+ if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute))) {
return MultiplayerAPI::RPC_MODE_REMOTESYNC;
- if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
+ }
+ if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute))) {
return MultiplayerAPI::RPC_MODE_MASTERSYNC;
- if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
+ }
+ if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute))) {
return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
+ }
return MultiplayerAPI::RPC_MODE_DISABLED;
}
@@ -3640,14 +3580,13 @@ MultiplayerAPI::RPCMode CSharpScript::get_rset_mode(const StringName &p_variable
}
Error CSharpScript::load_source_code(const String &p_path) {
-
Error ferr = read_all_file_utf8(p_path, source);
ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
ferr == ERR_INVALID_DATA ?
- "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
+ "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
" Please ensure that scripts are saved in valid UTF-8 unicode." :
- "Failed to read file: '" + p_path + "'.");
+ "Failed to read file: '" + p_path + "'.");
#ifdef TOOLS_ENABLED
source_changed_cache = true;
@@ -3656,16 +3595,27 @@ Error CSharpScript::load_source_code(const String &p_path) {
return OK;
}
-StringName CSharpScript::get_script_name() const {
+void CSharpScript::_update_name() {
+ String path = get_path();
- return name;
+ if (!path.is_empty()) {
+ name = get_path().get_file().get_basename();
+ }
}
-CSharpScript::CSharpScript() {
+void CSharpScript::_clear() {
+ tool = false;
+ valid = false;
+
+ base = nullptr;
+ native = nullptr;
+ script_class = nullptr;
+}
+CSharpScript::CSharpScript() {
_clear();
- _resource_path_changed();
+ _update_name();
#ifdef DEBUG_ENABLED
{
@@ -3676,19 +3626,28 @@ CSharpScript::CSharpScript() {
}
CSharpScript::~CSharpScript() {
-
#ifdef DEBUG_ENABLED
MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
#endif
}
+void CSharpScript::get_members(Set<StringName> *p_members) {
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ if (p_members) {
+ for (Set<StringName>::Element *E = exported_members_names.front(); E; E = E->next()) {
+ p_members->insert(E->get());
+ }
+ }
+#endif
+}
+
/*************** RESOURCE ***************/
RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CANT_OPEN;
+ }
// TODO ignore anything inside bin/ and obj/ in tools builds?
@@ -3705,29 +3664,26 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p
script->reload();
- if (r_error)
+ if (r_error) {
*r_error = OK;
+ }
return scriptres;
}
void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("cs");
}
bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
-
return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
}
String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
-
return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
}
Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
-
Ref<CSharpScript> sqscr = p_resource;
ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
@@ -3735,13 +3691,9 @@ Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_r
#ifdef TOOLS_ENABLED
if (!FileAccess::exists(p_path)) {
- // The file does not yet exists, let's assume the user just created this script
-
- if (_create_project_solution_if_needed()) {
- CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
- "Compile",
- ProjectSettings::get_singleton()->globalize_path(p_path));
- } else {
+ // The file does not yet exist, let's assume the user just created this script. In such
+ // cases we need to check whether the solution and csproj were already created or not.
+ if (!_create_project_solution_if_needed()) {
ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
}
}
@@ -3771,19 +3723,16 @@ Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_r
}
void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
-
if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
p_extensions->push_back("cs");
}
}
bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
-
return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
}
CSharpLanguage::StringNameCache::StringNameCache() {
-
_signal_callback = StaticCString::create("_signal_callback");
_set = StaticCString::create("_set");
_get = StaticCString::create("_get");
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index 05e2857538..85edd8b9c6 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,10 +31,11 @@
#ifndef CSHARP_SCRIPT_H
#define CSHARP_SCRIPT_H
+#include "core/doc_data.h"
#include "core/io/resource_loader.h"
#include "core/io/resource_saver.h"
-#include "core/script_language.h"
-#include "core/self_list.h"
+#include "core/object/script_language.h"
+#include "core/templates/self_list.h"
#include "mono_gc_handle.h"
#include "mono_gd/gd_mono.h"
@@ -66,7 +67,6 @@ TScriptInstance *cast_script_instance(ScriptInstance *p_inst) {
#define CAST_CSHARP_INSTANCE(m_inst) (cast_script_instance<CSharpInstance, CSharpLanguage>(m_inst))
class CSharpScript : public Script {
-
GDCLASS(CSharpScript, Script);
public:
@@ -136,19 +136,26 @@ private:
bool exports_invalidated = true;
void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames);
void _update_member_info_no_exports();
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
+ void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
+#endif
+
+#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
+ Set<StringName> exported_members_names;
#endif
Map<StringName, PropertyInfo> member_info;
void _clear();
+ void _update_name();
+
void load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class);
bool _get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_invoke, Vector<SignalParameter> &params);
bool _update_exports();
-#ifdef TOOLS_ENABLED
+
bool _get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported);
+#ifdef TOOLS_ENABLED
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
@@ -158,6 +165,7 @@ private:
// 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 update_script_class_info(Ref<CSharpScript> p_script);
static void initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native);
MultiplayerAPI::RPCMode _member_get_rpc_mode(IMonoClassMember *p_member) const;
@@ -165,72 +173,79 @@ private:
protected:
static void _bind_methods();
- Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- virtual void _resource_path_changed();
+ Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
+ void _resource_path_changed() override;
bool _get(const StringName &p_name, Variant &r_ret) const;
bool _set(const StringName &p_name, const Variant &p_value);
void _get_property_list(List<PropertyInfo> *p_properties) const;
public:
- virtual bool can_instance() const;
- virtual StringName get_instance_base_type() const;
- virtual ScriptInstance *instance_create(Object *p_this);
- virtual PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this);
- virtual bool instance_has(const Object *p_this) const;
+ bool can_instance() const override;
+ StringName get_instance_base_type() const override;
+ ScriptInstance *instance_create(Object *p_this) override;
+ PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override;
+ bool instance_has(const Object *p_this) const override;
+
+ bool has_source_code() const override;
+ String get_source_code() const override;
+ void set_source_code(const String &p_code) override;
+
+#ifdef TOOLS_ENABLED
+ virtual const Vector<DocData::ClassDoc> &get_documentation() const override {
+ // TODO
+ static Vector<DocData::ClassDoc> docs;
+ return docs;
+ }
+#endif // TOOLS_ENABLED
- virtual bool has_source_code() const;
- virtual String get_source_code() const;
- virtual void set_source_code(const String &p_code);
+ Error reload(bool p_keep_state = false) override;
- virtual Error reload(bool p_keep_state = false);
+ bool has_script_signal(const StringName &p_signal) const override;
+ void get_script_signal_list(List<MethodInfo> *r_signals) const override;
- virtual bool has_script_signal(const StringName &p_signal) const;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
+ bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
+ void get_script_property_list(List<PropertyInfo> *p_list) const override;
+ void update_exports() override;
- virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const;
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
- virtual void update_exports();
+ void get_members(Set<StringName> *p_members) override;
- virtual bool is_tool() const { return tool; }
- virtual bool is_valid() const { return valid; }
+ bool is_tool() const override { return tool; }
+ bool is_valid() const override { return valid; }
- bool inherits_script(const Ref<Script> &p_script) const;
+ bool inherits_script(const Ref<Script> &p_script) const override;
- virtual Ref<Script> get_base_script() const;
- virtual ScriptLanguage *get_language() const;
+ Ref<Script> get_base_script() const override;
+ ScriptLanguage *get_language() const override;
- virtual void get_script_method_list(List<MethodInfo> *p_list) const;
- bool has_method(const StringName &p_method) const;
- MethodInfo get_method_info(const StringName &p_method) const;
+ void get_script_method_list(List<MethodInfo> *p_list) const override;
+ bool has_method(const StringName &p_method) const override;
+ MethodInfo get_method_info(const StringName &p_method) const override;
- virtual int get_member_line(const StringName &p_member) const;
+ int get_member_line(const StringName &p_member) const override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ Vector<ScriptNetData> get_rpc_methods() const override;
+ uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ StringName get_rpc_method(const uint16_t p_rpc_method_id) const override;
+ MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_variable) const;
- virtual StringName get_rset_property(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ Vector<ScriptNetData> get_rset_properties() const override;
+ uint16_t get_rset_property_id(const StringName &p_variable) const override;
+ StringName get_rset_property(const uint16_t p_variable_id) const override;
+ MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override;
+ MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
#ifdef TOOLS_ENABLED
- virtual bool is_placeholder_fallback_enabled() const { return placeholder_fallback_enabled; }
+ bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; }
#endif
Error load_source_code(const String &p_path);
- StringName get_script_name() const;
-
CSharpScript();
~CSharpScript();
};
class CSharpInstance : public ScriptInstance {
-
friend class CSharpScript;
friend class CSharpLanguage;
@@ -244,8 +259,6 @@ class CSharpInstance : public ScriptInstance {
Ref<CSharpScript> script;
MonoGCHandleData gchandle;
- Vector<Callable> event_signal_callables;
-
bool _reference_owner_unsafe();
/*
@@ -262,8 +275,6 @@ class CSharpInstance : public ScriptInstance {
friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *);
static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle);
- void _call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount);
-
void get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state);
void get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state);
@@ -272,23 +283,21 @@ public:
_FORCE_INLINE_ bool is_destructing_script_instance() { return destructing_script_instance; }
- virtual Object *get_owner();
+ Object *get_owner() override;
- virtual bool set(const StringName &p_name, const Variant &p_value);
- virtual bool get(const StringName &p_name, Variant &r_ret) const;
- virtual void get_property_list(List<PropertyInfo> *p_properties) const;
- virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const;
+ bool set(const StringName &p_name, const Variant &p_value) override;
+ bool get(const StringName &p_name, Variant &r_ret) const override;
+ void get_property_list(List<PropertyInfo> *p_properties) const override;
+ Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override;
- /* TODO */ virtual void get_method_list(List<MethodInfo> *p_list) const {}
- virtual bool has_method(const StringName &p_method) const;
- virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error);
- virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount);
- virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount);
+ /* TODO */ void get_method_list(List<MethodInfo> *p_list) const override {}
+ bool has_method(const StringName &p_method) const override;
+ Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override;
void mono_object_disposed(MonoObject *p_obj);
/*
- * If 'r_delete_owner' is set to true, the caller must memdelete the script instance's owner. Otherwise, ifevent_signal
+ * If 'r_delete_owner' is set to true, the caller must memdelete the script instance's owner. Otherwise, if
* 'r_remove_script_instance' is set to true, the caller must destroy the script instance by removing it from its owner.
*/
void mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance);
@@ -296,46 +305,42 @@ public:
void connect_event_signals();
void disconnect_event_signals();
- virtual void refcount_incremented();
- virtual bool refcount_decremented();
+ void refcount_incremented() override;
+ bool refcount_decremented() override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ Vector<ScriptNetData> get_rpc_methods() const override;
+ uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ StringName get_rpc_method(const uint16_t p_rpc_method_id) const override;
+ MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_variable) const;
- virtual StringName get_rset_property(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ Vector<ScriptNetData> get_rset_properties() const override;
+ uint16_t get_rset_property_id(const StringName &p_variable) const override;
+ StringName get_rset_property(const uint16_t p_variable_id) const override;
+ MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override;
+ MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
- virtual void notification(int p_notification);
+ void notification(int p_notification) override;
void _call_notification(int p_notification);
- virtual String to_string(bool *r_valid);
+ String to_string(bool *r_valid) override;
- virtual Ref<Script> get_script() const;
+ Ref<Script> get_script() const override;
- virtual ScriptLanguage *get_language();
+ ScriptLanguage *get_language() override;
CSharpInstance(const Ref<CSharpScript> &p_script);
~CSharpInstance();
};
struct CSharpScriptBinding {
- bool inited;
+ bool inited = false;
StringName type_name;
- GDMonoClass *wrapper_class;
+ GDMonoClass *wrapper_class = nullptr;
MonoGCHandleData gchandle;
- Object *owner;
+ Object *owner = nullptr;
- CSharpScriptBinding() :
- inited(false),
- wrapper_class(nullptr),
- owner(nullptr) {
- }
+ CSharpScriptBinding() {}
};
class ManagedCallableMiddleman : public Object {
@@ -343,7 +348,6 @@ class ManagedCallableMiddleman : public Object {
};
class CSharpLanguage : public ScriptLanguage {
-
friend class CSharpScript;
friend class CSharpInstance;
@@ -370,7 +374,6 @@ class CSharpLanguage : public ScriptLanguage {
ManagedCallableMiddleman *managed_callable_middleman = memnew(ManagedCallableMiddleman);
struct StringNameCache {
-
StringName _signal_callback;
StringName _set;
StringName _get;
@@ -438,83 +441,90 @@ public:
}
_FORCE_INLINE_ const Dictionary &get_scripts_metadata() {
- if (scripts_metadata_invalidated)
+ if (scripts_metadata_invalidated) {
_load_scripts_metadata();
+ }
return scripts_metadata;
}
_FORCE_INLINE_ ManagedCallableMiddleman *get_managed_callable_middleman() const { return managed_callable_middleman; }
- virtual String get_name() const;
+ String get_name() const override;
/* LANGUAGE FUNCTIONS */
- virtual String get_type() const;
- virtual String get_extension() const;
- virtual Error execute_file(const String &p_path);
- virtual void init();
- virtual void finish();
+ String get_type() const override;
+ String get_extension() const override;
+ Error execute_file(const String &p_path) override;
+ void init() override;
+ void finish() override;
+
+ void finalize();
/* EDITOR FUNCTIONS */
- virtual void get_reserved_words(List<String> *p_words) const;
- virtual void get_comment_delimiters(List<String> *p_delimiters) const;
- virtual void get_string_delimiters(List<String> *p_delimiters) const;
- virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const;
- virtual bool is_using_templates();
- virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script);
- /* TODO */ virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const { return true; }
- virtual String validate_path(const String &p_path) const;
- virtual Script *create_script() const;
- virtual bool has_named_classes() const;
- 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 PackedStringArray &p_args) const;
+ void get_reserved_words(List<String> *p_words) const override;
+ void get_comment_delimiters(List<String> *p_delimiters) const override;
+ void get_string_delimiters(List<String> *p_delimiters) const override;
+ Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const override;
+ bool is_using_templates() override;
+ void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) override;
+ /* TODO */ bool validate(const String &p_script, int &r_line_error, int &r_col_error,
+ String &r_test_error, const String &p_path, List<String> *r_functions,
+ List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const override {
+ return true;
+ }
+ String validate_path(const String &p_path) const override;
+ Script *create_script() const override;
+ bool has_named_classes() const override;
+ bool supports_builtin_mode() const override;
+ /* TODO? */ int find_function(const String &p_function, const String &p_code) const override { return -1; }
+ String make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const override;
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) {}
+ /* TODO? */ void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const override {}
+ /* TODO */ void add_global_constant(const StringName &p_variable, const Variant &p_value) override {}
/* DEBUGGER FUNCTIONS */
- virtual String debug_get_error() const;
- virtual int debug_get_stack_level_count() const;
- virtual int debug_get_stack_level_line(int p_level) const;
- virtual String debug_get_stack_level_function(int p_level) const;
- virtual String debug_get_stack_level_source(int p_level) const;
- /* TODO */ virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {}
- /* TODO */ virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {}
- /* TODO */ virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {}
- /* TODO */ virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { return ""; }
- virtual Vector<StackInfo> debug_get_current_stack_info();
+ String debug_get_error() const override;
+ int debug_get_stack_level_count() const override;
+ int debug_get_stack_level_line(int p_level) const override;
+ String debug_get_stack_level_function(int p_level) const override;
+ String debug_get_stack_level_source(int p_level) const override;
+ /* TODO */ void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
+ /* TODO */ void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
+ /* TODO */ void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) override {}
+ /* TODO */ String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) override { return ""; }
+ Vector<StackInfo> debug_get_current_stack_info() override;
/* PROFILING FUNCTIONS */
- /* TODO */ virtual void profiling_start() {}
- /* TODO */ virtual void profiling_stop() {}
- /* TODO */ virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { return 0; }
- /* TODO */ virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { return 0; }
+ /* TODO */ void profiling_start() override {}
+ /* TODO */ void profiling_stop() override {}
+ /* TODO */ int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) override { return 0; }
+ /* TODO */ int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) override { return 0; }
- virtual void frame();
+ void frame() override;
- /* TODO? */ virtual void get_public_functions(List<MethodInfo> *p_functions) const {}
- /* TODO? */ virtual void get_public_constants(List<Pair<String, Variant>> *p_constants) const {}
+ /* TODO? */ void get_public_functions(List<MethodInfo> *p_functions) const override {}
+ /* TODO? */ void get_public_constants(List<Pair<String, Variant>> *p_constants) const override {}
- virtual void reload_all_scripts();
- virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload);
+ void reload_all_scripts() override;
+ void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) override;
/* LOADER FUNCTIONS */
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
+ void get_recognized_extensions(List<String> *p_extensions) const override;
#ifdef TOOLS_ENABLED
- virtual Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col);
- virtual bool overrides_external_editor();
+ Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) override;
+ bool overrides_external_editor() override;
#endif
/* THREAD ATTACHING */
- virtual void thread_enter();
- virtual void thread_exit();
+ void thread_enter() override;
+ void thread_exit() override;
// Don't use these. I'm watching you
- virtual void *alloc_instance_binding_data(Object *p_object);
- virtual void free_instance_binding_data(void *p_data);
- virtual void refcount_incremented_instance_binding(Object *p_object);
- virtual bool refcount_decremented_instance_binding(Object *p_object);
+ void *alloc_instance_binding_data(Object *p_object) override;
+ void free_instance_binding_data(void *p_data) override;
+ void refcount_incremented_instance_binding(Object *p_object) override;
+ bool refcount_decremented_instance_binding(Object *p_object) override;
Map<Object *, CSharpScriptBinding>::Element *insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding);
bool setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object);
@@ -532,17 +542,17 @@ public:
class ResourceFormatLoaderCSharpScript : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, bool p_no_cache = false);
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String &p_type) const;
- virtual String get_resource_type(const String &p_path) const;
+ RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, bool p_no_cache = false) override;
+ void get_recognized_extensions(List<String> *p_extensions) const override;
+ bool handles_type(const String &p_type) const override;
+ String get_resource_type(const String &p_path) const override;
};
class ResourceFormatSaverCSharpScript : public 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;
- virtual bool recognize(const RES &p_resource) const;
+ Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0) override;
+ void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const override;
+ bool recognize(const RES &p_resource) const override;
};
#endif // CSHARP_SCRIPT_H
diff --git a/modules/mono/doc_classes/@C#.xml b/modules/mono/doc_classes/@C#.xml
deleted file mode 100644
index 83a7fbf02c..0000000000
--- a/modules/mono/doc_classes/@C#.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="@C#" version="4.0">
- <brief_description>
- </brief_description>
- <description>
- </description>
- <tutorials>
- </tutorials>
- <methods>
- </methods>
- <constants>
- </constants>
-</class>
diff --git a/modules/mono/doc_classes/CSharpScript.xml b/modules/mono/doc_classes/CSharpScript.xml
index 1eb3404f9e..45a6f991bf 100644
--- a/modules/mono/doc_classes/CSharpScript.xml
+++ b/modules/mono/doc_classes/CSharpScript.xml
@@ -1,16 +1,21 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="CSharpScript" inherits="Script" version="4.0">
<brief_description>
+ A script implemented in the C# programming language (Mono-enabled builds only).
</brief_description>
<description>
+ This class represents a C# script. It is the C# equivalent of the [GDScript] class and is only available in Mono-enabled Godot builds.
+ See also [GodotSharp].
</description>
<tutorials>
+ <link title="C# tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/c_sharp/index.html</link>
</tutorials>
<methods>
<method name="new" qualifiers="vararg">
<return type="Variant">
</return>
<description>
+ Returns a new instance of the script.
</description>
</method>
</methods>
diff --git a/modules/mono/doc_classes/GodotSharp.xml b/modules/mono/doc_classes/GodotSharp.xml
index 19a08d2036..417f8ac704 100644
--- a/modules/mono/doc_classes/GodotSharp.xml
+++ b/modules/mono/doc_classes/GodotSharp.xml
@@ -1,8 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="GodotSharp" inherits="Object" version="4.0">
<brief_description>
+ Bridge between Godot and the Mono runtime (Mono-enabled builds only).
</brief_description>
<description>
+ This class is a bridge between Godot and the Mono runtime. It exposes several low-level operations and is only available in Mono-enabled Godot builds.
+ See also [CSharpScript].
</description>
<tutorials>
</tutorials>
@@ -11,26 +14,30 @@
<return type="void">
</return>
<description>
- Attaches the current thread to the mono runtime.
+ Attaches the current thread to the Mono runtime.
</description>
</method>
<method name="detach_thread">
<return type="void">
</return>
<description>
- Detaches the current thread from the mono runtime.
+ Detaches the current thread from the Mono runtime.
</description>
</method>
<method name="get_domain_id">
<return type="int">
</return>
<description>
+ Returns the current MonoDomain ID.
+ [b]Note:[/b] The Mono runtime must be initialized for this method to work (use [method is_runtime_initialized] to check). If the Mono runtime isn't initialized at the time this method is called, the engine will crash.
</description>
</method>
<method name="get_scripts_domain_id">
<return type="int">
</return>
<description>
+ Returns the scripts MonoDomain's ID. This will be the same MonoDomain ID as [method get_domain_id], unless the scripts domain isn't loaded.
+ [b]Note:[/b] The Mono runtime must be initialized for this method to work (use [method is_runtime_initialized] to check). If the Mono runtime isn't initialized at the time this method is called, the engine will crash.
</description>
</method>
<method name="is_domain_finalizing_for_unload">
@@ -39,26 +46,28 @@
<argument index="0" name="domain_id" type="int">
</argument>
<description>
- Returns whether the domain is being finalized.
+ Returns [code]true[/code] if the domain is being finalized, [code]false[/code] otherwise.
</description>
</method>
<method name="is_runtime_initialized">
<return type="bool">
</return>
<description>
+ Returns [code]true[/code] if the Mono runtime is initialized, [code]false[/code] otherwise.
</description>
</method>
<method name="is_runtime_shutting_down">
<return type="bool">
</return>
<description>
+ Returns [code]true[/code] if the Mono runtime is shutting down, [code]false[/code] otherwise.
</description>
</method>
<method name="is_scripts_domain_loaded">
<return type="bool">
</return>
<description>
- Returns whether the scripts domain is loaded.
+ Returns [code]true[/code] if the scripts domain is loaded, [code]false[/code] otherwise.
</description>
</method>
</methods>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
new file mode 100644
index 0000000000..56c0cb7703
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk.sln
@@ -0,0 +1,16 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Godot.NET.Sdk", "Godot.NET.Sdk\Godot.NET.Sdk.csproj", "{31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {31B00BFA-DEA1-42FA-A472-9E54A92A8A5F}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj
new file mode 100644
index 0000000000..8304d9e321
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.csproj
@@ -0,0 +1,50 @@
+<Project Sdk="Microsoft.Build.NoTargets/2.0.1">
+ <PropertyGroup>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+
+ <Description>MSBuild .NET Sdk for Godot projects.</Description>
+ <Authors>Godot Engine contributors</Authors>
+
+ <PackageId>Godot.NET.Sdk</PackageId>
+ <Version>4.0.0</Version>
+ <PackageProjectUrl>https://github.com/godotengine/godot/tree/master/modules/mono/editor/Godot.NET.Sdk</PackageProjectUrl>
+ <PackageType>MSBuildSdk</PackageType>
+ <PackageTags>MSBuildSdk</PackageTags>
+ <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <NuspecFile>Godot.NET.Sdk.nuspec</NuspecFile>
+ <GenerateNuspecDependsOn>$(GenerateNuspecDependsOn);SetNuSpecProperties</GenerateNuspecDependsOn>
+ </PropertyGroup>
+
+ <Target Name="ReadGodotNETSdkVersion" BeforeTargets="BeforeBuild;BeforeRebuild;CoreCompile">
+ <PropertyGroup>
+ <PackageVersion>$([System.IO.File]::ReadAllText('$(ProjectDir)Godot.NET.Sdk_PackageVersion.txt').Trim())</PackageVersion>
+ </PropertyGroup>
+ </Target>
+
+ <Target Name="SetNuSpecProperties" Condition=" Exists('$(NuspecFile)') " DependsOnTargets="ReadGodotNETSdkVersion">
+ <PropertyGroup>
+ <NuspecProperties>
+ id=$(PackageId);
+ description=$(Description);
+ authors=$(Authors);
+ version=$(PackageVersion);
+ packagetype=$(PackageType);
+ tags=$(PackageTags);
+ projecturl=$(PackageProjectUrl)
+ </NuspecProperties>
+ </PropertyGroup>
+ </Target>
+
+ <Target Name="CopyNupkgToSConsOutputDir" AfterTargets="Pack">
+ <PropertyGroup>
+ <GodotSourceRootPath>$(SolutionDir)\..\..\..\..\</GodotSourceRootPath>
+ <GodotOutputDataDir>$(GodotSourceRootPath)\bin\GodotSharp\</GodotOutputDataDir>
+ </PropertyGroup>
+ <Copy SourceFiles="$(OutputPath)$(PackageId).$(PackageVersion).nupkg"
+ DestinationFolder="$(GodotOutputDataDir)Tools\nupkgs\" />
+ </Target>
+</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.nuspec b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.nuspec
new file mode 100644
index 0000000000..ba68a4da43
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk.nuspec
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<package xmlns="http://schemas.microsoft.com/packaging/2011/10/nuspec.xsd">
+ <metadata>
+ <id>$id$</id>
+ <version>$version$</version>
+ <description>$description$</description>
+ <authors>$authors$</authors>
+ <owners>$authors$</owners>
+ <projectUrl>$projecturl$</projectUrl>
+ <requireLicenseAcceptance>false</requireLicenseAcceptance>
+ <license type="expression">MIT</license>
+ <licenseUrl>https://licenses.nuget.org/MIT</licenseUrl>
+ <tags>$tags$</tags>
+ <packageTypes>
+ <packageType name="$packagetype$" />
+ </packageTypes>
+ <repository url="$projecturl$" />
+ </metadata>
+ <files>
+ <file src="Sdk\**" target="Sdk" />
+ </files>
+</package>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk_PackageVersion.txt b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk_PackageVersion.txt
new file mode 100644
index 0000000000..34749489b9
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Godot.NET.Sdk_PackageVersion.txt
@@ -0,0 +1 @@
+4.0.0-dev3
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props
new file mode 100644
index 0000000000..5febcf3175
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.props
@@ -0,0 +1,112 @@
+<Project>
+ <PropertyGroup>
+ <!-- Determines if we should import Microsoft.NET.Sdk, if it wasn't already imported. -->
+ <GodotSdkImportsMicrosoftNetSdk Condition=" '$(UsingMicrosoftNETSdk)' != 'true' ">true</GodotSdkImportsMicrosoftNetSdk>
+
+ <GodotProjectTypeGuid>{8F3E2DF0-C35C-4265-82FC-BEA011F4A7ED}</GodotProjectTypeGuid>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <Configurations>Debug;ExportDebug;ExportRelease</Configurations>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+
+ <GodotProjectDir Condition=" '$(SolutionDir)' != '' ">$(SolutionDir)</GodotProjectDir>
+ <GodotProjectDir Condition=" '$(SolutionDir)' == '' ">$(MSBuildProjectDirectory)</GodotProjectDir>
+ <GodotProjectDir>$([MSBuild]::EnsureTrailingSlash('$(GodotProjectDir)'))</GodotProjectDir>
+
+ <!-- Custom output paths for Godot projects. In brief, 'bin\' and 'obj\' are moved to '$(GodotProjectDir)\.godot\mono\temp\'. -->
+ <BaseOutputPath>$(GodotProjectDir).godot\mono\temp\bin\</BaseOutputPath>
+ <OutputPath>$(GodotProjectDir).godot\mono\temp\bin\$(Configuration)\</OutputPath>
+ <!--
+ Use custom IntermediateOutputPath and BaseIntermediateOutputPath only if it wasn't already set.
+ Otherwise the old values may have already been changed by MSBuild which can cause problems with NuGet.
+ -->
+ <IntermediateOutputPath Condition=" '$(IntermediateOutputPath)' == '' ">$(GodotProjectDir).godot\mono\temp\obj\$(Configuration)\</IntermediateOutputPath>
+ <BaseIntermediateOutputPath Condition=" '$(BaseIntermediateOutputPath)' == '' ">$(GodotProjectDir).godot\mono\temp\obj\</BaseIntermediateOutputPath>
+
+ <!-- Do not append the target framework name to the output path. -->
+ <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+ </PropertyGroup>
+
+ <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.props" Condition=" '$(GodotSdkImportsMicrosoftNetSdk)' == 'true' " />
+
+ <PropertyGroup>
+ <EnableDefaultNoneItems>false</EnableDefaultNoneItems>
+ </PropertyGroup>
+
+ <!--
+ The Microsoft.NET.Sdk only understands of the Debug and Release configurations.
+ We need to set the following properties manually for ExportDebug and ExportRelease.
+ -->
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' or '$(Configuration)' == 'ExportDebug' ">
+ <DebugSymbols Condition=" '$(DebugSymbols)' == '' ">true</DebugSymbols>
+ <Optimize Condition=" '$(Optimize)' == '' ">false</Optimize>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)' == 'ExportRelease' ">
+ <Optimize Condition=" '$(Optimize)' == '' ">true</Optimize>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <GodotApiConfiguration Condition=" '$(Configuration)' != 'ExportRelease' ">Debug</GodotApiConfiguration>
+ <GodotApiConfiguration Condition=" '$(Configuration)' == 'ExportRelease' ">Release</GodotApiConfiguration>
+ </PropertyGroup>
+
+ <!-- Auto-detect the target Godot platform if it was not specified. -->
+ <PropertyGroup Condition=" '$(GodotTargetPlatform)' == '' ">
+ <GodotTargetPlatform Condition=" '$([MSBuild]::IsOsPlatform(Linux))' ">linuxbsd</GodotTargetPlatform>
+ <GodotTargetPlatform Condition=" '$([MSBuild]::IsOsPlatform(FreeBSD))' ">linuxbsd</GodotTargetPlatform>
+ <GodotTargetPlatform Condition=" '$([MSBuild]::IsOsPlatform(OSX))' ">osx</GodotTargetPlatform>
+ <GodotTargetPlatform Condition=" '$([MSBuild]::IsOsPlatform(Windows))' ">windows</GodotTargetPlatform>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <GodotRealTIsDouble Condition=" '$(GodotRealTIsDouble)' == '' ">false</GodotRealTIsDouble>
+ </PropertyGroup>
+
+ <!-- Godot DefineConstants. -->
+ <PropertyGroup>
+ <!-- Define constant to identify Godot builds. -->
+ <GodotDefineConstants>GODOT</GodotDefineConstants>
+
+ <!--
+ Define constant to determine the target Godot platform. This includes the
+ recognized platform names and the platform category (PC, MOBILE or WEB).
+ -->
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'windows' ">GODOT_WINDOWS;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'linuxbsd' ">GODOT_LINUXBSD;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'osx' ">GODOT_OSX;GODOT_MACOS;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'server' ">GODOT_SERVER;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'uwp' ">GODOT_UWP;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'haiku' ">GODOT_HAIKU;GODOT_PC</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'android' ">GODOT_ANDROID;GODOT_MOBILE</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'iphone' ">GODOT_IPHONE;GODOT_IOS;GODOT_MOBILE</GodotPlatformConstants>
+ <GodotPlatformConstants Condition=" '$(GodotTargetPlatform)' == 'javascript' ">GODOT_JAVASCRIPT;GODOT_HTML5;GODOT_WASM;GODOT_WEB</GodotPlatformConstants>
+
+ <GodotDefineConstants>$(GodotDefineConstants);$(GodotPlatformConstants)</GodotDefineConstants>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <!-- ExportDebug also defines DEBUG like Debug does. -->
+ <DefineConstants Condition=" '$(Configuration)' == 'ExportDebug' ">$(DefineConstants);DEBUG</DefineConstants>
+ <!-- Debug defines TOOLS to differentiate between Debug and ExportDebug configurations. -->
+ <DefineConstants Condition=" '$(Configuration)' == 'Debug' ">$(DefineConstants);TOOLS</DefineConstants>
+
+ <DefineConstants>$(GodotDefineConstants);$(DefineConstants)</DefineConstants>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <!--
+ TODO:
+ We should consider a nuget package for reference assemblies. This is difficult because the
+ Godot scripting API is continuaslly breaking backwards compatibility even in patch releases.
+ -->
+ <Reference Include="GodotSharp">
+ <Private>false</Private>
+ <HintPath>$(GodotProjectDir).godot\mono\assemblies\$(GodotApiConfiguration)\GodotSharp.dll</HintPath>
+ </Reference>
+ <Reference Include="GodotSharpEditor" Condition=" '$(Configuration)' == 'Debug' ">
+ <Private>false</Private>
+ <HintPath>$(GodotProjectDir).godot\mono\assemblies\$(GodotApiConfiguration)\GodotSharpEditor.dll</HintPath>
+ </Reference>
+ </ItemGroup>
+</Project>
diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets
new file mode 100644
index 0000000000..f5afd75505
--- /dev/null
+++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets
@@ -0,0 +1,17 @@
+<Project>
+ <Import Sdk="Microsoft.NET.Sdk" Project="Sdk.targets" Condition=" '$(GodotSdkImportsMicrosoftNetSdk)' == 'true' " />
+
+ <PropertyGroup>
+ <EnableGodotProjectTypeGuid Condition=" '$(EnableGodotProjectTypeGuid)' == '' ">true</EnableGodotProjectTypeGuid>
+ <ProjectTypeGuids Condition=" '$(EnableGodotProjectTypeGuid)' == 'true' ">$(GodotProjectTypeGuid);$(DefaultProjectTypeGuid)</ProjectTypeGuids>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <!--
+ Define constant to determine whether the real_t type in Godot is double precision or not.
+ By default this is false, like the official Godot builds. If someone is using a custom
+ Godot build where real_t is double, they can override the GodotRealTIsDouble property.
+ -->
+ <DefineConstants Condition=" '$(GodotRealTIsDouble)' == 'true' ">GODOT_REAL_T_IS_DOUBLE;$(DefineConstants)</DefineConstants>
+ </PropertyGroup>
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
index 6015cb22b6..9b7b422276 100644
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
@@ -2,7 +2,6 @@ using System;
using System.IO;
using System.Security;
using Microsoft.Build.Framework;
-using GodotTools.Core;
namespace GodotTools.BuildLogger
{
@@ -16,14 +15,14 @@ namespace GodotTools.BuildLogger
public void Initialize(IEventSource eventSource)
{
if (null == Parameters)
- throw new LoggerException("Log directory was not set.");
+ throw new LoggerException("Log directory parameter not specified.");
var parameters = Parameters.Split(new[] { ';' });
string logDir = parameters[0];
if (string.IsNullOrEmpty(logDir))
- throw new LoggerException("Log directory was not set.");
+ throw new LoggerException("Log directory parameter is empty.");
if (parameters.Length > 1)
throw new LoggerException("Too many parameters passed.");
@@ -52,36 +51,46 @@ namespace GodotTools.BuildLogger
{
throw new LoggerException("Failed to create log file: " + ex.Message);
}
- else
- {
- // Unexpected failure
- throw;
- }
+
+ // Unexpected failure
+ throw;
}
eventSource.ProjectStarted += eventSource_ProjectStarted;
- eventSource.TaskStarted += eventSource_TaskStarted;
+ eventSource.ProjectFinished += eventSource_ProjectFinished;
eventSource.MessageRaised += eventSource_MessageRaised;
eventSource.WarningRaised += eventSource_WarningRaised;
eventSource.ErrorRaised += eventSource_ErrorRaised;
- eventSource.ProjectFinished += eventSource_ProjectFinished;
}
- void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
+ private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
+ {
+ WriteLine(e.Message);
+ indent++;
+ }
+
+ private void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
+ {
+ indent--;
+ WriteLine(e.Message);
+ }
+
+ private 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)
+ if (!string.IsNullOrEmpty(e.ProjectFile))
line += $" [{e.ProjectFile}]";
WriteLine(line);
string errorLine = $@"error,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber}," +
- $@"{e.Code.CsvEscape()},{e.Message.CsvEscape()},{e.ProjectFile.CsvEscape()}";
+ $"{e.Code?.CsvEscape() ?? string.Empty},{e.Message.CsvEscape()}," +
+ $"{e.ProjectFile?.CsvEscape() ?? string.Empty}";
issuesStreamWriter.WriteLine(errorLine);
}
- void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
+ private void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
string line = $"{e.File}({e.LineNumber},{e.ColumnNumber}): warning {e.Code}: {e.Message}";
@@ -90,8 +99,9 @@ namespace GodotTools.BuildLogger
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)}";
+ string warningLine = $@"warning,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber}," +
+ $"{e.Code?.CsvEscape() ?? string.Empty},{e.Message.CsvEscape()}," +
+ $"{e.ProjectFile?.CsvEscape() ?? string.Empty}";
issuesStreamWriter.WriteLine(warningLine);
}
@@ -107,40 +117,6 @@ namespace GodotTools.BuildLogger
}
}
- 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)
@@ -183,4 +159,17 @@ namespace GodotTools.BuildLogger
private StreamWriter issuesStreamWriter;
private int indent;
}
+
+ internal static class StringExtensions
+ {
+ public static string CsvEscape(this string value, char delimiter = ',')
+ {
+ bool hasSpecialChar = value.IndexOfAny(new[] { '\"', '\n', '\r', delimiter }) != -1;
+
+ if (hasSpecialChar)
+ return "\"" + value.Replace("\"", "\"\"") + "\"";
+
+ return value;
+ }
+ }
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
index 8fdd485209..0afec970c6 100644
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
@@ -1,60 +1,10 @@
-<?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')" />
+<Project Sdk="Microsoft.NET.Sdk">
<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.7</TargetFrameworkVersion>
- <FileAlignment>512</FileAlignment>
- <LangVersion>7</LangVersion>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ <LangVersion>7.2</LangVersion>
</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>
+ <PackageReference Include="Microsoft.Build.Framework" Version="16.5.0" />
</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>
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs
deleted file mode 100644
index 4374f21cfa..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-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/FileUtils.cs b/modules/mono/editor/GodotTools/GodotTools.Core/FileUtils.cs
index 85760a3705..e1ccf0454a 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Core/FileUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/FileUtils.cs
@@ -19,7 +19,10 @@ namespace GodotTools.Core
}
if (attempt > maxAttempts + 1)
- return;
+ {
+ // Overwrite the oldest one
+ backupPath = backupPathBase;
+ }
File.Copy(filePath, backupPath, overwrite: true);
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
index c9ea7d3a2c..d6d8962f90 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
@@ -1,40 +1,7 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project Sdk="Microsoft.NET.Sdk">
<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.7</TargetFrameworkVersion>
- <LangVersion>7</LangVersion>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ <LangVersion>7.2</LangVersion>
</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="FileUtils.cs" />
- <Compile Include="ProcessExtensions.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="StringExtensions.cs" />
- </ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs
deleted file mode 100644
index 699ae6e741..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-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/GodotTools/GodotTools.Core/StringExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
index 326c49f096..b217ae4bf7 100644
--- a/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Runtime.InteropServices;
namespace GodotTools.Core
{
@@ -14,47 +15,52 @@ namespace GodotTools.Core
if (Path.DirectorySeparatorChar == '\\')
dir = dir.Replace("/", "\\") + "\\";
- Uri fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
- Uri relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
+ var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
+ var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
- return relRoot.MakeRelativeUri(fullPath).ToString();
+ // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
+ return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
}
public static string NormalizePath(this string path)
{
+ if (string.IsNullOrEmpty(path))
+ return path;
+
bool rooted = path.IsAbsolutePath();
path = path.Replace('\\', '/');
+ path = path[path.Length - 1] == '/' ? path.Substring(0, path.Length - 1) : path;
- string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
+ string[] parts = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
- return rooted ? Path.DirectorySeparatorChar + path : path;
+ if (!rooted)
+ return path;
+
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ string maybeDrive = parts[0];
+ if (maybeDrive.Length == 2 && maybeDrive[1] == ':')
+ return path; // Already has drive letter
+ }
+
+ return Path.DirectorySeparatorChar + path;
}
- private static readonly string driveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
+ private static readonly string DriveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
public static bool IsAbsolutePath(this string path)
{
return path.StartsWith("/", 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;
-
- if (hasSpecialChar)
- return "\"" + value.Replace("\"", "\"\"") + "\"";
-
- return value;
+ path.StartsWith(DriveRoot, StringComparison.Ordinal);
}
- public static string ToSafeDirName(this string dirName, bool allowDirSeparator)
+ public static string ToSafeDirName(this string dirName, bool allowDirSeparator = false)
{
- var invalidChars = new List<string> { ":", "*", "?", "\"", "<", ">", "|" };
+ var invalidChars = new List<string> {":", "*", "?", "\"", "<", ">", "|"};
if (allowDirSeparator)
{
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs
deleted file mode 100644
index 7a2ff2ca56..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ConsoleLogger.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System;
-
-namespace GodotTools.IdeConnection
-{
- public class ConsoleLogger : ILogger
- {
- public void LogDebug(string message)
- {
- Console.WriteLine("DEBUG: " + message);
- }
-
- public void LogInfo(string message)
- {
- Console.WriteLine("INFO: " + message);
- }
-
- public void LogWarning(string message)
- {
- Console.WriteLine("WARN: " + message);
- }
-
- public void LogError(string message)
- {
- Console.WriteLine("ERROR: " + message);
- }
-
- public void LogError(string message, Exception e)
- {
- Console.WriteLine("EXCEPTION: " + message);
- Console.WriteLine(e);
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs
deleted file mode 100644
index be89638241..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeBase.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-using System;
-using Path = System.IO.Path;
-
-namespace GodotTools.IdeConnection
-{
- public class GodotIdeBase : IDisposable
- {
- private ILogger logger;
-
- public ILogger Logger
- {
- get => logger ?? (logger = new ConsoleLogger());
- set => logger = value;
- }
-
- private readonly string projectMetadataDir;
-
- protected const string MetaFileName = "ide_server_meta.txt";
- protected string MetaFilePath => Path.Combine(projectMetadataDir, MetaFileName);
-
- private GodotIdeConnection connection;
- protected readonly object ConnectionLock = new object();
-
- public bool IsDisposed { get; private set; } = false;
-
- public bool IsConnected => connection != null && !connection.IsDisposed && connection.IsConnected;
-
- public event Action Connected
- {
- add
- {
- if (connection != null && !connection.IsDisposed)
- connection.Connected += value;
- }
- remove
- {
- if (connection != null && !connection.IsDisposed)
- connection.Connected -= value;
- }
- }
-
- protected GodotIdeConnection Connection
- {
- get => connection;
- set
- {
- connection?.Dispose();
- connection = value;
- }
- }
-
- protected GodotIdeBase(string projectMetadataDir)
- {
- this.projectMetadataDir = projectMetadataDir;
- }
-
- protected void DisposeConnection()
- {
- lock (ConnectionLock)
- {
- connection?.Dispose();
- }
- }
-
- ~GodotIdeBase()
- {
- Dispose(disposing: false);
- }
-
- public void Dispose()
- {
- if (IsDisposed)
- return;
-
- lock (ConnectionLock)
- {
- if (IsDisposed) // lock may not be fair
- return;
- IsDisposed = true;
- }
-
- Dispose(disposing: true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- connection?.Dispose();
- }
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs
deleted file mode 100644
index 2bf3b83c75..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeClient.cs
+++ /dev/null
@@ -1,219 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-
-namespace GodotTools.IdeConnection
-{
- public abstract class GodotIdeClient : GodotIdeBase
- {
- protected GodotIdeMetadata GodotIdeMetadata;
-
- private readonly FileSystemWatcher fsWatcher;
-
- protected GodotIdeClient(string projectMetadataDir) : base(projectMetadataDir)
- {
- messageHandlers = InitializeMessageHandlers();
-
- // FileSystemWatcher requires an existing directory
- if (!File.Exists(projectMetadataDir))
- Directory.CreateDirectory(projectMetadataDir);
-
- fsWatcher = new FileSystemWatcher(projectMetadataDir, MetaFileName);
- }
-
- private void OnMetaFileChanged(object sender, FileSystemEventArgs e)
- {
- if (IsDisposed)
- return;
-
- lock (ConnectionLock)
- {
- if (IsDisposed)
- return;
-
- if (!File.Exists(MetaFilePath))
- return;
-
- var metadata = ReadMetadataFile();
-
- if (metadata != null && metadata != GodotIdeMetadata)
- {
- GodotIdeMetadata = metadata.Value;
- ConnectToServer();
- }
- }
- }
-
- private void OnMetaFileDeleted(object sender, FileSystemEventArgs e)
- {
- if (IsDisposed)
- return;
-
- if (IsConnected)
- DisposeConnection();
-
- // The file may have been re-created
-
- lock (ConnectionLock)
- {
- if (IsDisposed)
- return;
-
- if (IsConnected || !File.Exists(MetaFilePath))
- return;
-
- var metadata = ReadMetadataFile();
-
- if (metadata != null)
- {
- GodotIdeMetadata = metadata.Value;
- ConnectToServer();
- }
- }
- }
-
- private GodotIdeMetadata? ReadMetadataFile()
- {
- using (var reader = File.OpenText(MetaFilePath))
- {
- string portStr = reader.ReadLine();
-
- if (portStr == null)
- return null;
-
- string editorExecutablePath = reader.ReadLine();
-
- if (editorExecutablePath == null)
- return null;
-
- if (!int.TryParse(portStr, out int port))
- return null;
-
- return new GodotIdeMetadata(port, editorExecutablePath);
- }
- }
-
- private void ConnectToServer()
- {
- var tcpClient = new TcpClient();
-
- Connection = new GodotIdeConnectionClient(tcpClient, HandleMessage);
- Connection.Logger = Logger;
-
- try
- {
- Logger.LogInfo("Connecting to Godot Ide Server");
-
- tcpClient.Connect(IPAddress.Loopback, GodotIdeMetadata.Port);
-
- Logger.LogInfo("Connection open with Godot Ide Server");
-
- var clientThread = new Thread(Connection.Start)
- {
- IsBackground = true,
- Name = "Godot Ide Connection Client"
- };
- clientThread.Start();
- }
- catch (SocketException e)
- {
- if (e.SocketErrorCode == SocketError.ConnectionRefused)
- Logger.LogError("The connection to the Godot Ide Server was refused");
- else
- throw;
- }
- }
-
- public void Start()
- {
- Logger.LogInfo("Starting Godot Ide Client");
-
- fsWatcher.Changed += OnMetaFileChanged;
- fsWatcher.Deleted += OnMetaFileDeleted;
- fsWatcher.EnableRaisingEvents = true;
-
- lock (ConnectionLock)
- {
- if (IsDisposed)
- return;
-
- if (!File.Exists(MetaFilePath))
- {
- Logger.LogInfo("There is no Godot Ide Server running");
- return;
- }
-
- var metadata = ReadMetadataFile();
-
- if (metadata != null)
- {
- GodotIdeMetadata = metadata.Value;
- ConnectToServer();
- }
- else
- {
- Logger.LogError("Failed to read Godot Ide metadata file");
- }
- }
- }
-
- public bool WriteMessage(Message message)
- {
- return Connection.WriteMessage(message);
- }
-
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
-
- if (disposing)
- {
- fsWatcher?.Dispose();
- }
- }
-
- protected virtual bool HandleMessage(Message message)
- {
- if (messageHandlers.TryGetValue(message.Id, out var action))
- {
- action(message.Arguments);
- return true;
- }
-
- return false;
- }
-
- private readonly Dictionary<string, Action<string[]>> messageHandlers;
-
- private Dictionary<string, Action<string[]>> InitializeMessageHandlers()
- {
- return new Dictionary<string, Action<string[]>>
- {
- ["OpenFile"] = args =>
- {
- switch (args.Length)
- {
- case 1:
- OpenFile(file: args[0]);
- return;
- case 2:
- OpenFile(file: args[0], line: int.Parse(args[1]));
- return;
- case 3:
- OpenFile(file: args[0], line: int.Parse(args[1]), column: int.Parse(args[2]));
- return;
- default:
- throw new ArgumentException();
- }
- }
- };
- }
-
- protected abstract void OpenFile(string file);
- protected abstract void OpenFile(string file, int line);
- protected abstract void OpenFile(string file, int line, int column);
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs
deleted file mode 100644
index 6441be8d6e..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnection.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Net.Sockets;
-using System.Text;
-
-namespace GodotTools.IdeConnection
-{
- public abstract class GodotIdeConnection : IDisposable
- {
- protected const string Version = "1.0";
-
- protected static readonly string ClientHandshake = $"Godot Ide Client Version {Version}";
- protected static readonly string ServerHandshake = $"Godot Ide Server Version {Version}";
-
- private const int ClientWriteTimeout = 8000;
- private readonly TcpClient tcpClient;
-
- private TextReader clientReader;
- private TextWriter clientWriter;
-
- private readonly object writeLock = new object();
-
- private readonly Func<Message, bool> messageHandler;
-
- public event Action Connected;
-
- private ILogger logger;
-
- public ILogger Logger
- {
- get => logger ?? (logger = new ConsoleLogger());
- set => logger = value;
- }
-
- public bool IsDisposed { get; private set; } = false;
-
- public bool IsConnected => tcpClient.Client != null && tcpClient.Client.Connected;
-
- protected GodotIdeConnection(TcpClient tcpClient, Func<Message, bool> messageHandler)
- {
- this.tcpClient = tcpClient;
- this.messageHandler = messageHandler;
- }
-
- public void Start()
- {
- try
- {
- if (!StartConnection())
- return;
-
- string messageLine;
- while ((messageLine = ReadLine()) != null)
- {
- if (!MessageParser.TryParse(messageLine, out Message msg))
- {
- Logger.LogError($"Received message with invalid format: {messageLine}");
- continue;
- }
-
- Logger.LogDebug($"Received message: {msg}");
-
- if (msg.Id == "close")
- {
- Logger.LogInfo("Closing connection");
- return;
- }
-
- try
- {
- try
- {
- Debug.Assert(messageHandler != null);
-
- if (!messageHandler(msg))
- Logger.LogError($"Received unknown message: {msg}");
- }
- catch (Exception e)
- {
- Logger.LogError($"Message handler for '{msg}' failed with exception", e);
- }
- }
- catch (Exception e)
- {
- Logger.LogError($"Exception thrown from message handler. Message: {msg}", e);
- }
- }
- }
- catch (Exception e)
- {
- Logger.LogError($"Unhandled exception in the Godot Ide Connection thread", e);
- }
- finally
- {
- Dispose();
- }
- }
-
- private bool StartConnection()
- {
- NetworkStream clientStream = tcpClient.GetStream();
-
- clientReader = new StreamReader(clientStream, Encoding.UTF8);
-
- lock (writeLock)
- clientWriter = new StreamWriter(clientStream, Encoding.UTF8);
-
- clientStream.WriteTimeout = ClientWriteTimeout;
-
- if (!WriteHandshake())
- {
- Logger.LogError("Could not write handshake");
- return false;
- }
-
- if (!IsValidResponseHandshake(ReadLine()))
- {
- Logger.LogError("Received invalid handshake");
- return false;
- }
-
- Connected?.Invoke();
-
- Logger.LogInfo("Godot Ide connection started");
-
- return true;
- }
-
- private string ReadLine()
- {
- try
- {
- return clientReader?.ReadLine();
- }
- catch (Exception e)
- {
- if (IsDisposed)
- {
- var se = e as SocketException ?? e.InnerException as SocketException;
- if (se != null && se.SocketErrorCode == SocketError.Interrupted)
- return null;
- }
-
- throw;
- }
- }
-
- public bool WriteMessage(Message message)
- {
- Logger.LogDebug($"Sending message {message}");
-
- var messageComposer = new MessageComposer();
-
- messageComposer.AddArgument(message.Id);
- foreach (string argument in message.Arguments)
- messageComposer.AddArgument(argument);
-
- return WriteLine(messageComposer.ToString());
- }
-
- protected bool WriteLine(string text)
- {
- if (clientWriter == null || IsDisposed || !IsConnected)
- return false;
-
- lock (writeLock)
- {
- try
- {
- clientWriter.WriteLine(text);
- clientWriter.Flush();
- }
- catch (Exception e)
- {
- if (!IsDisposed)
- {
- var se = e as SocketException ?? e.InnerException as SocketException;
- if (se != null && se.SocketErrorCode == SocketError.Shutdown)
- Logger.LogInfo("Client disconnected ungracefully");
- else
- Logger.LogError("Exception thrown when trying to write to client", e);
-
- Dispose();
- }
- }
- }
-
- return true;
- }
-
- protected abstract bool WriteHandshake();
- protected abstract bool IsValidResponseHandshake(string handshakeLine);
-
- public void Dispose()
- {
- if (IsDisposed)
- return;
-
- IsDisposed = true;
-
- clientReader?.Dispose();
- clientWriter?.Dispose();
- ((IDisposable)tcpClient)?.Dispose();
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs
deleted file mode 100644
index 1b11a14358..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionClient.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System;
-using System.Net.Sockets;
-using System.Threading.Tasks;
-
-namespace GodotTools.IdeConnection
-{
- public class GodotIdeConnectionClient : GodotIdeConnection
- {
- public GodotIdeConnectionClient(TcpClient tcpClient, Func<Message, bool> messageHandler)
- : base(tcpClient, messageHandler)
- {
- }
-
- protected override bool WriteHandshake()
- {
- return WriteLine(ClientHandshake);
- }
-
- protected override bool IsValidResponseHandshake(string handshakeLine)
- {
- return handshakeLine == ServerHandshake;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs
deleted file mode 100644
index aa98dc7ca3..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeConnectionServer.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System;
-using System.Net.Sockets;
-using System.Threading.Tasks;
-
-namespace GodotTools.IdeConnection
-{
- public class GodotIdeConnectionServer : GodotIdeConnection
- {
- public GodotIdeConnectionServer(TcpClient tcpClient, Func<Message, bool> messageHandler)
- : base(tcpClient, messageHandler)
- {
- }
-
- protected override bool WriteHandshake()
- {
- return WriteLine(ServerHandshake);
- }
-
- protected override bool IsValidResponseHandshake(string handshakeLine)
- {
- return handshakeLine == ClientHandshake;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj
deleted file mode 100644
index 8454535fba..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotTools.IdeConnection.csproj
+++ /dev/null
@@ -1,53 +0,0 @@
-<?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>{92600954-25F0-4291-8E11-1FEE9FC4BE20}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>GodotTools.IdeConnection</RootNamespace>
- <AssemblyName>GodotTools.IdeConnection</AssemblyName>
- <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
- <FileAlignment>512</FileAlignment>
- <LangVersion>7</LangVersion>
- </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="System" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="ConsoleLogger.cs" />
- <Compile Include="GodotIdeMetadata.cs" />
- <Compile Include="GodotIdeBase.cs" />
- <Compile Include="GodotIdeClient.cs" />
- <Compile Include="GodotIdeConnection.cs" />
- <Compile Include="GodotIdeConnectionClient.cs" />
- <Compile Include="GodotIdeConnectionServer.cs" />
- <Compile Include="ILogger.cs" />
- <Compile Include="Message.cs" />
- <Compile Include="MessageComposer.cs" />
- <Compile Include="MessageParser.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- </ItemGroup>
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs
deleted file mode 100644
index f24d324ae3..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Message.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Linq;
-
-namespace GodotTools.IdeConnection
-{
- public struct Message
- {
- public string Id { get; set; }
- public string[] Arguments { get; set; }
-
- public Message(string id, params string[] arguments)
- {
- Id = id;
- Arguments = arguments;
- }
-
- public override string ToString()
- {
- return $"(Id: '{Id}', Arguments: '{string.Join(",", Arguments)}')";
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs
deleted file mode 100644
index 30ffe7a06e..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageComposer.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System.Linq;
-using System.Text;
-
-namespace GodotTools.IdeConnection
-{
- public class MessageComposer
- {
- private readonly StringBuilder stringBuilder = new StringBuilder();
-
- private static readonly char[] CharsToEscape = { '\\', '"' };
-
- public void AddArgument(string argument)
- {
- AddArgument(argument, quoted: argument.Contains(","));
- }
-
- public void AddArgument(string argument, bool quoted)
- {
- if (stringBuilder.Length > 0)
- stringBuilder.Append(',');
-
- if (quoted)
- {
- stringBuilder.Append('"');
-
- foreach (char @char in argument)
- {
- if (CharsToEscape.Contains(@char))
- stringBuilder.Append('\\');
- stringBuilder.Append(@char);
- }
-
- stringBuilder.Append('"');
- }
- else
- {
- stringBuilder.Append(argument);
- }
- }
-
- public override string ToString()
- {
- return stringBuilder.ToString();
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs
deleted file mode 100644
index 4365d69989..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/MessageParser.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace GodotTools.IdeConnection
-{
- public static class MessageParser
- {
- public static bool TryParse(string messageLine, out Message message)
- {
- var arguments = new List<string>();
- var stringBuilder = new StringBuilder();
-
- bool expectingArgument = true;
-
- for (int i = 0; i < messageLine.Length; i++)
- {
- char @char = messageLine[i];
-
- if (@char == ',')
- {
- if (expectingArgument)
- arguments.Add(string.Empty);
-
- expectingArgument = true;
- continue;
- }
-
- bool quoted = false;
-
- if (messageLine[i] == '"')
- {
- quoted = true;
- i++;
- }
-
- while (i < messageLine.Length)
- {
- @char = messageLine[i];
-
- if (quoted && @char == '"')
- {
- i++;
- break;
- }
-
- if (@char == '\\')
- {
- i++;
- if (i < messageLine.Length)
- break;
-
- stringBuilder.Append(messageLine[i]);
- }
- else if (!quoted && @char == ',')
- {
- break; // We don't increment the counter to allow the colon to be parsed after this
- }
- else
- {
- stringBuilder.Append(@char);
- }
-
- i++;
- }
-
- arguments.Add(stringBuilder.ToString());
- stringBuilder.Clear();
-
- expectingArgument = false;
- }
-
- if (arguments.Count == 0)
- {
- message = new Message();
- return false;
- }
-
- message = new Message
- {
- Id = arguments[0],
- Arguments = arguments.Skip(1).ToArray()
- };
-
- return true;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs
deleted file mode 100644
index 0806d02ca0..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-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.IdeConnection")]
-[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("92600954-25F0-4291-8E11-1FEE9FC4BE20")]
-
-// 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.IdeMessaging.CLI/ForwarderMessageHandler.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/ForwarderMessageHandler.cs
new file mode 100644
index 0000000000..3cb6a6687e
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/ForwarderMessageHandler.cs
@@ -0,0 +1,57 @@
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging.Utils;
+
+namespace GodotTools.IdeMessaging.CLI
+{
+ public class ForwarderMessageHandler : IMessageHandler
+ {
+ private readonly StreamWriter outputWriter;
+ private readonly SemaphoreSlim outputWriteSem = new SemaphoreSlim(1);
+
+ public ForwarderMessageHandler(StreamWriter outputWriter)
+ {
+ this.outputWriter = outputWriter;
+ }
+
+ public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
+ {
+ await WriteRequestToOutput(id, content);
+ return new MessageContent(MessageStatus.RequestNotSupported, "null");
+ }
+
+ private async Task WriteRequestToOutput(string id, MessageContent content)
+ {
+ using (await outputWriteSem.UseAsync())
+ {
+ await outputWriter.WriteLineAsync("======= Request =======");
+ await outputWriter.WriteLineAsync(id);
+ await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString());
+ await outputWriter.WriteLineAsync(content.Body);
+ await outputWriter.WriteLineAsync("=======================");
+ await outputWriter.FlushAsync();
+ }
+ }
+
+ public async Task WriteResponseToOutput(string id, MessageContent content)
+ {
+ using (await outputWriteSem.UseAsync())
+ {
+ await outputWriter.WriteLineAsync("======= Response =======");
+ await outputWriter.WriteLineAsync(id);
+ await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString());
+ await outputWriter.WriteLineAsync(content.Body);
+ await outputWriter.WriteLineAsync("========================");
+ await outputWriter.FlushAsync();
+ }
+ }
+
+ public async Task WriteLineToOutput(string eventName)
+ {
+ using (await outputWriteSem.UseAsync())
+ await outputWriter.WriteLineAsync($"======= {eventName} =======");
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj
new file mode 100644
index 0000000000..ae78da27bc
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/GodotTools.IdeMessaging.CLI.csproj
@@ -0,0 +1,17 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <ProjectGuid>{B06C2951-C8E3-4F28-80B2-717CF327EB19}</ProjectGuid>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net472</TargetFramework>
+ <LangVersion>7.2</LangVersion>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\GodotTools.IdeMessaging\GodotTools.IdeMessaging.csproj" />
+ </ItemGroup>
+ <ItemGroup>
+ <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
+ </ItemGroup>
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs
new file mode 100644
index 0000000000..4db71500da
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs
@@ -0,0 +1,218 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging.Requests;
+using Newtonsoft.Json;
+
+namespace GodotTools.IdeMessaging.CLI
+{
+ internal static class Program
+ {
+ private static readonly ILogger Logger = new CustomLogger();
+
+ public static int Main(string[] args)
+ {
+ try
+ {
+ var mainTask = StartAsync(args, Console.OpenStandardInput(), Console.OpenStandardOutput());
+ mainTask.Wait();
+ return mainTask.Result;
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError("Unhandled exception: ", ex);
+ return 1;
+ }
+ }
+
+ private static async Task<int> StartAsync(string[] args, Stream inputStream, Stream outputStream)
+ {
+ var inputReader = new StreamReader(inputStream, Encoding.UTF8);
+ var outputWriter = new StreamWriter(outputStream, Encoding.UTF8);
+
+ try
+ {
+ if (args.Length == 0)
+ {
+ Logger.LogError("Expected at least 1 argument");
+ return 1;
+ }
+
+ string godotProjectDir = args[0];
+
+ if (!Directory.Exists(godotProjectDir))
+ {
+ Logger.LogError($"The specified Godot project directory does not exist: {godotProjectDir}");
+ return 1;
+ }
+
+ var forwarder = new ForwarderMessageHandler(outputWriter);
+
+ using (var fwdClient = new Client("VisualStudioCode", godotProjectDir, forwarder, Logger))
+ {
+ fwdClient.Start();
+
+ // ReSharper disable AccessToDisposedClosure
+ fwdClient.Connected += async () => await forwarder.WriteLineToOutput("Event=Connected");
+ fwdClient.Disconnected += async () => await forwarder.WriteLineToOutput("Event=Disconnected");
+ // ReSharper restore AccessToDisposedClosure
+
+ // TODO: Await connected with timeout
+
+ while (!fwdClient.IsDisposed)
+ {
+ string firstLine = await inputReader.ReadLineAsync();
+
+ if (firstLine == null || firstLine == "QUIT")
+ goto ExitMainLoop;
+
+ string messageId = firstLine;
+
+ string messageArgcLine = await inputReader.ReadLineAsync();
+
+ if (messageArgcLine == null)
+ {
+ Logger.LogInfo("EOF when expecting argument count");
+ goto ExitMainLoop;
+ }
+
+ if (!int.TryParse(messageArgcLine, out int messageArgc))
+ {
+ Logger.LogError("Received invalid line for argument count: " + firstLine);
+ continue;
+ }
+
+ var body = new StringBuilder();
+
+ for (int i = 0; i < messageArgc; i++)
+ {
+ string bodyLine = await inputReader.ReadLineAsync();
+
+ if (bodyLine == null)
+ {
+ Logger.LogInfo($"EOF when expecting body line #{i + 1}");
+ goto ExitMainLoop;
+ }
+
+ body.AppendLine(bodyLine);
+ }
+
+ var response = await SendRequest(fwdClient, messageId, new MessageContent(MessageStatus.Ok, body.ToString()));
+
+ if (response == null)
+ {
+ Logger.LogError($"Failed to write message to the server: {messageId}");
+ }
+ else
+ {
+ var content = new MessageContent(response.Status, JsonConvert.SerializeObject(response));
+ await forwarder.WriteResponseToOutput(messageId, content);
+ }
+ }
+
+ ExitMainLoop:
+
+ await forwarder.WriteLineToOutput("Event=Quit");
+ }
+
+ return 0;
+ }
+ catch (Exception e)
+ {
+ Logger.LogError("Unhandled exception", e);
+ return 1;
+ }
+ }
+
+ private static async Task<Response> SendRequest(Client client, string id, MessageContent content)
+ {
+ var handlers = new Dictionary<string, Func<Task<Response>>>
+ {
+ [PlayRequest.Id] = async () =>
+ {
+ var request = JsonConvert.DeserializeObject<PlayRequest>(content.Body);
+ return await client.SendRequest<PlayResponse>(request);
+ },
+ [DebugPlayRequest.Id] = async () =>
+ {
+ var request = JsonConvert.DeserializeObject<DebugPlayRequest>(content.Body);
+ return await client.SendRequest<DebugPlayResponse>(request);
+ },
+ [ReloadScriptsRequest.Id] = async () =>
+ {
+ var request = JsonConvert.DeserializeObject<ReloadScriptsRequest>(content.Body);
+ return await client.SendRequest<ReloadScriptsResponse>(request);
+ },
+ [CodeCompletionRequest.Id] = async () =>
+ {
+ var request = JsonConvert.DeserializeObject<CodeCompletionRequest>(content.Body);
+ return await client.SendRequest<CodeCompletionResponse>(request);
+ }
+ };
+
+ if (handlers.TryGetValue(id, out var handler))
+ return await handler();
+
+ Console.WriteLine("INVALID REQUEST");
+ return null;
+ }
+
+ private class CustomLogger : ILogger
+ {
+ private static string ThisAppPath => Assembly.GetExecutingAssembly().Location;
+ private static string ThisAppPathWithoutExtension => Path.ChangeExtension(ThisAppPath, null);
+
+ private static readonly string LogPath = $"{ThisAppPathWithoutExtension}.log";
+
+ private static StreamWriter NewWriter() => new StreamWriter(LogPath, append: true, encoding: Encoding.UTF8);
+
+ private static void Log(StreamWriter writer, string message)
+ {
+ writer.WriteLine($"{DateTime.Now:HH:mm:ss.ffffff}: {message}");
+ }
+
+ public void LogDebug(string message)
+ {
+ using (var writer = NewWriter())
+ {
+ Log(writer, "DEBUG: " + message);
+ }
+ }
+
+ public void LogInfo(string message)
+ {
+ using (var writer = NewWriter())
+ {
+ Log(writer, "INFO: " + message);
+ }
+ }
+
+ public void LogWarning(string message)
+ {
+ using (var writer = NewWriter())
+ {
+ Log(writer, "WARN: " + message);
+ }
+ }
+
+ public void LogError(string message)
+ {
+ using (var writer = NewWriter())
+ {
+ Log(writer, "ERROR: " + message);
+ }
+ }
+
+ public void LogError(string message, Exception e)
+ {
+ using (var writer = NewWriter())
+ {
+ Log(writer, "EXCEPTION: " + message + '\n' + e);
+ }
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs
new file mode 100644
index 0000000000..0f50c90531
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Client.cs
@@ -0,0 +1,351 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using Newtonsoft.Json;
+using System.Threading;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging.Requests;
+using GodotTools.IdeMessaging.Utils;
+
+namespace GodotTools.IdeMessaging
+{
+ // ReSharper disable once UnusedType.Global
+ public sealed class Client : IDisposable
+ {
+ private readonly ILogger logger;
+
+ private readonly string identity;
+
+ private string MetaFilePath { get; }
+ private DateTime? metaFileModifiedTime;
+ private GodotIdeMetadata godotIdeMetadata;
+ private readonly FileSystemWatcher fsWatcher;
+
+ public string GodotEditorExecutablePath => godotIdeMetadata.EditorExecutablePath;
+
+ private readonly IMessageHandler messageHandler;
+
+ private Peer peer;
+ private readonly SemaphoreSlim connectionSem = new SemaphoreSlim(1);
+
+ private readonly Queue<NotifyAwaiter<bool>> clientConnectedAwaiters = new Queue<NotifyAwaiter<bool>>();
+ private readonly Queue<NotifyAwaiter<bool>> clientDisconnectedAwaiters = new Queue<NotifyAwaiter<bool>>();
+
+ // ReSharper disable once UnusedMember.Global
+ public async Task<bool> AwaitConnected()
+ {
+ var awaiter = new NotifyAwaiter<bool>();
+ clientConnectedAwaiters.Enqueue(awaiter);
+ return await awaiter;
+ }
+
+ // ReSharper disable once UnusedMember.Global
+ public async Task<bool> AwaitDisconnected()
+ {
+ var awaiter = new NotifyAwaiter<bool>();
+ clientDisconnectedAwaiters.Enqueue(awaiter);
+ return await awaiter;
+ }
+
+ // ReSharper disable once MemberCanBePrivate.Global
+ public bool IsDisposed { get; private set; }
+
+ // ReSharper disable once MemberCanBePrivate.Global
+ public bool IsConnected => peer != null && !peer.IsDisposed && peer.IsTcpClientConnected;
+
+ // ReSharper disable once EventNeverSubscribedTo.Global
+ public event Action Connected
+ {
+ add
+ {
+ if (peer != null && !peer.IsDisposed)
+ peer.Connected += value;
+ }
+ remove
+ {
+ if (peer != null && !peer.IsDisposed)
+ peer.Connected -= value;
+ }
+ }
+
+ // ReSharper disable once EventNeverSubscribedTo.Global
+ public event Action Disconnected
+ {
+ add
+ {
+ if (peer != null && !peer.IsDisposed)
+ peer.Disconnected += value;
+ }
+ remove
+ {
+ if (peer != null && !peer.IsDisposed)
+ peer.Disconnected -= value;
+ }
+ }
+
+ ~Client()
+ {
+ Dispose(disposing: false);
+ }
+
+ public async void Dispose()
+ {
+ if (IsDisposed)
+ return;
+
+ using (await connectionSem.UseAsync())
+ {
+ if (IsDisposed) // lock may not be fair
+ return;
+ IsDisposed = true;
+ }
+
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ peer?.Dispose();
+ fsWatcher?.Dispose();
+ }
+ }
+
+ public Client(string identity, string godotProjectDir, IMessageHandler messageHandler, ILogger logger)
+ {
+ this.identity = identity;
+ this.messageHandler = messageHandler;
+ this.logger = logger;
+
+ string projectMetadataDir = Path.Combine(godotProjectDir, ".godot", "mono", "metadata");
+
+ MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName);
+
+ // FileSystemWatcher requires an existing directory
+ if (!Directory.Exists(projectMetadataDir))
+ Directory.CreateDirectory(projectMetadataDir);
+
+ fsWatcher = new FileSystemWatcher(projectMetadataDir, GodotIdeMetadata.DefaultFileName);
+ }
+
+ private async void OnMetaFileChanged(object sender, FileSystemEventArgs e)
+ {
+ if (IsDisposed)
+ return;
+
+ using (await connectionSem.UseAsync())
+ {
+ if (IsDisposed)
+ return;
+
+ if (!File.Exists(MetaFilePath))
+ return;
+
+ var lastWriteTime = File.GetLastWriteTime(MetaFilePath);
+
+ if (lastWriteTime == metaFileModifiedTime)
+ return;
+
+ metaFileModifiedTime = lastWriteTime;
+
+ var metadata = ReadMetadataFile();
+
+ if (metadata != null && metadata != godotIdeMetadata)
+ {
+ godotIdeMetadata = metadata.Value;
+ _ = Task.Run(ConnectToServer);
+ }
+ }
+ }
+
+ private async void OnMetaFileDeleted(object sender, FileSystemEventArgs e)
+ {
+ if (IsDisposed)
+ return;
+
+ if (IsConnected)
+ {
+ using (await connectionSem.UseAsync())
+ peer?.Dispose();
+ }
+
+ // The file may have been re-created
+
+ using (await connectionSem.UseAsync())
+ {
+ if (IsDisposed)
+ return;
+
+ if (IsConnected || !File.Exists(MetaFilePath))
+ return;
+
+ var lastWriteTime = File.GetLastWriteTime(MetaFilePath);
+
+ if (lastWriteTime == metaFileModifiedTime)
+ return;
+
+ metaFileModifiedTime = lastWriteTime;
+
+ var metadata = ReadMetadataFile();
+
+ if (metadata != null)
+ {
+ godotIdeMetadata = metadata.Value;
+ _ = Task.Run(ConnectToServer);
+ }
+ }
+ }
+
+ private GodotIdeMetadata? ReadMetadataFile()
+ {
+ using (var fileStream = new FileStream(MetaFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
+ using (var reader = new StreamReader(fileStream))
+ {
+ string portStr = reader.ReadLine();
+
+ if (portStr == null)
+ return null;
+
+ string editorExecutablePath = reader.ReadLine();
+
+ if (editorExecutablePath == null)
+ return null;
+
+ if (!int.TryParse(portStr, out int port))
+ return null;
+
+ return new GodotIdeMetadata(port, editorExecutablePath);
+ }
+ }
+
+ private async Task AcceptClient(TcpClient tcpClient)
+ {
+ logger.LogDebug("Accept client...");
+
+ using (peer = new Peer(tcpClient, new ClientHandshake(), messageHandler, logger))
+ {
+ // ReSharper disable AccessToDisposedClosure
+ peer.Connected += () =>
+ {
+ logger.LogInfo("Connection open with Ide Client");
+
+ while (clientConnectedAwaiters.Count > 0)
+ clientConnectedAwaiters.Dequeue().SetResult(true);
+ };
+
+ peer.Disconnected += () =>
+ {
+ while (clientDisconnectedAwaiters.Count > 0)
+ clientDisconnectedAwaiters.Dequeue().SetResult(true);
+ };
+ // ReSharper restore AccessToDisposedClosure
+
+ try
+ {
+ if (!await peer.DoHandshake(identity))
+ {
+ logger.LogError("Handshake failed");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ logger.LogError("Handshake failed with unhandled exception: ", e);
+ return;
+ }
+
+ await peer.Process();
+
+ logger.LogInfo("Connection closed with Ide Client");
+ }
+ }
+
+ private async Task ConnectToServer()
+ {
+ var tcpClient = new TcpClient();
+
+ try
+ {
+ logger.LogInfo("Connecting to Godot Ide Server");
+
+ await tcpClient.ConnectAsync(IPAddress.Loopback, godotIdeMetadata.Port);
+
+ logger.LogInfo("Connection open with Godot Ide Server");
+
+ await AcceptClient(tcpClient);
+ }
+ catch (SocketException e)
+ {
+ if (e.SocketErrorCode == SocketError.ConnectionRefused)
+ logger.LogError("The connection to the Godot Ide Server was refused");
+ else
+ throw;
+ }
+ }
+
+ // ReSharper disable once UnusedMember.Global
+ public async void Start()
+ {
+ fsWatcher.Created += OnMetaFileChanged;
+ fsWatcher.Changed += OnMetaFileChanged;
+ fsWatcher.Deleted += OnMetaFileDeleted;
+ fsWatcher.EnableRaisingEvents = true;
+
+ using (await connectionSem.UseAsync())
+ {
+ if (IsDisposed)
+ return;
+
+ if (IsConnected)
+ return;
+
+ if (!File.Exists(MetaFilePath))
+ {
+ logger.LogInfo("There is no Godot Ide Server running");
+ return;
+ }
+
+ var metadata = ReadMetadataFile();
+
+ if (metadata != null)
+ {
+ godotIdeMetadata = metadata.Value;
+ _ = Task.Run(ConnectToServer);
+ }
+ else
+ {
+ logger.LogError("Failed to read Godot Ide metadata file");
+ }
+ }
+ }
+
+ public async Task<TResponse> SendRequest<TResponse>(Request request)
+ where TResponse : Response, new()
+ {
+ if (!IsConnected)
+ {
+ logger.LogError("Cannot write request. Not connected to the Godot Ide Server.");
+ return null;
+ }
+
+ string body = JsonConvert.SerializeObject(request);
+ return await peer.SendRequest<TResponse>(request.Id, body);
+ }
+
+ public async Task<TResponse> SendRequest<TResponse>(string id, string body)
+ where TResponse : Response, new()
+ {
+ if (!IsConnected)
+ {
+ logger.LogError("Cannot write request. Not connected to the Godot Ide Server.");
+ return null;
+ }
+
+ return await peer.SendRequest<TResponse>(id, body);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientHandshake.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientHandshake.cs
new file mode 100644
index 0000000000..43041be7be
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientHandshake.cs
@@ -0,0 +1,44 @@
+using System.Text.RegularExpressions;
+
+namespace GodotTools.IdeMessaging
+{
+ public class ClientHandshake : IHandshake
+ {
+ private static readonly string ClientHandshakeBase = $"{Peer.ClientHandshakeName},Version={Peer.ProtocolVersionMajor}.{Peer.ProtocolVersionMinor}.{Peer.ProtocolVersionRevision}";
+ private static readonly string ServerHandshakePattern = $@"{Regex.Escape(Peer.ServerHandshakeName)},Version=([0-9]+)\.([0-9]+)\.([0-9]+),([_a-zA-Z][_a-zA-Z0-9]{{0,63}})";
+
+ public string GetHandshakeLine(string identity) => $"{ClientHandshakeBase},{identity}";
+
+ public bool IsValidPeerHandshake(string handshake, out string identity, ILogger logger)
+ {
+ identity = null;
+
+ var match = Regex.Match(handshake, ServerHandshakePattern);
+
+ if (!match.Success)
+ return false;
+
+ if (!uint.TryParse(match.Groups[1].Value, out uint serverMajor) || Peer.ProtocolVersionMajor != serverMajor)
+ {
+ logger.LogDebug("Incompatible major version: " + match.Groups[1].Value);
+ return false;
+ }
+
+ if (!uint.TryParse(match.Groups[2].Value, out uint serverMinor) || Peer.ProtocolVersionMinor < serverMinor)
+ {
+ logger.LogDebug("Incompatible minor version: " + match.Groups[2].Value);
+ return false;
+ }
+
+ if (!uint.TryParse(match.Groups[3].Value, out uint _)) // Revision
+ {
+ logger.LogDebug("Incompatible revision build: " + match.Groups[3].Value);
+ return false;
+ }
+
+ identity = match.Groups[4].Value;
+
+ return true;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs
new file mode 100644
index 0000000000..64bcfd824c
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs
@@ -0,0 +1,52 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging.Requests;
+using Newtonsoft.Json;
+
+namespace GodotTools.IdeMessaging
+{
+ // ReSharper disable once UnusedType.Global
+ public abstract class ClientMessageHandler : IMessageHandler
+ {
+ private readonly Dictionary<string, Peer.RequestHandler> requestHandlers;
+
+ protected ClientMessageHandler()
+ {
+ requestHandlers = InitializeRequestHandlers();
+ }
+
+ public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
+ {
+ if (!requestHandlers.TryGetValue(id, out var handler))
+ {
+ logger.LogError($"Received unknown request: {id}");
+ return new MessageContent(MessageStatus.RequestNotSupported, "null");
+ }
+
+ try
+ {
+ var response = await handler(peer, content);
+ return new MessageContent(response.Status, JsonConvert.SerializeObject(response));
+ }
+ catch (JsonException)
+ {
+ logger.LogError($"Received request with invalid body: {id}");
+ return new MessageContent(MessageStatus.InvalidRequestBody, "null");
+ }
+ }
+
+ private Dictionary<string, Peer.RequestHandler> InitializeRequestHandlers()
+ {
+ return new Dictionary<string, Peer.RequestHandler>
+ {
+ [OpenFileRequest.Id] = async (peer, content) =>
+ {
+ var request = JsonConvert.DeserializeObject<OpenFileRequest>(content.Body);
+ return await HandleOpenFile(request);
+ }
+ };
+ }
+
+ protected abstract Task<Response> HandleOpenFile(OpenFileRequest request);
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotIdeMetadata.cs
index d16daba0e2..686202e81e 100644
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/GodotIdeMetadata.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotIdeMetadata.cs
@@ -1,10 +1,12 @@
-namespace GodotTools.IdeConnection
+namespace GodotTools.IdeMessaging
{
- public struct GodotIdeMetadata
+ public readonly struct GodotIdeMetadata
{
public int Port { get; }
public string EditorExecutablePath { get; }
+ public const string DefaultFileName = "ide_messaging_meta.txt";
+
public GodotIdeMetadata(int port, string editorExecutablePath)
{
Port = port;
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotTools.IdeMessaging.csproj b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotTools.IdeMessaging.csproj
new file mode 100644
index 0000000000..dad6b9ae7a
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/GodotTools.IdeMessaging.csproj
@@ -0,0 +1,24 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <ProjectGuid>{92600954-25F0-4291-8E11-1FEE9FC4BE20}</ProjectGuid>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ <LangVersion>7.2</LangVersion>
+ <PackageId>GodotTools.IdeMessaging</PackageId>
+ <Version>1.1.1</Version>
+ <AssemblyVersion>$(Version)</AssemblyVersion>
+ <Authors>Godot Engine contributors</Authors>
+ <Company />
+ <PackageTags>godot</PackageTags>
+ <RepositoryUrl>https://github.com/godotengine/godot/tree/master/modules/mono/editor/GodotTools/GodotTools.IdeMessaging</RepositoryUrl>
+ <PackageLicenseExpression>MIT</PackageLicenseExpression>
+ <Description>
+This library enables communication with the Godot Engine editor (the version with .NET support).
+It's intended for use in IDEs/editors plugins for a better experience working with Godot C# projects.
+
+A client using this library is only compatible with servers of the same major version and of a lower or equal minor version.
+ </Description>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
+ </ItemGroup>
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IHandshake.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IHandshake.cs
new file mode 100644
index 0000000000..6387145a28
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IHandshake.cs
@@ -0,0 +1,8 @@
+namespace GodotTools.IdeMessaging
+{
+ public interface IHandshake
+ {
+ string GetHandshakeLine(string identity);
+ bool IsValidPeerHandshake(string handshake, out string identity, ILogger logger);
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ILogger.cs
index 614bb30271..d2855f93a1 100644
--- a/modules/mono/editor/GodotTools/GodotTools.IdeConnection/ILogger.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ILogger.cs
@@ -1,6 +1,6 @@
using System;
-namespace GodotTools.IdeConnection
+namespace GodotTools.IdeMessaging
{
public interface ILogger
{
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IMessageHandler.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IMessageHandler.cs
new file mode 100644
index 0000000000..9622fcc96d
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/IMessageHandler.cs
@@ -0,0 +1,9 @@
+using System.Threading.Tasks;
+
+namespace GodotTools.IdeMessaging
+{
+ public interface IMessageHandler
+ {
+ Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger);
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Message.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Message.cs
new file mode 100644
index 0000000000..6903ec197b
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Message.cs
@@ -0,0 +1,52 @@
+namespace GodotTools.IdeMessaging
+{
+ public class Message
+ {
+ public MessageKind Kind { get; }
+ public string Id { get; }
+ public MessageContent Content { get; }
+
+ public Message(MessageKind kind, string id, MessageContent content)
+ {
+ Kind = kind;
+ Id = id;
+ Content = content;
+ }
+
+ public override string ToString()
+ {
+ return $"{Kind} | {Id}";
+ }
+ }
+
+ public enum MessageKind
+ {
+ Request,
+ Response
+ }
+
+ public enum MessageStatus
+ {
+ Ok,
+ RequestNotSupported,
+ InvalidRequestBody
+ }
+
+ public readonly struct MessageContent
+ {
+ public MessageStatus Status { get; }
+ public string Body { get; }
+
+ public MessageContent(string body)
+ {
+ Status = MessageStatus.Ok;
+ Body = body;
+ }
+
+ public MessageContent(MessageStatus status, string body)
+ {
+ Status = status;
+ Body = body;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/MessageDecoder.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/MessageDecoder.cs
new file mode 100644
index 0000000000..a00575a2a1
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/MessageDecoder.cs
@@ -0,0 +1,100 @@
+using System;
+using System.Text;
+
+namespace GodotTools.IdeMessaging
+{
+ public class MessageDecoder
+ {
+ private class DecodedMessage
+ {
+ public MessageKind? Kind;
+ public string Id;
+ public MessageStatus? Status;
+ public readonly StringBuilder Body = new StringBuilder();
+ public uint? PendingBodyLines;
+
+ public void Clear()
+ {
+ Kind = null;
+ Id = null;
+ Status = null;
+ Body.Clear();
+ PendingBodyLines = null;
+ }
+
+ public Message ToMessage()
+ {
+ if (!Kind.HasValue || Id == null || !Status.HasValue ||
+ !PendingBodyLines.HasValue || PendingBodyLines.Value > 0)
+ throw new InvalidOperationException();
+
+ return new Message(Kind.Value, Id, new MessageContent(Status.Value, Body.ToString()));
+ }
+ }
+
+ public enum State
+ {
+ Decoding,
+ Decoded,
+ Errored
+ }
+
+ private readonly DecodedMessage decodingMessage = new DecodedMessage();
+
+ public State Decode(string messageLine, out Message decodedMessage)
+ {
+ decodedMessage = null;
+
+ if (!decodingMessage.Kind.HasValue)
+ {
+ if (!Enum.TryParse(messageLine, ignoreCase: true, out MessageKind kind))
+ {
+ decodingMessage.Clear();
+ return State.Errored;
+ }
+
+ decodingMessage.Kind = kind;
+ }
+ else if (decodingMessage.Id == null)
+ {
+ decodingMessage.Id = messageLine;
+ }
+ else if (decodingMessage.Status == null)
+ {
+ if (!Enum.TryParse(messageLine, ignoreCase: true, out MessageStatus status))
+ {
+ decodingMessage.Clear();
+ return State.Errored;
+ }
+
+ decodingMessage.Status = status;
+ }
+ else if (decodingMessage.PendingBodyLines == null)
+ {
+ if (!uint.TryParse(messageLine, out uint pendingBodyLines))
+ {
+ decodingMessage.Clear();
+ return State.Errored;
+ }
+
+ decodingMessage.PendingBodyLines = pendingBodyLines;
+ }
+ else
+ {
+ if (decodingMessage.PendingBodyLines > 0)
+ {
+ decodingMessage.Body.AppendLine(messageLine);
+ decodingMessage.PendingBodyLines -= 1;
+ }
+ else
+ {
+ decodedMessage = decodingMessage.ToMessage();
+ decodingMessage.Clear();
+ return State.Decoded;
+ }
+ }
+
+ return State.Decoding;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Peer.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Peer.cs
new file mode 100644
index 0000000000..10d7e1898e
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Peer.cs
@@ -0,0 +1,298 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Sockets;
+using System.Reflection;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging.Requests;
+using GodotTools.IdeMessaging.Utils;
+
+namespace GodotTools.IdeMessaging
+{
+ public sealed class Peer : IDisposable
+ {
+ /// <summary>
+ /// Major version.
+ /// There is no forward nor backward compatibility between different major versions.
+ /// Connection is refused if client and server have different major versions.
+ /// </summary>
+ public static readonly int ProtocolVersionMajor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Major;
+
+ /// <summary>
+ /// Minor version, which clients must be backward compatible with.
+ /// Connection is refused if the client's minor version is lower than the server's.
+ /// </summary>
+ public static readonly int ProtocolVersionMinor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Minor;
+
+ /// <summary>
+ /// Revision, which doesn't affect compatibility.
+ /// </summary>
+ public static readonly int ProtocolVersionRevision = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Revision;
+
+ public const string ClientHandshakeName = "GodotIdeClient";
+ public const string ServerHandshakeName = "GodotIdeServer";
+
+ private const int ClientWriteTimeout = 8000;
+
+ public delegate Task<Response> RequestHandler(Peer peer, MessageContent content);
+
+ private readonly TcpClient tcpClient;
+
+ private readonly TextReader clientReader;
+ private readonly TextWriter clientWriter;
+
+ private readonly SemaphoreSlim writeSem = new SemaphoreSlim(1);
+
+ private string remoteIdentity = string.Empty;
+ public string RemoteIdentity => remoteIdentity;
+
+ public event Action Connected;
+ public event Action Disconnected;
+
+ private ILogger Logger { get; }
+
+ public bool IsDisposed { get; private set; }
+
+ public bool IsTcpClientConnected => tcpClient.Client != null && tcpClient.Client.Connected;
+
+ private bool IsConnected { get; set; }
+
+ private readonly IHandshake handshake;
+ private readonly IMessageHandler messageHandler;
+
+ private readonly Dictionary<string, Queue<ResponseAwaiter>> requestAwaiterQueues = new Dictionary<string, Queue<ResponseAwaiter>>();
+ private readonly SemaphoreSlim requestsSem = new SemaphoreSlim(1);
+
+ public Peer(TcpClient tcpClient, IHandshake handshake, IMessageHandler messageHandler, ILogger logger)
+ {
+ this.tcpClient = tcpClient;
+ this.handshake = handshake;
+ this.messageHandler = messageHandler;
+
+ Logger = logger;
+
+ NetworkStream clientStream = tcpClient.GetStream();
+ clientStream.WriteTimeout = ClientWriteTimeout;
+
+ clientReader = new StreamReader(clientStream, Encoding.UTF8);
+ clientWriter = new StreamWriter(clientStream, Encoding.UTF8) {NewLine = "\n"};
+ }
+
+ public async Task Process()
+ {
+ try
+ {
+ var decoder = new MessageDecoder();
+
+ string messageLine;
+ while ((messageLine = await ReadLine()) != null)
+ {
+ var state = decoder.Decode(messageLine, out var msg);
+
+ if (state == MessageDecoder.State.Decoding)
+ continue; // Not finished decoding yet
+
+ if (state == MessageDecoder.State.Errored)
+ {
+ Logger.LogError($"Received message line with invalid format: {messageLine}");
+ continue;
+ }
+
+ Logger.LogDebug($"Received message: {msg}");
+
+ try
+ {
+ if (msg.Kind == MessageKind.Request)
+ {
+ var responseContent = await messageHandler.HandleRequest(this, msg.Id, msg.Content, Logger);
+ await WriteMessage(new Message(MessageKind.Response, msg.Id, responseContent));
+ }
+ else if (msg.Kind == MessageKind.Response)
+ {
+ ResponseAwaiter responseAwaiter;
+
+ using (await requestsSem.UseAsync())
+ {
+ if (!requestAwaiterQueues.TryGetValue(msg.Id, out var queue) || queue.Count <= 0)
+ {
+ Logger.LogError($"Received unexpected response: {msg.Id}");
+ return;
+ }
+
+ responseAwaiter = queue.Dequeue();
+ }
+
+ responseAwaiter.SetResult(msg.Content);
+ }
+ else
+ {
+ throw new IndexOutOfRangeException($"Invalid message kind {msg.Kind}");
+ }
+ }
+ catch (Exception e)
+ {
+ Logger.LogError($"Message handler for '{msg}' failed with exception", e);
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ if (!IsDisposed || !(e is SocketException || e.InnerException is SocketException))
+ {
+ Logger.LogError("Unhandled exception in the peer loop", e);
+ }
+ }
+ }
+
+ public async Task<bool> DoHandshake(string identity)
+ {
+ if (!await WriteLine(handshake.GetHandshakeLine(identity)))
+ {
+ Logger.LogError("Could not write handshake");
+ return false;
+ }
+
+ var readHandshakeTask = ReadLine();
+
+ if (await Task.WhenAny(readHandshakeTask, Task.Delay(8000)) != readHandshakeTask)
+ {
+ Logger.LogError("Timeout waiting for the client handshake");
+ return false;
+ }
+
+ string peerHandshake = await readHandshakeTask;
+
+ if (handshake == null || !handshake.IsValidPeerHandshake(peerHandshake, out remoteIdentity, Logger))
+ {
+ Logger.LogError("Received invalid handshake: " + peerHandshake);
+ return false;
+ }
+
+ IsConnected = true;
+ Connected?.Invoke();
+
+ Logger.LogInfo("Peer connection started");
+
+ return true;
+ }
+
+ private async Task<string> ReadLine()
+ {
+ try
+ {
+ return await clientReader.ReadLineAsync();
+ }
+ catch (Exception e)
+ {
+ if (IsDisposed)
+ {
+ var se = e as SocketException ?? e.InnerException as SocketException;
+ if (se != null && se.SocketErrorCode == SocketError.Interrupted)
+ return null;
+ }
+
+ throw;
+ }
+ }
+
+ private Task<bool> WriteMessage(Message message)
+ {
+ Logger.LogDebug($"Sending message: {message}");
+ int bodyLineCount = message.Content.Body.Count(c => c == '\n');
+
+ bodyLineCount += 1; // Extra line break at the end
+
+ var builder = new StringBuilder();
+
+ builder.AppendLine(message.Kind.ToString());
+ builder.AppendLine(message.Id);
+ builder.AppendLine(message.Content.Status.ToString());
+ builder.AppendLine(bodyLineCount.ToString());
+ builder.AppendLine(message.Content.Body);
+
+ return WriteLine(builder.ToString());
+ }
+
+ public async Task<TResponse> SendRequest<TResponse>(string id, string body)
+ where TResponse : Response, new()
+ {
+ ResponseAwaiter responseAwaiter;
+
+ using (await requestsSem.UseAsync())
+ {
+ bool written = await WriteMessage(new Message(MessageKind.Request, id, new MessageContent(body)));
+
+ if (!written)
+ return null;
+
+ if (!requestAwaiterQueues.TryGetValue(id, out var queue))
+ {
+ queue = new Queue<ResponseAwaiter>();
+ requestAwaiterQueues.Add(id, queue);
+ }
+
+ responseAwaiter = new ResponseAwaiter<TResponse>();
+ queue.Enqueue(responseAwaiter);
+ }
+
+ return (TResponse)await responseAwaiter;
+ }
+
+ private async Task<bool> WriteLine(string text)
+ {
+ if (clientWriter == null || IsDisposed || !IsTcpClientConnected)
+ return false;
+
+ using (await writeSem.UseAsync())
+ {
+ try
+ {
+ await clientWriter.WriteLineAsync(text);
+ await clientWriter.FlushAsync();
+ }
+ catch (Exception e)
+ {
+ if (!IsDisposed)
+ {
+ var se = e as SocketException ?? e.InnerException as SocketException;
+ if (se != null && se.SocketErrorCode == SocketError.Shutdown)
+ Logger.LogInfo("Client disconnected ungracefully");
+ else
+ Logger.LogError("Exception thrown when trying to write to client", e);
+
+ Dispose();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ // ReSharper disable once UnusedMember.Global
+ public void ShutdownSocketSend()
+ {
+ tcpClient.Client.Shutdown(SocketShutdown.Send);
+ }
+
+ public void Dispose()
+ {
+ if (IsDisposed)
+ return;
+
+ IsDisposed = true;
+
+ if (IsTcpClientConnected)
+ {
+ if (IsConnected)
+ Disconnected?.Invoke();
+ }
+
+ clientReader?.Dispose();
+ clientWriter?.Dispose();
+ ((IDisposable)tcpClient)?.Dispose();
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Requests/Requests.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Requests/Requests.cs
new file mode 100644
index 0000000000..e93db9377b
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Requests/Requests.cs
@@ -0,0 +1,129 @@
+// ReSharper disable ClassNeverInstantiated.Global
+// ReSharper disable UnusedMember.Global
+// ReSharper disable UnusedAutoPropertyAccessor.Global
+
+using Newtonsoft.Json;
+
+namespace GodotTools.IdeMessaging.Requests
+{
+ public abstract class Request
+ {
+ [JsonIgnore] public string Id { get; }
+
+ protected Request(string id)
+ {
+ Id = id;
+ }
+ }
+
+ public abstract class Response
+ {
+ [JsonIgnore] public MessageStatus Status { get; set; } = MessageStatus.Ok;
+ }
+
+ public sealed class CodeCompletionRequest : Request
+ {
+ public enum CompletionKind
+ {
+ InputActions = 0,
+ NodePaths,
+ ResourcePaths,
+ ScenePaths,
+ ShaderParams,
+ Signals,
+ ThemeColors,
+ ThemeConstants,
+ ThemeFonts,
+ ThemeStyles
+ }
+
+ public CompletionKind Kind { get; set; }
+ public string ScriptFile { get; set; }
+
+ public new const string Id = "CodeCompletion";
+
+ public CodeCompletionRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class CodeCompletionResponse : Response
+ {
+ public CodeCompletionRequest.CompletionKind Kind;
+ public string ScriptFile { get; set; }
+ public string[] Suggestions { get; set; }
+ }
+
+ public sealed class PlayRequest : Request
+ {
+ public new const string Id = "Play";
+
+ public PlayRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class PlayResponse : Response
+ {
+ }
+
+ public sealed class StopPlayRequest : Request
+ {
+ public new const string Id = "StopPlay";
+
+ public StopPlayRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class StopPlayResponse : Response
+ {
+ }
+
+ public sealed class DebugPlayRequest : Request
+ {
+ public string DebuggerHost { get; set; }
+ public int DebuggerPort { get; set; }
+ public bool? BuildBeforePlaying { get; set; }
+
+ public new const string Id = "DebugPlay";
+
+ public DebugPlayRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class DebugPlayResponse : Response
+ {
+ }
+
+ public sealed class OpenFileRequest : Request
+ {
+ public string File { get; set; }
+ public int? Line { get; set; }
+ public int? Column { get; set; }
+
+ public new const string Id = "OpenFile";
+
+ public OpenFileRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class OpenFileResponse : Response
+ {
+ }
+
+ public sealed class ReloadScriptsRequest : Request
+ {
+ public new const string Id = "ReloadScripts";
+
+ public ReloadScriptsRequest() : base(Id)
+ {
+ }
+ }
+
+ public sealed class ReloadScriptsResponse : Response
+ {
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ResponseAwaiter.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ResponseAwaiter.cs
new file mode 100644
index 0000000000..548e7f06ee
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ResponseAwaiter.cs
@@ -0,0 +1,23 @@
+using GodotTools.IdeMessaging.Requests;
+using GodotTools.IdeMessaging.Utils;
+using Newtonsoft.Json;
+
+namespace GodotTools.IdeMessaging
+{
+ public abstract class ResponseAwaiter : NotifyAwaiter<Response>
+ {
+ public abstract void SetResult(MessageContent content);
+ }
+
+ public class ResponseAwaiter<T> : ResponseAwaiter
+ where T : Response, new()
+ {
+ public override void SetResult(MessageContent content)
+ {
+ if (content.Status == MessageStatus.Ok)
+ SetResult(JsonConvert.DeserializeObject<T>(content.Body));
+ else
+ SetResult(new T {Status = content.Status});
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/NotifyAwaiter.cs
index 700b786752..d84a63c83c 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Utils/NotifyAwaiter.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/NotifyAwaiter.cs
@@ -1,9 +1,9 @@
using System;
using System.Runtime.CompilerServices;
-namespace GodotTools.Utils
+namespace GodotTools.IdeMessaging.Utils
{
- public sealed class NotifyAwaiter<T> : INotifyCompletion
+ public class NotifyAwaiter<T> : INotifyCompletion
{
private Action continuation;
private Exception exception;
diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/SemaphoreExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/SemaphoreExtensions.cs
new file mode 100644
index 0000000000..9d593fbf8a
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Utils/SemaphoreExtensions.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace GodotTools.IdeMessaging.Utils
+{
+ public static class SemaphoreExtensions
+ {
+ public static ConfiguredTaskAwaitable<IDisposable> UseAsync(this SemaphoreSlim semaphoreSlim, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ var wrapper = new SemaphoreSlimWaitReleaseWrapper(semaphoreSlim, out Task waitAsyncTask, cancellationToken);
+ return waitAsyncTask.ContinueWith<IDisposable>(t => wrapper, cancellationToken).ConfigureAwait(false);
+ }
+
+ private struct SemaphoreSlimWaitReleaseWrapper : IDisposable
+ {
+ private readonly SemaphoreSlim semaphoreSlim;
+
+ public SemaphoreSlimWaitReleaseWrapper(SemaphoreSlim semaphoreSlim, out Task waitAsyncTask, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ this.semaphoreSlim = semaphoreSlim;
+ waitAsyncTask = this.semaphoreSlim.WaitAsync(cancellationToken);
+ }
+
+ public void Dispose()
+ {
+ semaphoreSlim.Release();
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj
new file mode 100644
index 0000000000..5b3ed0b1b7
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/GodotTools.OpenVisualStudio.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <ProjectGuid>{EAFFF236-FA96-4A4D-BD23-0E51EF988277}</ProjectGuid>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net472</TargetFramework>
+ <LangVersion>7.2</LangVersion>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
+ <PackageReference Include="EnvDTE" Version="8.0.2" />
+ </ItemGroup>
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/Program.cs b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/Program.cs
new file mode 100644
index 0000000000..ce2b378623
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/Program.cs
@@ -0,0 +1,270 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.ComTypes;
+using System.Text.RegularExpressions;
+using EnvDTE;
+
+namespace GodotTools.OpenVisualStudio
+{
+ internal static class Program
+ {
+ [DllImport("ole32.dll")]
+ private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable pprot);
+
+ [DllImport("ole32.dll")]
+ private static extern void CreateBindCtx(int reserved, out IBindCtx ppbc);
+
+ [DllImport("user32.dll")]
+ private static extern bool SetForegroundWindow(IntPtr hWnd);
+
+ private static void ShowHelp()
+ {
+ Console.WriteLine("Opens the file(s) in a Visual Studio instance that is editing the specified solution.");
+ Console.WriteLine("If an existing instance for the solution is not found, a new one is created.");
+ Console.WriteLine();
+ Console.WriteLine("Usage:");
+ Console.WriteLine(@" GodotTools.OpenVisualStudio.exe solution [file[;line[;col]]...]");
+ Console.WriteLine();
+ Console.WriteLine("Lines and columns begin at one. Zero or lower will result in an error.");
+ Console.WriteLine("If a line is specified but a column is not, the line is selected in the text editor.");
+ }
+
+ // STAThread needed, otherwise CoRegisterMessageFilter may return CO_E_NOT_SUPPORTED.
+ [STAThread]
+ private static int Main(string[] args)
+ {
+ if (args.Length == 0 || args[0] == "--help" || args[0] == "-h")
+ {
+ ShowHelp();
+ return 0;
+ }
+
+ string solutionFile = NormalizePath(args[0]);
+
+ var dte = FindInstanceEditingSolution(solutionFile);
+
+ if (dte == null)
+ {
+ // Open a new instance
+
+ var visualStudioDteType = Type.GetTypeFromProgID("VisualStudio.DTE.16.0", throwOnError: true);
+ dte = (DTE)Activator.CreateInstance(visualStudioDteType);
+
+ dte.UserControl = true;
+
+ try
+ {
+ dte.Solution.Open(solutionFile);
+ }
+ catch (ArgumentException)
+ {
+ Console.Error.WriteLine("Solution.Open: Invalid path or file not found");
+ return 1;
+ }
+
+ dte.MainWindow.Visible = true;
+ }
+
+ MessageFilter.Register();
+
+ try
+ {
+ // Open files
+
+ for (int i = 1; i < args.Length; i++)
+ {
+ // Both the line number and the column begin at one
+
+ string[] fileArgumentParts = args[i].Split(';');
+
+ string filePath = NormalizePath(fileArgumentParts[0]);
+
+ try
+ {
+ dte.ItemOperations.OpenFile(filePath);
+ }
+ catch (ArgumentException)
+ {
+ Console.Error.WriteLine("ItemOperations.OpenFile: Invalid path or file not found");
+ return 1;
+ }
+
+ if (fileArgumentParts.Length > 1)
+ {
+ if (int.TryParse(fileArgumentParts[1], out int line))
+ {
+ var textSelection = (TextSelection)dte.ActiveDocument.Selection;
+
+ if (fileArgumentParts.Length > 2)
+ {
+ if (int.TryParse(fileArgumentParts[2], out int column))
+ {
+ textSelection.MoveToLineAndOffset(line, column);
+ }
+ else
+ {
+ Console.Error.WriteLine("The column part of the argument must be a valid integer");
+ return 1;
+ }
+ }
+ else
+ {
+ textSelection.GotoLine(line, Select: true);
+ }
+ }
+ else
+ {
+ Console.Error.WriteLine("The line part of the argument must be a valid integer");
+ return 1;
+ }
+ }
+ }
+ }
+ finally
+ {
+ var mainWindow = dte.MainWindow;
+ mainWindow.Activate();
+ SetForegroundWindow(new IntPtr(mainWindow.HWnd));
+
+ MessageFilter.Revoke();
+ }
+
+ return 0;
+ }
+
+ private static DTE FindInstanceEditingSolution(string solutionPath)
+ {
+ if (GetRunningObjectTable(0, out IRunningObjectTable pprot) != 0)
+ return null;
+
+ try
+ {
+ pprot.EnumRunning(out IEnumMoniker ppenumMoniker);
+ ppenumMoniker.Reset();
+
+ var moniker = new IMoniker[1];
+
+ while (ppenumMoniker.Next(1, moniker, IntPtr.Zero) == 0)
+ {
+ string ppszDisplayName;
+
+ CreateBindCtx(0, out IBindCtx ppbc);
+
+ try
+ {
+ moniker[0].GetDisplayName(ppbc, null, out ppszDisplayName);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(ppbc);
+ }
+
+ if (ppszDisplayName == null)
+ continue;
+
+ // The digits after the colon are the process ID
+ if (!Regex.IsMatch(ppszDisplayName, "!VisualStudio.DTE.16.0:[0-9]"))
+ continue;
+
+ if (pprot.GetObject(moniker[0], out object ppunkObject) == 0)
+ {
+ if (ppunkObject is DTE dte && dte.Solution.FullName.Length > 0)
+ {
+ if (NormalizePath(dte.Solution.FullName) == solutionPath)
+ return dte;
+ }
+ }
+ }
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(pprot);
+ }
+
+ return null;
+ }
+
+ static string NormalizePath(string path)
+ {
+ return new Uri(Path.GetFullPath(path)).LocalPath
+ .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
+ .ToUpperInvariant();
+ }
+
+ #region MessageFilter. See: http: //msdn.microsoft.com/en-us/library/ms228772.aspx
+
+ private class MessageFilter : IOleMessageFilter
+ {
+ // Class containing the IOleMessageFilter
+ // thread error-handling functions
+
+ private static IOleMessageFilter _oldFilter;
+
+ // Start the filter
+ public static void Register()
+ {
+ IOleMessageFilter newFilter = new MessageFilter();
+ int ret = CoRegisterMessageFilter(newFilter, out _oldFilter);
+ if (ret != 0)
+ Console.Error.WriteLine($"CoRegisterMessageFilter failed with error code: {ret}");
+ }
+
+ // Done with the filter, close it
+ public static void Revoke()
+ {
+ int ret = CoRegisterMessageFilter(_oldFilter, out _);
+ if (ret != 0)
+ Console.Error.WriteLine($"CoRegisterMessageFilter failed with error code: {ret}");
+ }
+
+ //
+ // IOleMessageFilter functions
+ // Handle incoming thread requests
+ int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
+ {
+ // Return the flag SERVERCALL_ISHANDLED
+ return 0;
+ }
+
+ // Thread call was rejected, so try again.
+ int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
+ {
+ if (dwRejectType == 2)
+ // flag = SERVERCALL_RETRYLATER
+ {
+ // Retry the thread call immediately if return >= 0 & < 100
+ return 99;
+ }
+
+ // Too busy; cancel call
+ return -1;
+ }
+
+ int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
+ {
+ // Return the flag PENDINGMSG_WAITDEFPROCESS
+ return 2;
+ }
+
+ // Implement the IOleMessageFilter interface
+ [DllImport("ole32.dll")]
+ private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
+ }
+
+ [ComImport(), Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IOleMessageFilter
+ {
+ [PreserveSig]
+ int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
+
+ [PreserveSig]
+ int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
+
+ [PreserveSig]
+ int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
+ }
+
+ #endregion
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs
index 6f318aab4a..cc0da44a13 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs
@@ -2,6 +2,7 @@ using GodotTools.Core;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Text;
using System.Text.RegularExpressions;
namespace GodotTools.ProjectEditor
@@ -88,7 +89,7 @@ namespace GodotTools.ProjectEditor
string solutionPath = Path.Combine(DirectoryPath, Name + ".sln");
string content = string.Format(SolutionTemplate, projectsDecl, slnPlatformsCfg, projPlatformsCfg);
- File.WriteAllText(solutionPath, content);
+ File.WriteAllText(solutionPath, content, Encoding.UTF8); // UTF-8 with BOM
}
public DotNetSolution(string name)
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
index b60e501beb..37123ba2b2 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
@@ -1,57 +1,32 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</ProjectGuid>
- <OutputType>Library</OutputType>
- <RootNamespace>GodotTools.ProjectEditor</RootNamespace>
- <AssemblyName>GodotTools.ProjectEditor</AssemblyName>
- <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
- <BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath>
- <LangVersion>7</LangVersion>
+ <TargetFramework>net472</TargetFramework>
+ <LangVersion>7.2</LangVersion>
</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="Microsoft.Build" />
- <Reference Include="DotNet.Glob, Version=2.1.1.0, Culture=neutral, PublicKeyToken=b68cc888b4f632d1, processorArchitecture=MSIL">
- <HintPath>$(SolutionDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath>
- </Reference>
- </ItemGroup>
<ItemGroup>
- <Compile Include="ApiAssembliesInfo.cs" />
- <Compile Include="DotNetSolution.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="IdentifierUtils.cs" />
- <Compile Include="ProjectExtensions.cs" />
- <Compile Include="ProjectGenerator.cs" />
- <Compile Include="ProjectUtils.cs" />
+ <PackageReference Include="Microsoft.Build" Version="16.5.0" />
+ <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
- <None Include="packages.config" />
+ <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj" />
+ <ProjectReference Include="..\GodotTools.Shared\GodotTools.Shared.csproj" />
</ItemGroup>
+ <!--
+ The Microsoft.Build.Runtime package is too problematic so we create a MSBuild.exe stub. The workaround described
+ here doesn't work with Microsoft.NETFramework.ReferenceAssemblies: https://github.com/microsoft/msbuild/issues/3486
+ We need a MSBuild.exe file as there's an issue in Microsoft.Build where it executes platform dependent code when
+ searching for MSBuild.exe before the fallback to not using it. A stub is fine as it should never be executed.
+ -->
<ItemGroup>
- <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj">
- <Project>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</Project>
- <Name>GodotTools.Core</Name>
- </ProjectReference>
+ <None Include="MSBuild.exe" CopyToOutputDirectory="Always" />
</ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <Target Name="CopyMSBuildStubWindows" AfterTargets="Build" Condition=" '$(GodotPlatform)' == 'windows' Or ( '$(GodotPlatform)' == '' And '$(OS)' == 'Windows_NT' ) ">
+ <PropertyGroup>
+ <GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
+ <GodotOutputDataDir>$(GodotSourceRootPath)/bin/GodotSharp</GodotOutputDataDir>
+ </PropertyGroup>
+ <!-- Need to copy it here as well on Windows -->
+ <Copy SourceFiles="MSBuild.exe" DestinationFiles="$(GodotOutputDataDir)\Mono\lib\mono\v4.0\MSBuild.exe" />
+ </Target>
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs
index f93eb9a1fa..ed77076df3 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs
@@ -22,6 +22,37 @@ namespace GodotTools.ProjectEditor
return string.Join(".", identifiers);
}
+ /// <summary>
+ /// Skips invalid identifier characters including decimal digit numbers at the start of the identifier.
+ /// </summary>
+ private static void SkipInvalidCharacters(string source, int startIndex, StringBuilder outputBuilder)
+ {
+ for (int i = startIndex; i < source.Length; i++)
+ {
+ char @char = source[i];
+
+ switch (char.GetUnicodeCategory(@char))
+ {
+ case UnicodeCategory.UppercaseLetter:
+ case UnicodeCategory.LowercaseLetter:
+ case UnicodeCategory.TitlecaseLetter:
+ case UnicodeCategory.ModifierLetter:
+ case UnicodeCategory.LetterNumber:
+ case UnicodeCategory.OtherLetter:
+ outputBuilder.Append(@char);
+ break;
+ case UnicodeCategory.NonSpacingMark:
+ case UnicodeCategory.SpacingCombiningMark:
+ case UnicodeCategory.ConnectorPunctuation:
+ case UnicodeCategory.DecimalDigitNumber:
+ // Identifiers may start with underscore
+ if (outputBuilder.Length > startIndex || @char == '_')
+ outputBuilder.Append(@char);
+ break;
+ }
+ }
+ }
+
public static string SanitizeIdentifier(string identifier, bool allowEmpty)
{
if (string.IsNullOrEmpty(identifier))
@@ -44,30 +75,7 @@ namespace GodotTools.ProjectEditor
startIndex += 1;
}
- for (int i = startIndex; i < identifier.Length; i++)
- {
- char @char = identifier[i];
-
- switch (Char.GetUnicodeCategory(@char))
- {
- case UnicodeCategory.UppercaseLetter:
- case UnicodeCategory.LowercaseLetter:
- case UnicodeCategory.TitlecaseLetter:
- case UnicodeCategory.ModifierLetter:
- case UnicodeCategory.LetterNumber:
- case UnicodeCategory.OtherLetter:
- identifierBuilder.Append(@char);
- break;
- case UnicodeCategory.NonSpacingMark:
- case UnicodeCategory.SpacingCombiningMark:
- case UnicodeCategory.ConnectorPunctuation:
- case UnicodeCategory.DecimalDigitNumber:
- // Identifiers may start with underscore
- if (identifierBuilder.Length > startIndex || @char == '_')
- identifierBuilder.Append(@char);
- break;
- }
- }
+ SkipInvalidCharacters(identifier, startIndex, identifierBuilder);
if (identifierBuilder.Length == startIndex)
{
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/MSBuild.exe
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs
deleted file mode 100644
index f0e0d1b33d..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-using GodotTools.Core;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using DotNet.Globbing;
-using Microsoft.Build.Construction;
-
-namespace GodotTools.ProjectEditor
-{
- public static class ProjectExtensions
- {
- public static ProjectItemElement FindItemOrNull(this ProjectRootElement root, string itemType, string include, bool noCondition = false)
- {
- GlobOptions globOptions = new GlobOptions {Evaluation = {CaseInsensitive = false}};
-
- string normalizedInclude = include.NormalizePath();
-
- foreach (var itemGroup in root.ItemGroups)
- {
- if (noCondition && itemGroup.Condition.Length != 0)
- continue;
-
- foreach (var item in itemGroup.Items)
- {
- if (item.ItemType != itemType)
- continue;
-
- var glob = Glob.Parse(item.Include.NormalizePath(), globOptions);
-
- if (glob.IsMatch(normalizedInclude))
- return item;
- }
- }
-
- return null;
- }
- public static ProjectItemElement FindItemOrNullAbs(this ProjectRootElement root, string itemType, string include, bool noCondition = false)
- {
- GlobOptions globOptions = new GlobOptions {Evaluation = {CaseInsensitive = false}};
-
- string normalizedInclude = Path.GetFullPath(include).NormalizePath();
-
- foreach (var itemGroup in root.ItemGroups)
- {
- if (noCondition && itemGroup.Condition.Length != 0)
- continue;
-
- foreach (var item in itemGroup.Items)
- {
- if (item.ItemType != itemType)
- continue;
-
- var glob = Glob.Parse(Path.GetFullPath(item.Include).NormalizePath(), globOptions);
-
- if (glob.IsMatch(normalizedInclude))
- return item;
- }
- }
-
- return null;
- }
-
- public static IEnumerable<ProjectItemElement> FindAllItemsInFolder(this ProjectRootElement root, string itemType, string folder)
- {
- string absFolderNormalizedWithSep = Path.GetFullPath(folder).NormalizePath() + Path.DirectorySeparatorChar;
-
- foreach (var itemGroup in root.ItemGroups)
- {
- foreach (var item in itemGroup.Items)
- {
- if (item.ItemType != itemType)
- continue;
-
- string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath();
-
- if (absPathNormalized.StartsWith(absFolderNormalizedWithSep))
- yield return item;
- }
- }
- }
-
- public static bool HasItem(this ProjectRootElement root, string itemType, string include, bool noCondition = false)
- {
- return root.FindItemOrNull(itemType, include, noCondition) != null;
- }
-
- public static bool AddItemChecked(this ProjectRootElement root, string itemType, string include)
- {
- if (!root.HasItem(itemType, include, noCondition: true))
- {
- root.AddItem(itemType, include);
- return true;
- }
-
- return false;
- }
-
- public static bool RemoveItemChecked(this ProjectRootElement root, string itemType, string include)
- {
- var item = root.FindItemOrNullAbs(itemType, include);
- if (item != null)
- {
- item.Parent.RemoveChild(item);
- return true;
- }
-
- return false;
- }
-
- public static Guid GetGuid(this ProjectRootElement root)
- {
- foreach (var property in root.Properties)
- {
- if (property.Name == "ProjectGuid")
- return Guid.Parse(property.Value);
- }
-
- return Guid.Empty;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
index cbe3afaedd..7d49d251dd 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
@@ -1,162 +1,50 @@
-using GodotTools.Core;
using System;
-using System.Collections.Generic;
using System.IO;
-using System.Reflection;
+using System.Text;
using Microsoft.Build.Construction;
+using Microsoft.Build.Evaluation;
+using GodotTools.Shared;
namespace GodotTools.ProjectEditor
{
public static class ProjectGenerator
{
- private const string CoreApiProjectName = "GodotSharp";
- private const string EditorApiProjectName = "GodotSharpEditor";
+ public static string GodotSdkAttrValue => $"Godot.NET.Sdk/{GeneratedGodotNupkgsVersions.GodotNETSdk}";
- public static string GenGameProject(string dir, string name, IEnumerable<string> compileItems)
+ public static ProjectRootElement GenGameProject(string name)
{
- string path = Path.Combine(dir, name + ".csproj");
-
- ProjectPropertyGroupElement mainGroup;
- var root = CreateLibraryProject(name, "Debug", out mainGroup);
-
- 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)' != 'ExportRelease' ";
- mainGroup.SetProperty("ApiConfiguration", "Release").Condition = " '$(Configuration)' == 'ExportRelease' ";
-
- var debugGroup = root.AddPropertyGroup();
- debugGroup.Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ";
- debugGroup.AddProperty("DebugSymbols", "true");
- debugGroup.AddProperty("DebugType", "portable");
- debugGroup.AddProperty("Optimize", "false");
- debugGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;DEBUG;TOOLS;");
- debugGroup.AddProperty("ErrorReport", "prompt");
- debugGroup.AddProperty("WarningLevel", "4");
- debugGroup.AddProperty("ConsolePause", "false");
-
- var coreApiRef = root.AddItem("Reference", CoreApiProjectName);
- coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", CoreApiProjectName + ".dll"));
- coreApiRef.AddMetadata("Private", "False");
-
- var editorApiRef = root.AddItem("Reference", EditorApiProjectName);
- editorApiRef.Condition = " '$(Configuration)' == 'Debug' ";
- editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", EditorApiProjectName + ".dll"));
- editorApiRef.AddMetadata("Private", "False");
-
- GenAssemblyInfoFile(root, dir, name);
-
- foreach (var item in compileItems)
- {
- root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
- }
-
- root.Save(path);
-
- return root.GetGuid().ToString().ToUpper();
- }
-
- private 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);
-
- string usingDirectivesText = string.Empty;
+ if (name.Length == 0)
+ throw new ArgumentException("Project name is empty", nameof(name));
- if (usingDirectives != null)
- {
- foreach (var usingDirective in usingDirectives)
- usingDirectivesText += "\nusing " + usingDirective + ";";
- }
+ var root = ProjectRootElement.Create(NewProjectFileOptions.None);
- string assemblyLinesText = string.Empty;
+ root.Sdk = GodotSdkAttrValue;
- if (assemblyLines != null)
- assemblyLinesText += string.Join("\n", assemblyLines) + "\n";
+ var mainGroup = root.AddPropertyGroup();
+ mainGroup.AddProperty("TargetFramework", "netstandard2.1");
- string content = string.Format(AssemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText);
+ string sanitizedName = IdentifierUtils.SanitizeQualifiedIdentifier(name, allowEmptyIdentifiers: true);
- string assemblyInfoFile = Path.Combine(propertiesDir, "AssemblyInfo.cs");
+ // If the name is not a valid namespace, manually set RootNamespace to a sanitized one.
+ if (sanitizedName != name)
+ mainGroup.AddProperty("RootNamespace", sanitizedName);
- File.WriteAllText(assemblyInfoFile, content);
-
- root.AddItem("Compile", assemblyInfoFile.RelativeToPath(dir).Replace("/", "\\"));
+ return root;
}
- public static ProjectRootElement CreateLibraryProject(string name, string defaultConfig, out ProjectPropertyGroupElement mainGroup)
+ public static string GenAndSaveGameProject(string dir, string name)
{
- if (string.IsNullOrEmpty(name))
- throw new ArgumentException($"{nameof(name)} cannot be empty", nameof(name));
-
- var root = ProjectRootElement.Create();
- root.DefaultTargets = "Build";
-
- mainGroup = root.AddPropertyGroup();
- mainGroup.AddProperty("Configuration", defaultConfig).Condition = " '$(Configuration)' == '' ";
- mainGroup.AddProperty("Platform", "AnyCPU").Condition = " '$(Platform)' == '' ";
- mainGroup.AddProperty("ProjectGuid", "{" + Guid.NewGuid().ToString().ToUpper() + "}");
- mainGroup.AddProperty("OutputType", "Library");
- mainGroup.AddProperty("OutputPath", Path.Combine("bin", "$(Configuration)"));
- mainGroup.AddProperty("RootNamespace", IdentifierUtils.SanitizeQualifiedIdentifier(name, allowEmptyIdentifiers: true));
- mainGroup.AddProperty("AssemblyName", name);
- mainGroup.AddProperty("TargetFrameworkVersion", "v4.7");
- mainGroup.AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());
+ if (name.Length == 0)
+ throw new ArgumentException("Project name is empty", nameof(name));
- var exportDebugGroup = root.AddPropertyGroup();
- exportDebugGroup.Condition = " '$(Configuration)|$(Platform)' == 'ExportDebug|AnyCPU' ";
- exportDebugGroup.AddProperty("DebugSymbols", "true");
- exportDebugGroup.AddProperty("DebugType", "portable");
- exportDebugGroup.AddProperty("Optimize", "false");
- exportDebugGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;DEBUG;");
- exportDebugGroup.AddProperty("ErrorReport", "prompt");
- exportDebugGroup.AddProperty("WarningLevel", "4");
- exportDebugGroup.AddProperty("ConsolePause", "false");
-
- var exportReleaseGroup = root.AddPropertyGroup();
- exportReleaseGroup.Condition = " '$(Configuration)|$(Platform)' == 'ExportRelease|AnyCPU' ";
- exportReleaseGroup.AddProperty("DebugType", "portable");
- exportReleaseGroup.AddProperty("Optimize", "true");
- exportReleaseGroup.AddProperty("DefineConstants", "$(GodotDefineConstants);GODOT;");
- exportReleaseGroup.AddProperty("ErrorReport", "prompt");
- exportReleaseGroup.AddProperty("WarningLevel", "4");
- exportReleaseGroup.AddProperty("ConsolePause", "false");
+ string path = Path.Combine(dir, name + ".csproj");
- // References
- var referenceGroup = root.AddItemGroup();
- referenceGroup.AddItem("Reference", "System");
+ var root = GenGameProject(name);
- root.AddImport(Path.Combine("$(MSBuildBinPath)", "Microsoft.CSharp.targets").Replace("/", "\\"));
+ // Save (without BOM)
+ root.Save(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
- return root;
+ return Guid.NewGuid().ToString().ToUpper();
}
-
- 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.
-
-[assembly: AssemblyTitle(""{1}"")]
-[assembly: AssemblyDescription("""")]
-[assembly: AssemblyConfiguration("""")]
-[assembly: AssemblyCompany("""")]
-[assembly: AssemblyProduct("""")]
-[assembly: AssemblyCopyright("""")]
-[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("""")]
-{2}";
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
index f2ebef1a7d..4e2c0f17cc 100644
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
@@ -1,17 +1,17 @@
+using System;
using GodotTools.Core;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
-using System.Reflection;
-using DotNet.Globbing;
using Microsoft.Build.Construction;
+using Microsoft.Build.Globbing;
namespace GodotTools.ProjectEditor
{
public sealed class MSBuildProject
{
- public ProjectRootElement Root { get; }
+ internal ProjectRootElement Root { get; set; }
public bool HasUnsavedChanges { get; set; }
@@ -31,91 +31,7 @@ namespace GodotTools.ProjectEditor
return root != null ? new MSBuildProject(root) : null;
}
- 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();
- }
-
- public static void RenameItemInProjectChecked(string projectPath, string itemType, string oldInclude, string newInclude)
- {
- var dir = Directory.GetParent(projectPath).FullName;
- var root = ProjectRootElement.Open(projectPath);
- Debug.Assert(root != null);
-
- var normalizedOldInclude = oldInclude.NormalizePath();
- var normalizedNewInclude = newInclude.NormalizePath();
-
- var item = root.FindItemOrNullAbs(itemType, normalizedOldInclude);
-
- if (item == null)
- return;
-
- item.Include = normalizedNewInclude.RelativeToPath(dir).Replace("/", "\\");
- root.Save();
- }
-
- public static void RemoveItemFromProjectChecked(string projectPath, string itemType, string include)
- {
- var root = ProjectRootElement.Open(projectPath);
- Debug.Assert(root != null);
-
- var normalizedInclude = include.NormalizePath();
-
- if (root.RemoveItemChecked(itemType, normalizedInclude))
- root.Save();
- }
-
- public static void RenameItemsToNewFolderInProjectChecked(string projectPath, string itemType, string oldFolder, string newFolder)
- {
- var dir = Directory.GetParent(projectPath).FullName;
- var root = ProjectRootElement.Open(projectPath);
- Debug.Assert(root != null);
-
- bool dirty = false;
-
- var oldFolderNormalized = oldFolder.NormalizePath();
- var newFolderNormalized = newFolder.NormalizePath();
- string absOldFolderNormalized = Path.GetFullPath(oldFolderNormalized).NormalizePath();
- string absNewFolderNormalized = Path.GetFullPath(newFolderNormalized).NormalizePath();
-
- foreach (var item in root.FindAllItemsInFolder(itemType, oldFolderNormalized))
- {
- string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath();
- string absNewIncludeNormalized = absNewFolderNormalized + absPathNormalized.Substring(absOldFolderNormalized.Length);
- item.Include = absNewIncludeNormalized.RelativeToPath(dir).Replace("/", "\\");
- dirty = true;
- }
-
- if (dirty)
- root.Save();
- }
-
- public static void RemoveItemsInFolderFromProjectChecked(string projectPath, string itemType, string folder)
- {
- var root = ProjectRootElement.Open(projectPath);
- Debug.Assert(root != null);
-
- var folderNormalized = folder.NormalizePath();
-
- var itemsToRemove = root.FindAllItemsInFolder(itemType, folderNormalized).ToList();
-
- if (itemsToRemove.Count > 0)
- {
- foreach (var item in itemsToRemove)
- item.Parent.RemoveChild(item);
-
- root.Save();
- }
- }
-
- private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
+ private static List<string> GetAllFilesRecursive(string rootDirectory, string mask)
{
string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
@@ -125,231 +41,59 @@ namespace GodotTools.ProjectEditor
files[i] = files[i].RelativeToPath(rootDirectory);
}
- return files;
+ return new List<string>(files);
}
- public static string[] GetIncludeFiles(string projectPath, string itemType)
+ // NOTE: Assumes auto-including items. Only used by the scripts metadata generator, which will be replaced with source generators in the future.
+ public static IEnumerable<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 excluded = new List<string>();
+ var includedFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
var root = ProjectRootElement.Open(projectPath);
Debug.Assert(root != null);
- foreach (var itemGroup in root.ItemGroups)
+ foreach (var item in root.Items)
{
- if (itemGroup.Condition.Length != 0)
+ if (string.IsNullOrEmpty(item.Condition))
continue;
- foreach (var item in itemGroup.Items)
- {
- if (item.ItemType != itemType)
- continue;
-
- string normalizedInclude = item.Include.NormalizePath();
-
- var glob = Glob.Parse(normalizedInclude, globOptions);
+ if (item.ItemType != itemType)
+ continue;
- // TODO Check somehow if path has no blob to avoid the following loop...
+ string normalizedRemove = item.Remove.NormalizePath();
- foreach (var existingFile in existingFiles)
- {
- if (glob.IsMatch(existingFile))
- {
- result.Add(existingFile);
- }
- }
- }
+ var glob = MSBuildGlob.Parse(normalizedRemove);
+ excluded.AddRange(includedFiles.Where(includedFile => glob.IsMatch(includedFile)));
}
- return result.ToArray();
+ includedFiles.RemoveAll(f => excluded.Contains(f));
+
+ return includedFiles;
}
- /// Simple function to make sure the Api assembly references are configured correctly
- public static void FixApiHintPath(MSBuildProject project)
+ public static void MigrateToProjectSdksStyle(MSBuildProject project, string projectName)
{
- var root = project.Root;
-
- void AddPropertyIfNotPresent(string name, string condition, string value)
- {
- if (root.PropertyGroups
- .Any(g => (g.Condition == string.Empty || g.Condition.Trim() == condition) &&
- g.Properties
- .Any(p => p.Name == name &&
- p.Value == value &&
- (p.Condition.Trim() == condition || g.Condition.Trim() == condition))))
- {
- return;
- }
-
- root.AddProperty(name, value).Condition = " " + condition + " ";
- project.HasUnsavedChanges = true;
- }
-
- AddPropertyIfNotPresent(name: "ApiConfiguration",
- condition: "'$(Configuration)' != 'ExportRelease'",
- value: "Debug");
- AddPropertyIfNotPresent(name: "ApiConfiguration",
- condition: "'$(Configuration)' == 'ExportRelease'",
- value: "Release");
-
- void SetReferenceHintPath(string referenceName, string condition, string hintPath)
- {
- foreach (var itemGroup in root.ItemGroups.Where(g =>
- g.Condition.Trim() == string.Empty || g.Condition.Trim() == condition))
- {
- var references = itemGroup.Items.Where(item =>
- item.ItemType == "Reference" &&
- item.Include == referenceName &&
- (item.Condition.Trim() == condition || itemGroup.Condition.Trim() == 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);
- project.HasUnsavedChanges = true;
- return;
- }
-
- var referenceWithoutHintPath = references.FirstOrDefault();
- if (referenceWithoutHintPath != null)
- {
- // Found a Reference item without a HintPath
- referenceWithoutHintPath.AddMetadata("HintPath", hintPath);
- project.HasUnsavedChanges = true;
- return;
- }
- }
-
- // Found no Reference item at all. Add it.
- root.AddItem("Reference", referenceName).Condition = " " + condition + " ";
- project.HasUnsavedChanges = true;
- }
+ var origRoot = project.Root;
- const string coreProjectName = "GodotSharp";
- const string editorProjectName = "GodotSharpEditor";
-
- const string coreCondition = "";
- const string editorCondition = "'$(Configuration)' == 'Debug'";
-
- var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll";
- var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll";
+ if (!string.IsNullOrEmpty(origRoot.Sdk))
+ return;
- SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath);
- SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath);
+ project.Root = ProjectGenerator.GenGameProject(projectName);
+ project.Root.FullPath = origRoot.FullPath;
+ project.HasUnsavedChanges = true;
}
- public static void MigrateFromOldConfigNames(MSBuildProject project)
+ public static void EnsureGodotSdkIsUpToDate(MSBuildProject project)
{
var root = project.Root;
+ string godotSdkAttrValue = ProjectGenerator.GodotSdkAttrValue;
- bool hasGodotProjectGeneratorVersion = false;
- bool foundOldConfiguration = false;
-
- foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition == string.Empty))
- {
- if (!hasGodotProjectGeneratorVersion && propertyGroup.Properties.Any(p => p.Name == "GodotProjectGeneratorVersion"))
- hasGodotProjectGeneratorVersion = true;
-
- foreach (var configItem in propertyGroup.Properties
- .Where(p => p.Condition.Trim() == "'$(Configuration)' == ''" && p.Value == "Tools"))
- {
- configItem.Value = "Debug";
- foundOldConfiguration = true;
- project.HasUnsavedChanges = true;
- }
- }
-
- if (!hasGodotProjectGeneratorVersion)
- {
- root.PropertyGroups.First(g => g.Condition == string.Empty)?
- .AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());
- project.HasUnsavedChanges = true;
- }
-
- if (!foundOldConfiguration)
- {
- var toolsConditions = new[]
- {
- "'$(Configuration)|$(Platform)' == 'Tools|AnyCPU'",
- "'$(Configuration)|$(Platform)' != 'Tools|AnyCPU'",
- "'$(Configuration)' == 'Tools'",
- "'$(Configuration)' != 'Tools'"
- };
-
- foundOldConfiguration = root.PropertyGroups
- .Any(g => toolsConditions.Any(c => c == g.Condition.Trim()));
- }
-
- if (foundOldConfiguration)
- {
- void MigrateConfigurationConditions(string oldConfiguration, string newConfiguration)
- {
- void MigrateConditions(string oldCondition, string newCondition)
- {
- foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition.Trim() == oldCondition))
- {
- propertyGroup.Condition = " " + newCondition + " ";
- project.HasUnsavedChanges = true;
- }
-
- foreach (var propertyGroup in root.PropertyGroups)
- {
- foreach (var prop in propertyGroup.Properties.Where(p => p.Condition.Trim() == oldCondition))
- {
- prop.Condition = " " + newCondition + " ";
- project.HasUnsavedChanges = true;
- }
- }
-
- foreach (var itemGroup in root.ItemGroups.Where(g => g.Condition.Trim() == oldCondition))
- {
- itemGroup.Condition = " " + newCondition + " ";
- project.HasUnsavedChanges = true;
- }
-
- foreach (var itemGroup in root.ItemGroups)
- {
- foreach (var item in itemGroup.Items.Where(item => item.Condition.Trim() == oldCondition))
- {
- item.Condition = " " + newCondition + " ";
- project.HasUnsavedChanges = true;
- }
- }
- }
-
- foreach (var op in new[] {"==", "!="})
- {
- MigrateConditions($"'$(Configuration)|$(Platform)' {op} '{oldConfiguration}|AnyCPU'", $"'$(Configuration)|$(Platform)' {op} '{newConfiguration}|AnyCPU'");
- MigrateConditions($"'$(Configuration)' {op} '{oldConfiguration}'", $"'$(Configuration)' {op} '{newConfiguration}'");
- }
- }
+ if (!string.IsNullOrEmpty(root.Sdk) && root.Sdk.Trim().Equals(godotSdkAttrValue, StringComparison.OrdinalIgnoreCase))
+ return;
- MigrateConfigurationConditions("Debug", "ExportDebug");
- MigrateConfigurationConditions("Release", "ExportRelease");
- MigrateConfigurationConditions("Tools", "Debug"); // Must be last
- }
+ root.Sdk = godotSdkAttrValue;
+ project.HasUnsavedChanges = true;
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs
deleted file mode 100644
index 3a0464c9bc..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-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.ProjectEditor")]
-[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.ProjectEditor/packages.config b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config
deleted file mode 100644
index 2db030f9d8..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<packages>
- <package id="DotNet.Glob" version="2.1.1" targetFramework="net45" />
-</packages>
diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets
new file mode 100644
index 0000000000..1d382dcb43
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets
@@ -0,0 +1,36 @@
+<Project>
+ <!-- Generate C# file with the version of all the nupkgs bundled with Godot -->
+
+ <Target Name="SetPropertiesForGenerateGodotNupkgsVersions">
+ <PropertyGroup>
+ <GodotNETSdkPackageVersionFile>$(SolutionDir)..\Godot.NET.Sdk\Godot.NET.Sdk\Godot.NET.Sdk_PackageVersion.txt</GodotNETSdkPackageVersionFile>
+ <GeneratedGodotNupkgsVersionsFile>$(IntermediateOutputPath)GodotNupkgsVersions.g.cs</GeneratedGodotNupkgsVersionsFile>
+ </PropertyGroup>
+ </Target>
+
+ <Target Name="GenerateGodotNupkgsVersionsFile"
+ DependsOnTargets="PrepareForBuild;_GenerateGodotNupkgsVersionsFile"
+ BeforeTargets="BeforeCompile;CoreCompile">
+ <ItemGroup>
+ <Compile Include="$(GeneratedGodotNupkgsVersionsFile)" />
+ <FileWrites Include="$(GeneratedGodotNupkgsVersionsFile)" />
+ </ItemGroup>
+ </Target>
+ <Target Name="_GenerateGodotNupkgsVersionsFile"
+ DependsOnTargets="SetPropertiesForGenerateGodotNupkgsVersions"
+ Inputs="$(MSBuildProjectFile);@(GodotNETSdkPackageVersionFile)"
+ Outputs="$(GeneratedGodotNupkgsVersionsFile)">
+ <PropertyGroup>
+ <GenerateGodotNupkgsVersionsCode><![CDATA[
+namespace $(RootNamespace) {
+ public class GeneratedGodotNupkgsVersions {
+ public const string GodotNETSdk = "$([System.IO.File]::ReadAllText('$(GodotNETSdkPackageVersionFile)').Trim())"%3b
+ }
+}
+]]></GenerateGodotNupkgsVersionsCode>
+ </PropertyGroup>
+ <WriteLinesToFile Lines="$(GenerateGodotNupkgsVersionsCode)"
+ File="$(GeneratedGodotNupkgsVersionsFile)"
+ Overwrite="True" WriteOnlyWhenDifferent="True" />
+ </Target>
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj b/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj
new file mode 100644
index 0000000000..3bc1698c15
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GodotTools.Shared.csproj
@@ -0,0 +1,6 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ </PropertyGroup>
+ <Import Project="GenerateGodotNupkgsVersions.targets" />
+</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools.sln b/modules/mono/editor/GodotTools/GodotTools.sln
index a3438ea5f3..d3107a69db 100644
--- a/modules/mono/editor/GodotTools/GodotTools.sln
+++ b/modules/mono/editor/GodotTools/GodotTools.sln
@@ -9,7 +9,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.Core", "GodotToo
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.BuildLogger", "GodotTools.BuildLogger\GodotTools.BuildLogger.csproj", "{6CE9A984-37B1-4F8A-8FE9-609F05F071B3}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.IdeConnection", "GodotTools.IdeConnection\GodotTools.IdeConnection.csproj", "{92600954-25F0-4291-8E11-1FEE9FC4BE20}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.IdeMessaging", "GodotTools.IdeMessaging\GodotTools.IdeMessaging.csproj", "{92600954-25F0-4291-8E11-1FEE9FC4BE20}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.OpenVisualStudio", "GodotTools.OpenVisualStudio\GodotTools.OpenVisualStudio.csproj", "{EAFFF236-FA96-4A4D-BD23-0E51EF988277}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.Shared", "GodotTools.Shared\GodotTools.Shared.csproj", "{2758FFAF-8237-4CF2-B569-66BF8B3587BB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -37,5 +41,13 @@ Global
{92600954-25F0-4291-8E11-1FEE9FC4BE20}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92600954-25F0-4291-8E11-1FEE9FC4BE20}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92600954-25F0-4291-8E11-1FEE9FC4BE20}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EAFFF236-FA96-4A4D-BD23-0E51EF988277}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EAFFF236-FA96-4A4D-BD23-0E51EF988277}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EAFFF236-FA96-4A4D-BD23-0E51EF988277}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EAFFF236-FA96-4A4D-BD23-0E51EF988277}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2758FFAF-8237-4CF2-B569-66BF8B3587BB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
diff --git a/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs b/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs
deleted file mode 100644
index 3cf495f025..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/BottomPanel.cs
+++ /dev/null
@@ -1,343 +0,0 @@
-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 BottomPanel : 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 = (BuildTab)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 == BuildTab.BuildResults.Success ? "Succeeded" : "Errored";
- else
- itemTooltip += "Running";
-
- if (!tab.BuildExited || tab.BuildResult == BuildTab.BuildResults.Error)
- itemTooltip += $"\nErrors: {tab.ErrorCount}";
-
- itemTooltip += $"\nWarnings: {tab.WarningCount}";
-
- buildTabsList.SetItemTooltip(i, itemTooltip);
-
- if (noCurrentTab || currentTab == i)
- {
- buildTabsList.Select(i);
- _BuildTabsItemSelected(i);
- }
- }
- }
-
- public BuildTab GetBuildTabFor(BuildInfo buildInfo)
- {
- foreach (var buildTab in new Array<BuildTab>(buildTabs.GetChildren()))
- {
- if (buildTab.BuildInfo.Equals(buildInfo))
- return buildTab;
- }
-
- var newBuildTab = new BuildTab(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 = (BuildTab)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 = (BuildTab)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");
-
- CsProjOperations.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 = BuildManager.BuildProjectBlocking("Debug", godotDefines);
-
- if (!buildSuccess)
- return;
-
- // Notify running game for hot-reload
- Internal.EditorDebuggerNodeReloadScripts();
-
- // 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 = (BuildTab)buildTabs.GetTabControl(selectedItem);
-
- OS.ShellOpen(Path.Combine(buildTab.BuildInfo.LogsDirPath, BuildManager.MsBuildLogFileName));
- }
-
- public override void _Notification(int what)
- {
- base._Notification(what);
-
- if (what == EditorSettings.NotificationEditorSettingsChanged)
- {
- var editorBaseControl = editorInterface.GetBaseControl();
- panelTabs.AddThemeStyleboxOverride("panel", editorBaseControl.GetThemeStylebox("DebuggerPanel", "EditorStyles"));
- panelTabs.AddThemeStyleboxOverride("tab_fg", editorBaseControl.GetThemeStylebox("DebuggerTabFG", "EditorStyles"));
- panelTabs.AddThemeStyleboxOverride("tab_bg", editorBaseControl.GetThemeStylebox("DebuggerTabBG", "EditorStyles"));
- }
- }
-
- public void AddBuildTab(BuildTab buildTab)
- {
- buildTabs.AddChild(buildTab);
- RaiseBuildTab(buildTab);
- }
-
- public void RaiseBuildTab(BuildTab 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.AddThemeStyleboxOverride("panel", editorBaseControl.GetThemeStylebox("DebuggerPanel", "EditorStyles"));
- panelTabs.AddThemeStyleboxOverride("tab_fg", editorBaseControl.GetThemeStylebox("DebuggerTabFG", "EditorStyles"));
- panelTabs.AddThemeStyleboxOverride("tab_bg", editorBaseControl.GetThemeStylebox("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.PressedSignal += BuildProjectPressed;
- toolBarHBox.AddChild(buildProjectBtn);
-
- toolBarHBox.AddSpacer(begin: false);
-
- warningsBtn = new ToolButton
- {
- Text = "Warnings".TTR(),
- ToggleMode = true,
- Pressed = true,
- Visible = false,
- FocusMode = FocusModeEnum.None
- };
- warningsBtn.Toggled += _WarningsToggled;
- toolBarHBox.AddChild(warningsBtn);
-
- errorsBtn = new ToolButton
- {
- Text = "Errors".TTR(),
- ToggleMode = true,
- Pressed = true,
- Visible = false,
- FocusMode = FocusModeEnum.None
- };
- errorsBtn.Toggled += _ErrorsToggled;
- toolBarHBox.AddChild(errorsBtn);
-
- toolBarHBox.AddSpacer(begin: false);
-
- viewLogBtn = new Button
- {
- Text = "View log".TTR(),
- FocusMode = FocusModeEnum.None,
- Visible = false
- };
- viewLogBtn.PressedSignal += _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.ItemSelected += _BuildTabsItemSelected;
- buildTabsList.NothingSelected += _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/BuildInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs
index 70bd552f2f..51055dc9b9 100644
--- a/modules/mono/editor/GodotTools/GodotTools/BuildInfo.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs
@@ -4,13 +4,15 @@ using Godot.Collections;
using GodotTools.Internals;
using Path = System.IO.Path;
-namespace GodotTools
+namespace GodotTools.Build
{
[Serializable]
public sealed class BuildInfo : Reference // TODO Remove Reference once we have proper serialization
{
public string Solution { get; }
+ public string[] Targets { get; }
public string Configuration { get; }
+ public bool Restore { 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}");
@@ -18,7 +20,9 @@ namespace GodotTools
public override bool Equals(object obj)
{
if (obj is BuildInfo other)
- return other.Solution == Solution && other.Configuration == Configuration;
+ return other.Solution == Solution && other.Targets == Targets &&
+ other.Configuration == Configuration && other.Restore == Restore &&
+ other.CustomProperties == CustomProperties && other.LogsDirPath == LogsDirPath;
return false;
}
@@ -29,7 +33,11 @@ namespace GodotTools
{
int hash = 17;
hash = hash * 29 + Solution.GetHashCode();
+ hash = hash * 29 + Targets.GetHashCode();
hash = hash * 29 + Configuration.GetHashCode();
+ hash = hash * 29 + Restore.GetHashCode();
+ hash = hash * 29 + CustomProperties.GetHashCode();
+ hash = hash * 29 + LogsDirPath.GetHashCode();
return hash;
}
}
@@ -38,10 +46,12 @@ namespace GodotTools
{
}
- public BuildInfo(string solution, string configuration)
+ public BuildInfo(string solution, string[] targets, string configuration, bool restore)
{
Solution = solution;
+ Targets = targets;
Configuration = configuration;
+ Restore = restore;
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs
new file mode 100644
index 0000000000..b96b0c8175
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildManager.cs
@@ -0,0 +1,303 @@
+using System;
+using System.IO;
+using System.Threading.Tasks;
+using GodotTools.Ides.Rider;
+using GodotTools.Internals;
+using JetBrains.Annotations;
+using static GodotTools.Internals.Globals;
+using File = GodotTools.Utils.File;
+using OS = GodotTools.Utils.OS;
+
+namespace GodotTools.Build
+{
+ public static class BuildManager
+ {
+ private static BuildInfo _buildInProgress;
+
+ public const string PropNameMSBuildMono = "MSBuild (Mono)";
+ public const string PropNameMSBuildVs = "MSBuild (VS Build Tools)";
+ public const string PropNameMSBuildJetBrains = "MSBuild (JetBrains Rider)";
+ public const string PropNameDotnetCli = "dotnet CLI";
+
+ public const string MsBuildIssuesFileName = "msbuild_issues.csv";
+ public const string MsBuildLogFileName = "msbuild_log.txt";
+
+ public delegate void BuildLaunchFailedEventHandler(BuildInfo buildInfo, string reason);
+
+ public static event BuildLaunchFailedEventHandler BuildLaunchFailed;
+ public static event Action<BuildInfo> BuildStarted;
+ public static event Action<BuildResult> BuildFinished;
+ public static event Action<string> StdOutputReceived;
+ public static event Action<string> StdErrorReceived;
+
+ private static void RemoveOldIssuesFile(BuildInfo buildInfo)
+ {
+ var issuesFile = GetIssuesFilePath(buildInfo);
+
+ if (!File.Exists(issuesFile))
+ return;
+
+ File.Delete(issuesFile);
+ }
+
+ private static void ShowBuildErrorDialog(string message)
+ {
+ var plugin = GodotSharpEditor.Instance;
+ plugin.ShowErrorDialog(message, "Build error");
+ plugin.MakeBottomPanelItemVisible(plugin.MSBuildPanel);
+ }
+
+ public static void RestartBuild(BuildOutputView buildOutputView) => throw new NotImplementedException();
+ public static void StopBuild(BuildOutputView buildOutputView) => throw new NotImplementedException();
+
+ private static string GetLogFilePath(BuildInfo buildInfo)
+ {
+ return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName);
+ }
+
+ private static string GetIssuesFilePath(BuildInfo buildInfo)
+ {
+ return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName);
+ }
+
+ private static void PrintVerbose(string text)
+ {
+ if (Godot.OS.IsStdoutVerbose())
+ Godot.GD.Print(text);
+ }
+
+ public static bool Build(BuildInfo buildInfo)
+ {
+ if (_buildInProgress != null)
+ throw new InvalidOperationException("A build is already in progress");
+
+ _buildInProgress = buildInfo;
+
+ try
+ {
+ BuildStarted?.Invoke(buildInfo);
+
+ // Required in order to update the build tasks list
+ Internal.GodotMainIteration();
+
+ try
+ {
+ RemoveOldIssuesFile(buildInfo);
+ }
+ catch (IOException e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}");
+ Console.Error.WriteLine(e);
+ }
+
+ try
+ {
+ int exitCode = BuildSystem.Build(buildInfo, StdOutputReceived, StdErrorReceived);
+
+ if (exitCode != 0)
+ PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}");
+
+ BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error);
+
+ return exitCode == 0;
+ }
+ catch (Exception e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ finally
+ {
+ _buildInProgress = null;
+ }
+ }
+
+ public static async Task<bool> BuildAsync(BuildInfo buildInfo)
+ {
+ if (_buildInProgress != null)
+ throw new InvalidOperationException("A build is already in progress");
+
+ _buildInProgress = buildInfo;
+
+ try
+ {
+ BuildStarted?.Invoke(buildInfo);
+
+ try
+ {
+ RemoveOldIssuesFile(buildInfo);
+ }
+ catch (IOException e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo, $"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}");
+ Console.Error.WriteLine(e);
+ }
+
+ try
+ {
+ int exitCode = await BuildSystem.BuildAsync(buildInfo, StdOutputReceived, StdErrorReceived);
+
+ if (exitCode != 0)
+ PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}");
+
+ BuildFinished?.Invoke(exitCode == 0 ? BuildResult.Success : BuildResult.Error);
+
+ return exitCode == 0;
+ }
+ catch (Exception e)
+ {
+ BuildLaunchFailed?.Invoke(buildInfo, $"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ finally
+ {
+ _buildInProgress = null;
+ }
+ }
+
+ public static bool BuildProjectBlocking(string config, [CanBeNull] string[] targets = null, [CanBeNull] string platform = null)
+ {
+ var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, targets ?? new[] {"Build"}, config, restore: true);
+
+ // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it.
+ if (platform != null || OS.PlatformNameMap.TryGetValue(Godot.OS.GetName(), out platform))
+ buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}");
+
+ if (Internal.GodotIsRealTDouble())
+ buildInfo.CustomProperties.Add("GodotRealTIsDouble=true");
+
+ return BuildProjectBlocking(buildInfo);
+ }
+
+ private static bool BuildProjectBlocking(BuildInfo buildInfo)
+ {
+ if (!File.Exists(buildInfo.Solution))
+ return true; // No solution to build
+
+ // Make sure the API assemblies are up to date before building the project.
+ // We may not have had the chance to update the release API assemblies, and the debug ones
+ // may have been deleted by the user at some point after they were loaded by the Godot editor.
+ string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(buildInfo.Configuration == "ExportRelease" ? "Release" : "Debug");
+
+ if (!string.IsNullOrEmpty(apiAssembliesUpdateError))
+ {
+ ShowBuildErrorDialog("Failed to update the Godot API assemblies");
+ return false;
+ }
+
+ using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1))
+ {
+ pr.Step("Building project solution", 0);
+
+ 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
+
+ try
+ {
+ // Make sure our packages are added to the fallback folder
+ NuGetUtils.AddBundledPackagesToFallbackFolder(NuGetUtils.GodotFallbackFolderPath);
+ }
+ catch (Exception e)
+ {
+ Godot.GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
+ }
+
+ GenerateEditorScriptMetadata();
+
+ if (GodotSharpEditor.Instance.SkipBuildBeforePlaying)
+ return true; // Requested play from an external editor/IDE which already built the project
+
+ return BuildProjectBlocking("Debug");
+ }
+
+ // NOTE: This will be replaced with C# source generators in 4.0
+ public static void GenerateEditorScriptMetadata()
+ {
+ string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor");
+ string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player");
+
+ CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath);
+
+ if (!File.Exists(editorScriptsMetadataPath))
+ return;
+
+ try
+ {
+ File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath);
+ }
+ catch (IOException e)
+ {
+ throw new IOException("Failed to copy scripts metadata file.", innerException: e);
+ }
+ }
+
+ // NOTE: This will be replaced with C# source generators in 4.0
+ public static string GenerateExportedGameScriptMetadata(bool isDebug)
+ {
+ string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}");
+ CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath);
+ return scriptsMetadataPath;
+ }
+
+ public static void Initialize()
+ {
+ // Build tool settings
+ var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
+
+ BuildTool msbuildDefault;
+
+ if (OS.IsWindows)
+ {
+ if (RiderPathManager.IsExternalEditorSetToRider(editorSettings))
+ msbuildDefault = BuildTool.JetBrainsMsBuild;
+ else
+ msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildVs;
+ }
+ else
+ {
+ msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildMono;
+ }
+
+ EditorDef("mono/builds/build_tool", msbuildDefault);
+
+ string hintString;
+
+ if (OS.IsWindows)
+ {
+ hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," +
+ $"{PropNameMSBuildVs}:{(int)BuildTool.MsBuildVs}," +
+ $"{PropNameMSBuildJetBrains}:{(int)BuildTool.JetBrainsMsBuild}," +
+ $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}";
+ }
+ else
+ {
+ hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," +
+ $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}";
+ }
+
+ editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
+ {
+ ["type"] = Godot.Variant.Type.Int,
+ ["name"] = "mono/builds/build_tool",
+ ["hint"] = Godot.PropertyHint.Enum,
+ ["hint_string"] = hintString
+ });
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs
new file mode 100644
index 0000000000..1a1639aac7
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs
@@ -0,0 +1,417 @@
+using Godot;
+using System;
+using Godot.Collections;
+using GodotTools.Internals;
+using JetBrains.Annotations;
+using File = GodotTools.Utils.File;
+using Path = System.IO.Path;
+
+namespace GodotTools.Build
+{
+ public class BuildOutputView : VBoxContainer, ISerializationListener
+ {
+ [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;
+ private TextEdit buildLog;
+ private PopupMenu issuesListContextMenu;
+
+ private readonly object pendingBuildLogTextLock = new object();
+ [NotNull] private string pendingBuildLogText = string.Empty;
+
+ [Signal] public event Action BuildStateChanged;
+
+ public bool HasBuildExited { get; private set; } = false;
+
+ public BuildResult? 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 Texture2D BuildStateIcon
+ {
+ get
+ {
+ if (!HasBuildExited)
+ return GetThemeIcon("Stop", "EditorIcons");
+
+ if (BuildResult == Build.BuildResult.Error)
+ return GetThemeIcon("Error", "EditorIcons");
+
+ if (WarningCount > 1)
+ return GetThemeIcon("Warning", "EditorIcons");
+
+ return null;
+ }
+ }
+
+ private BuildInfo BuildInfo { get; set; }
+
+ public bool LogVisible
+ {
+ set => buildLog.Visible = value;
+ }
+
+ private void LoadIssuesFromFile(string csvFile)
+ {
+ using (var file = new Godot.File())
+ {
+ try
+ {
+ 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 && string.IsNullOrEmpty(csvColumns[0]))
+ 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);
+ }
+ }
+ finally
+ {
+ file.Close(); // Disposing it is not enough. We need to call Close()
+ }
+ }
+ }
+
+ 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)(long)issuesList.GetItemMetadata(idx);
+
+ if (issueIndex < 0 || issueIndex >= issues.Count)
+ throw new IndexOutOfRangeException("Issue index out of range");
+
+ BuildIssue issue = issues[issueIndex];
+
+ if (string.IsNullOrEmpty(issue.ProjectFile) && string.IsNullOrEmpty(issue.File))
+ 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 = GetThemeIcon("Warning", "EditorIcons"))
+ using (var errorIcon = GetThemeIcon("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 (!string.IsNullOrEmpty(issue.Code))
+ tooltip += $"\nCode: {issue.Code}";
+
+ tooltip += $"\nType: {(issue.Warning ? "warning" : "error")}";
+
+ string text = string.Empty;
+
+ if (!string.IsNullOrEmpty(issue.File))
+ {
+ text += $"{issue.File}({issue.Line},{issue.Column}): ";
+
+ tooltip += $"\nFile: {issue.File}";
+ tooltip += $"\nLine: {issue.Line}";
+ tooltip += $"\nColumn: {issue.Column}";
+ }
+
+ if (!string.IsNullOrEmpty(issue.ProjectFile))
+ 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);
+ }
+ }
+ }
+
+ private void BuildLaunchFailed(BuildInfo buildInfo, string cause)
+ {
+ HasBuildExited = true;
+ BuildResult = Build.BuildResult.Error;
+
+ issuesList.Clear();
+
+ var issue = new BuildIssue {Message = cause, Warning = false};
+
+ ErrorCount += 1;
+ issues.Add(issue);
+
+ UpdateIssuesList();
+
+ EmitSignal(nameof(BuildStateChanged));
+ }
+
+ private void BuildStarted(BuildInfo buildInfo)
+ {
+ BuildInfo = buildInfo;
+ HasBuildExited = false;
+
+ issues.Clear();
+ WarningCount = 0;
+ ErrorCount = 0;
+ buildLog.Text = string.Empty;
+
+ UpdateIssuesList();
+
+ EmitSignal(nameof(BuildStateChanged));
+ }
+
+ private void BuildFinished(BuildResult result)
+ {
+ HasBuildExited = true;
+ BuildResult = result;
+
+ LoadIssuesFromFile(Path.Combine(BuildInfo.LogsDirPath, BuildManager.MsBuildIssuesFileName));
+
+ UpdateIssuesList();
+
+ EmitSignal(nameof(BuildStateChanged));
+ }
+
+ private void UpdateBuildLogText()
+ {
+ lock (pendingBuildLogTextLock)
+ {
+ buildLog.Text += pendingBuildLogText;
+ pendingBuildLogText = string.Empty;
+ ScrollToLastNonEmptyLogLine();
+ }
+ }
+
+ private void StdOutputReceived(string text)
+ {
+ lock (pendingBuildLogTextLock)
+ {
+ if (pendingBuildLogText.Length == 0)
+ CallDeferred(nameof(UpdateBuildLogText));
+ pendingBuildLogText += text + "\n";
+ }
+ }
+
+ private void StdErrorReceived(string text)
+ {
+ lock (pendingBuildLogTextLock)
+ {
+ if (pendingBuildLogText.Length == 0)
+ CallDeferred(nameof(UpdateBuildLogText));
+ pendingBuildLogText += text + "\n";
+ }
+ }
+
+ private void ScrollToLastNonEmptyLogLine()
+ {
+ int line;
+ for (line = buildLog.GetLineCount(); line > 0; line--)
+ {
+ string lineText = buildLog.GetLine(line);
+
+ if (!string.IsNullOrEmpty(lineText) || !string.IsNullOrEmpty(lineText?.Trim()))
+ break;
+ }
+
+ buildLog.CursorSetLine(line);
+ }
+
+ public void RestartBuild()
+ {
+ if (!HasBuildExited)
+ throw new InvalidOperationException("Build already started");
+
+ BuildManager.RestartBuild(this);
+ }
+
+ public void StopBuild()
+ {
+ if (!HasBuildExited)
+ throw new InvalidOperationException("Build is not in progress");
+
+ BuildManager.StopBuild(this);
+ }
+
+ private enum IssuesContextMenuOption
+ {
+ Copy
+ }
+
+ private void IssuesListContextOptionPressed(int id)
+ {
+ switch ((IssuesContextMenuOption)id)
+ {
+ case IssuesContextMenuOption.Copy:
+ {
+ // We don't allow multi-selection but just in case that changes later...
+ string text = null;
+
+ foreach (int issueIndex in issuesList.GetSelectedItems())
+ {
+ if (text != null)
+ text += "\n";
+ text += issuesList.GetItemText(issueIndex);
+ }
+
+ if (text != null)
+ DisplayServer.ClipboardSet(text);
+ break;
+ }
+ default:
+ throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid issue context menu option");
+ }
+ }
+
+ private void IssuesListRmbSelected(int index, Vector2 atPosition)
+ {
+ _ = index; // Unused
+
+ issuesListContextMenu.Clear();
+ issuesListContextMenu.Size = new Vector2i(1, 1);
+
+ if (issuesList.IsAnythingSelected())
+ {
+ // Add menu entries for the selected item
+ issuesListContextMenu.AddIconItem(GetThemeIcon("ActionCopy", "EditorIcons"),
+ label: "Copy Error".TTR(), (int)IssuesContextMenuOption.Copy);
+ }
+
+ if (issuesListContextMenu.GetItemCount() > 0)
+ {
+ issuesListContextMenu.Position = (Vector2i)(issuesList.RectGlobalPosition + atPosition);
+ issuesListContextMenu.Popup();
+ }
+ }
+
+ public override void _Ready()
+ {
+ base._Ready();
+
+ SizeFlagsVertical = (int)SizeFlags.ExpandFill;
+
+ var hsc = new HSplitContainer
+ {
+ SizeFlagsHorizontal = (int)SizeFlags.ExpandFill,
+ SizeFlagsVertical = (int)SizeFlags.ExpandFill
+ };
+ AddChild(hsc);
+
+ issuesList = new ItemList
+ {
+ SizeFlagsVertical = (int)SizeFlags.ExpandFill,
+ SizeFlagsHorizontal = (int)SizeFlags.ExpandFill // Avoid being squashed by the build log
+ };
+ issuesList.ItemActivated += IssueActivated;
+ issuesList.AllowRmbSelect = true;
+ issuesList.ItemRmbSelected += IssuesListRmbSelected;
+ hsc.AddChild(issuesList);
+
+ issuesListContextMenu = new PopupMenu();
+ issuesListContextMenu.IdPressed += IssuesListContextOptionPressed;
+ issuesList.AddChild(issuesListContextMenu);
+
+ buildLog = new TextEdit
+ {
+ Readonly = true,
+ SizeFlagsVertical = (int)SizeFlags.ExpandFill,
+ SizeFlagsHorizontal = (int)SizeFlags.ExpandFill // Avoid being squashed by the issues list
+ };
+ hsc.AddChild(buildLog);
+
+ AddBuildEventListeners();
+ }
+
+ private void AddBuildEventListeners()
+ {
+ BuildManager.BuildLaunchFailed += BuildLaunchFailed;
+ BuildManager.BuildStarted += BuildStarted;
+ BuildManager.BuildFinished += BuildFinished;
+ // StdOutput/Error can be received from different threads, so we need to use CallDeferred
+ BuildManager.StdOutputReceived += StdOutputReceived;
+ BuildManager.StdErrorReceived += StdErrorReceived;
+ }
+
+ public void OnBeforeSerialize()
+ {
+ // In case it didn't update yet. We don't want to have to serialize any pending output.
+ UpdateBuildLogText();
+ }
+
+ public void OnAfterDeserialize()
+ {
+ AddBuildEventListeners(); // Re-add them
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildResult.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildResult.cs
new file mode 100644
index 0000000000..59055b60c3
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildResult.cs
@@ -0,0 +1,8 @@
+namespace GodotTools.Build
+{
+ public enum BuildResult
+ {
+ Error,
+ Success
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
index 43c96d2e30..bac7a2e6db 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
@@ -14,16 +14,6 @@ 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
@@ -46,35 +36,32 @@ namespace GodotTools.Build
{
if (OS.IsWindows)
{
- return (BuildManager.BuildTool)EditorSettings.GetSetting("mono/builds/build_tool")
- == BuildManager.BuildTool.MsBuildMono;
+ return (BuildTool)EditorSettings.GetSetting("mono/builds/build_tool")
+ == 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)
+ private static Process LaunchBuild(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
{
- var customPropertiesList = new List<string>();
-
- if (customProperties != null)
- customPropertiesList.AddRange(customProperties);
+ (string msbuildPath, BuildTool buildTool) = MsBuildFinder.FindMsBuild();
- string compilerArgs = BuildArguments(solution, config, loggerOutputDir, customPropertiesList);
+ if (msbuildPath == null)
+ throw new FileNotFoundException("Cannot find the MSBuild executable.");
- var startInfo = new ProcessStartInfo(GetMsBuildPath(), compilerArgs);
+ string compilerArgs = BuildArguments(buildTool, buildInfo);
- bool redirectOutput = !IsDebugMsBuildRequested() && !PrintBuildOutput;
+ var startInfo = new ProcessStartInfo(msbuildPath, compilerArgs);
- if (!redirectOutput || Godot.OS.IsStdoutVerbose())
- Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}");
+ string launchMessage = $"Running: \"{startInfo.FileName}\" {startInfo.Arguments}";
+ stdOutHandler?.Invoke(launchMessage);
+ if (Godot.OS.IsStdoutVerbose())
+ Console.WriteLine(launchMessage);
- startInfo.RedirectStandardOutput = redirectOutput;
- startInfo.RedirectStandardError = redirectOutput;
+ startInfo.RedirectStandardOutput = true;
+ startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
if (UsingMonoMsBuildOnWindows)
@@ -90,34 +77,24 @@ namespace GodotTools.Build
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
- var process = new Process { StartInfo = startInfo };
+ var process = new Process {StartInfo = startInfo};
+
+ if (stdOutHandler != null)
+ process.OutputDataReceived += (s, e) => stdOutHandler.Invoke(e.Data);
+ if (stdErrHandler != null)
+ process.ErrorDataReceived += (s, e) => stdErrHandler.Invoke(e.Data);
process.Start();
- if (redirectOutput)
- {
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
- }
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
return process;
}
- public static int Build(BuildInfo buildInfo)
+ public static int Build(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
{
- return Build(buildInfo.Solution, buildInfo.Configuration,
- buildInfo.LogsDirPath, buildInfo.CustomProperties);
- }
-
- public static async Task<int> BuildAsync(BuildInfo buildInfo)
- {
- return await BuildAsync(buildInfo.Solution, buildInfo.Configuration,
- buildInfo.LogsDirPath, buildInfo.CustomProperties);
- }
-
- public static int Build(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null)
- {
- using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties))
+ using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
{
process.WaitForExit();
@@ -125,9 +102,9 @@ namespace GodotTools.Build
}
}
- public static async Task<int> BuildAsync(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null)
+ public static async Task<int> BuildAsync(BuildInfo buildInfo, Action<string> stdOutHandler, Action<string> stdErrHandler)
{
- using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties))
+ using (var process = LaunchBuild(buildInfo, stdOutHandler, stdErrHandler))
{
await process.WaitForExitAsync();
@@ -135,12 +112,23 @@ namespace GodotTools.Build
}
}
- private static string BuildArguments(string solution, string config, string loggerOutputDir, List<string> customProperties)
+ private static string BuildArguments(BuildTool buildTool, BuildInfo buildInfo)
{
- string arguments = $@"""{solution}"" /v:normal /t:Build ""/p:{"Configuration=" + config}"" " +
- $@"""/l:{typeof(GodotBuildLogger).FullName},{GodotBuildLogger.AssemblyPath};{loggerOutputDir}""";
+ string arguments = string.Empty;
+
+ if (buildTool == BuildTool.DotnetCli)
+ arguments += "msbuild"; // `dotnet msbuild` command
- foreach (string customProperty in customProperties)
+ arguments += $@" ""{buildInfo.Solution}""";
+
+ if (buildInfo.Restore)
+ arguments += " /restore";
+
+ arguments += $@" /t:{string.Join(",", buildInfo.Targets)} " +
+ $@"""/p:{"Configuration=" + buildInfo.Configuration}"" /v:normal " +
+ $@"""/l:{typeof(GodotBuildLogger).FullName},{GodotBuildLogger.AssemblyPath};{buildInfo.LogsDirPath}""";
+
+ foreach (string customProperty in buildInfo.CustomProperties)
{
arguments += " /p:" + customProperty;
}
@@ -163,10 +151,5 @@ namespace GodotTools.Build
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/BuildTool.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs
new file mode 100644
index 0000000000..837c8adddb
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildTool.cs
@@ -0,0 +1,10 @@
+namespace GodotTools.Build
+{
+ public enum BuildTool : long
+ {
+ MsBuildMono,
+ MsBuildVs,
+ JetBrainsMsBuild,
+ DotnetCli
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs
new file mode 100644
index 0000000000..708ec73454
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs
@@ -0,0 +1,185 @@
+using System;
+using Godot;
+using GodotTools.Internals;
+using JetBrains.Annotations;
+using static GodotTools.Internals.Globals;
+using File = GodotTools.Utils.File;
+
+namespace GodotTools.Build
+{
+ public class MSBuildPanel : VBoxContainer
+ {
+ public BuildOutputView BuildOutputView { get; private set; }
+
+ private Button errorsBtn;
+ private Button warningsBtn;
+ private Button viewLogBtn;
+
+ private void WarningsToggled(bool pressed)
+ {
+ BuildOutputView.WarningsVisible = pressed;
+ BuildOutputView.UpdateIssuesList();
+ }
+
+ private void ErrorsToggled(bool pressed)
+ {
+ BuildOutputView.ErrorsVisible = pressed;
+ BuildOutputView.UpdateIssuesList();
+ }
+
+ [UsedImplicitly]
+ public void BuildSolution()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return; // No solution to build
+
+ try
+ {
+ // Make sure our packages are added to the fallback folder
+ NuGetUtils.AddBundledPackagesToFallbackFolder(NuGetUtils.GodotFallbackFolderPath);
+ }
+ catch (Exception e)
+ {
+ GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
+ }
+
+ BuildManager.GenerateEditorScriptMetadata();
+
+ if (!BuildManager.BuildProjectBlocking("Debug"))
+ return; // Build failed
+
+ // Notify running game for hot-reload
+ Internal.EditorDebuggerNodeReloadScripts();
+
+ // Hot-reload in the editor
+ GodotSharpEditor.Instance.GetNode<HotReloadAssemblyWatcher>("HotReloadAssemblyWatcher").RestartTimer();
+
+ if (Internal.IsAssembliesReloadingNeeded())
+ Internal.ReloadAssemblies(softReload: false);
+ }
+
+ [UsedImplicitly]
+ private void RebuildSolution()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return; // No solution to build
+
+ try
+ {
+ // Make sure our packages are added to the fallback folder
+ NuGetUtils.AddBundledPackagesToFallbackFolder(NuGetUtils.GodotFallbackFolderPath);
+ }
+ catch (Exception e)
+ {
+ GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message);
+ }
+
+ BuildManager.GenerateEditorScriptMetadata();
+
+ if (!BuildManager.BuildProjectBlocking("Debug", targets: new[] {"Rebuild"}))
+ return; // Build failed
+
+ // Notify running game for hot-reload
+ Internal.EditorDebuggerNodeReloadScripts();
+
+ // Hot-reload in the editor
+ GodotSharpEditor.Instance.GetNode<HotReloadAssemblyWatcher>("HotReloadAssemblyWatcher").RestartTimer();
+
+ if (Internal.IsAssembliesReloadingNeeded())
+ Internal.ReloadAssemblies(softReload: false);
+ }
+
+ [UsedImplicitly]
+ private void CleanSolution()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return; // No solution to build
+
+ BuildManager.BuildProjectBlocking("Debug", targets: new[] {"Clean"});
+ }
+
+ private void ViewLogToggled(bool pressed) => BuildOutputView.LogVisible = pressed;
+
+ private void BuildMenuOptionPressed(int id)
+ {
+ switch ((BuildMenuOptions)id)
+ {
+ case BuildMenuOptions.BuildSolution:
+ BuildSolution();
+ break;
+ case BuildMenuOptions.RebuildSolution:
+ RebuildSolution();
+ break;
+ case BuildMenuOptions.CleanSolution:
+ CleanSolution();
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid build menu option");
+ }
+ }
+
+ private enum BuildMenuOptions
+ {
+ BuildSolution,
+ RebuildSolution,
+ CleanSolution
+ }
+
+ public override void _Ready()
+ {
+ base._Ready();
+
+ RectMinSize = new Vector2(0, 228) * EditorScale;
+ SizeFlagsVertical = (int)SizeFlags.ExpandFill;
+
+ var toolBarHBox = new HBoxContainer {SizeFlagsHorizontal = (int)SizeFlags.ExpandFill};
+ AddChild(toolBarHBox);
+
+ var buildMenuBtn = new MenuButton {Text = "Build", Icon = GetThemeIcon("Play", "EditorIcons")};
+ toolBarHBox.AddChild(buildMenuBtn);
+
+ var buildMenu = buildMenuBtn.GetPopup();
+ buildMenu.AddItem("Build Solution".TTR(), (int)BuildMenuOptions.BuildSolution);
+ buildMenu.AddItem("Rebuild Solution".TTR(), (int)BuildMenuOptions.RebuildSolution);
+ buildMenu.AddItem("Clean Solution".TTR(), (int)BuildMenuOptions.CleanSolution);
+ buildMenu.IdPressed += BuildMenuOptionPressed;
+
+ errorsBtn = new Button
+ {
+ HintTooltip = "Show Errors".TTR(),
+ Icon = GetThemeIcon("StatusError", "EditorIcons"),
+ ExpandIcon = false,
+ ToggleMode = true,
+ Pressed = true,
+ FocusMode = FocusModeEnum.None
+ };
+ errorsBtn.Toggled += ErrorsToggled;
+ toolBarHBox.AddChild(errorsBtn);
+
+ warningsBtn = new Button
+ {
+ HintTooltip = "Show Warnings".TTR(),
+ Icon = GetThemeIcon("NodeWarning", "EditorIcons"),
+ ExpandIcon = false,
+ ToggleMode = true,
+ Pressed = true,
+ FocusMode = FocusModeEnum.None
+ };
+ warningsBtn.Toggled += WarningsToggled;
+ toolBarHBox.AddChild(warningsBtn);
+
+ viewLogBtn = new Button
+ {
+ Text = "Show Output".TTR(),
+ ToggleMode = true,
+ Pressed = true,
+ FocusMode = FocusModeEnum.None
+ };
+ viewLogBtn.Toggled += ViewLogToggled;
+ toolBarHBox.AddChild(viewLogBtn);
+
+ BuildOutputView = new BuildOutputView();
+ AddChild(BuildOutputView);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
index af8d070cbd..5ef55fea49 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
@@ -17,75 +17,96 @@ namespace GodotTools.Build
private static string _msbuildToolsPath = string.Empty;
private static string _msbuildUnixPath = string.Empty;
- public static string FindMsBuild()
+ public static (string, BuildTool) FindMsBuild()
{
var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
- var buildTool = (BuildManager.BuildTool)editorSettings.GetSetting("mono/builds/build_tool");
+ var buildTool = (BuildTool)editorSettings.GetSetting("mono/builds/build_tool");
if (OS.IsWindows)
{
switch (buildTool)
{
- case BuildManager.BuildTool.MsBuildVs:
+ case BuildTool.DotnetCli:
{
- if (_msbuildToolsPath.Empty() || !File.Exists(_msbuildToolsPath))
+ string dotnetCliPath = OS.PathWhich("dotnet");
+ if (!string.IsNullOrEmpty(dotnetCliPath))
+ return (dotnetCliPath, BuildTool.DotnetCli);
+ GD.PushError($"Cannot find executable for '{BuildManager.PropNameDotnetCli}'. Fallback to MSBuild from Visual Studio.");
+ goto case BuildTool.MsBuildVs;
+ }
+ case BuildTool.MsBuildVs:
+ {
+ if (string.IsNullOrEmpty(_msbuildToolsPath) || !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 '{BuildManager.PropNameMsbuildVs}'.");
- }
+ if (string.IsNullOrEmpty(_msbuildToolsPath))
+ throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildVs}'.");
}
if (!_msbuildToolsPath.EndsWith("\\"))
_msbuildToolsPath += "\\";
- return Path.Combine(_msbuildToolsPath, "MSBuild.exe");
+ return (Path.Combine(_msbuildToolsPath, "MSBuild.exe"), BuildTool.MsBuildVs);
}
- case BuildManager.BuildTool.MsBuildMono:
+ case BuildTool.MsBuildMono:
{
string msbuildPath = Path.Combine(Internal.MonoWindowsInstallRoot, "bin", "msbuild.bat");
if (!File.Exists(msbuildPath))
- {
- throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMsbuildMono}'. Tried with path: {msbuildPath}");
- }
+ throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildMono}'. Tried with path: {msbuildPath}");
- return msbuildPath;
+ return (msbuildPath, BuildTool.MsBuildMono);
}
- case BuildManager.BuildTool.JetBrainsMsBuild:
+ case BuildTool.JetBrainsMsBuild:
+ {
var editorPath = (string)editorSettings.GetSetting(RiderPathManager.EditorPathSettingName);
+
if (!File.Exists(editorPath))
throw new FileNotFoundException($"Cannot find Rider executable. Tried with path: {editorPath}");
- var riderDir = new FileInfo(editorPath).Directory.Parent;
- return Path.Combine(riderDir.FullName, @"tools\MSBuild\Current\Bin\MSBuild.exe");
+
+ var riderDir = new FileInfo(editorPath).Directory?.Parent;
+
+ string msbuildPath = Path.Combine(riderDir.FullName, @"tools\MSBuild\Current\Bin\MSBuild.exe");
+
+ if (!File.Exists(msbuildPath))
+ throw new FileNotFoundException($"Cannot find executable for '{BuildManager.PropNameMSBuildJetBrains}'. Tried with path: {msbuildPath}");
+
+ return (msbuildPath, BuildTool.JetBrainsMsBuild);
+ }
default:
throw new IndexOutOfRangeException("Invalid build tool in editor settings");
}
}
- if (OS.IsUnixLike())
+ if (OS.IsUnixLike)
{
- if (buildTool == BuildManager.BuildTool.MsBuildMono)
+ switch (buildTool)
{
- if (_msbuildUnixPath.Empty() || !File.Exists(_msbuildUnixPath))
+ case BuildTool.DotnetCli:
{
- // Try to search it again if it wasn't found last time or if it was removed from its location
- _msbuildUnixPath = FindBuildEngineOnUnix("msbuild");
+ string dotnetCliPath = OS.PathWhich("dotnet");
+ if (!string.IsNullOrEmpty(dotnetCliPath))
+ return (dotnetCliPath, BuildTool.DotnetCli);
+ GD.PushError($"Cannot find executable for '{BuildManager.PropNameDotnetCli}'. Fallback to MSBuild from Mono.");
+ goto case BuildTool.MsBuildMono;
}
-
- if (_msbuildUnixPath.Empty())
+ case BuildTool.MsBuildMono:
{
- throw new FileNotFoundException($"Cannot find binary for '{BuildManager.PropNameMsbuildMono}'");
- }
+ if (string.IsNullOrEmpty(_msbuildUnixPath) || !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");
+ }
- return _msbuildUnixPath;
- }
- else
- {
- throw new IndexOutOfRangeException("Invalid build tool in editor settings");
+ if (string.IsNullOrEmpty(_msbuildUnixPath))
+ throw new FileNotFoundException($"Cannot find binary for '{BuildManager.PropNameMSBuildMono}'");
+
+ return (_msbuildUnixPath, BuildTool.MsBuildMono);
+ }
+ default:
+ throw new IndexOutOfRangeException("Invalid build tool in editor settings");
}
}
@@ -98,7 +119,7 @@ namespace GodotTools.Build
{
var result = new List<string>();
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
result.Add("/Library/Frameworks/Mono.framework/Versions/Current/bin/");
result.Add("/usr/local/var/homebrew/linked/mono/bin/");
@@ -114,12 +135,12 @@ namespace GodotTools.Build
{
string ret = OS.PathWhich(name);
- if (!ret.Empty())
+ if (!string.IsNullOrEmpty(ret))
return ret;
string retFallback = OS.PathWhich($"{name}.exe");
- if (!retFallback.Empty())
+ if (!string.IsNullOrEmpty(retFallback))
return retFallback;
foreach (string hintDir in MsBuildHintDirs)
@@ -140,14 +161,27 @@ namespace GodotTools.Build
// Try to find 15.0 with vswhere
- string vsWherePath = Environment.GetEnvironmentVariable(Internal.GodotIs32Bits() ? "ProgramFiles" : "ProgramFiles(x86)");
- vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
+ var envNames = Internal.GodotIs32Bits() ? new[] {"ProgramFiles", "ProgramW6432"} : new[] {"ProgramFiles(x86)", "ProgramFiles"};
+
+ string vsWherePath = null;
+ foreach (var envName in envNames)
+ {
+ vsWherePath = Environment.GetEnvironmentVariable(envName);
+ if (!string.IsNullOrEmpty(vsWherePath))
+ {
+ vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
+ if (File.Exists(vsWherePath))
+ break;
+ }
+
+ vsWherePath = null;
+ }
- var vsWhereArgs = new[] { "-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild" };
+ 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);
+ output: (Godot.Collections.Array)outputArray);
if (exitCode != 0)
return string.Empty;
@@ -171,7 +205,7 @@ namespace GodotTools.Build
string value = line.Substring(sepIdx + 1).StripEdges();
- if (value.Empty())
+ if (string.IsNullOrEmpty(value))
throw new FormatException("installationPath value is empty");
if (!value.EndsWith("\\"))
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs
new file mode 100644
index 0000000000..793ef7fd71
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs
@@ -0,0 +1,296 @@
+using System;
+using System.IO;
+using System.IO.Compression;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using System.Xml;
+using Godot;
+using GodotTools.Internals;
+using GodotTools.Shared;
+using Directory = GodotTools.Utils.Directory;
+using Environment = System.Environment;
+using File = GodotTools.Utils.File;
+
+namespace GodotTools.Build
+{
+ public static class NuGetUtils
+ {
+ public const string GodotFallbackFolderName = "Godot Offline Packages";
+
+ public static string GodotFallbackFolderPath
+ => Path.Combine(GodotSharpDirs.MonoUserDir, "GodotNuGetFallbackFolder");
+
+ private static void AddFallbackFolderToNuGetConfig(string nuGetConfigPath, string name, string path)
+ {
+ var xmlDoc = new XmlDocument();
+ xmlDoc.Load(nuGetConfigPath);
+
+ const string nuGetConfigRootName = "configuration";
+
+ var rootNode = xmlDoc.DocumentElement;
+
+ if (rootNode == null)
+ {
+ // No root node, create it
+ rootNode = xmlDoc.CreateElement(nuGetConfigRootName);
+ xmlDoc.AppendChild(rootNode);
+
+ // Since this can be considered pretty much a new NuGet.Config, add the default nuget.org source as well
+ XmlElement nugetOrgSourceEntry = xmlDoc.CreateElement("add");
+ nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = "nuget.org";
+ nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = "https://api.nuget.org/v3/index.json";
+ nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("protocolVersion")).Value = "3";
+ rootNode.AppendChild(xmlDoc.CreateElement("packageSources")).AppendChild(nugetOrgSourceEntry);
+ }
+ else
+ {
+ // Check that the root node is the expected one
+ if (rootNode.Name != nuGetConfigRootName)
+ throw new Exception("Invalid root Xml node for NuGet.Config. " +
+ $"Expected '{nuGetConfigRootName}' got '{rootNode.Name}'.");
+ }
+
+ var fallbackFoldersNode = rootNode["fallbackPackageFolders"] ??
+ rootNode.AppendChild(xmlDoc.CreateElement("fallbackPackageFolders"));
+
+ // Check if it already has our fallback package folder
+ for (var xmlNode = fallbackFoldersNode.FirstChild; xmlNode != null; xmlNode = xmlNode.NextSibling)
+ {
+ if (xmlNode.NodeType != XmlNodeType.Element)
+ continue;
+
+ var xmlElement = (XmlElement)xmlNode;
+ if (xmlElement.Name == "add" &&
+ xmlElement.Attributes["key"]?.Value == name &&
+ xmlElement.Attributes["value"]?.Value == path)
+ {
+ return;
+ }
+ }
+
+ XmlElement newEntry = xmlDoc.CreateElement("add");
+ newEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = name;
+ newEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = path;
+
+ fallbackFoldersNode.AppendChild(newEntry);
+
+ xmlDoc.Save(nuGetConfigPath);
+ }
+
+ /// <summary>
+ /// Returns all the paths where the user NuGet.Config files can be found.
+ /// Does not determine whether the returned files exist or not.
+ /// </summary>
+ private static string[] GetAllUserNuGetConfigFilePaths()
+ {
+ // Where to find 'NuGet/NuGet.Config':
+ //
+ // - Mono/.NETFramework (standalone NuGet):
+ // Uses Environment.SpecialFolder.ApplicationData
+ // - Windows: '%APPDATA%'
+ // - Linux/macOS: '$HOME/.config'
+ // - CoreCLR (dotnet CLI NuGet):
+ // - Windows: '%APPDATA%'
+ // - Linux/macOS: '$DOTNET_CLI_HOME/.nuget' otherwise '$HOME/.nuget'
+
+ string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
+
+ if (Utils.OS.IsWindows)
+ {
+ // %APPDATA% for both
+ return new[] {Path.Combine(applicationData, "NuGet", "NuGet.Config")};
+ }
+
+ var paths = new string[2];
+
+ // CoreCLR (dotnet CLI NuGet)
+
+ string dotnetCliHome = Environment.GetEnvironmentVariable("DOTNET_CLI_HOME");
+ if (!string.IsNullOrEmpty(dotnetCliHome))
+ {
+ paths[0] = Path.Combine(dotnetCliHome, ".nuget", "NuGet", "NuGet.Config");
+ }
+ else
+ {
+ string home = Environment.GetEnvironmentVariable("HOME");
+ if (string.IsNullOrEmpty(home))
+ throw new InvalidOperationException("Required environment variable 'HOME' is not set.");
+ paths[0] = Path.Combine(home, ".nuget", "NuGet", "NuGet.Config");
+ }
+
+ // Mono/.NETFramework (standalone NuGet)
+
+ // ApplicationData is $HOME/.config on Linux/macOS
+ paths[1] = Path.Combine(applicationData, "NuGet", "NuGet.Config");
+
+ return paths;
+ }
+
+ // nupkg extraction
+ //
+ // Exclude: (NuGet.Client -> NuGet.Packaging.PackageHelper.ExcludePaths)
+ // package/
+ // _rels/
+ // [Content_Types].xml
+ //
+ // Don't ignore files that begin with a dot (.)
+ //
+ // The nuspec is not lower case inside the nupkg but must be made lower case when extracted.
+
+ /// <summary>
+ /// Adds the specified fallback folder to the user NuGet.Config files,
+ /// for both standalone NuGet (Mono/.NETFramework) and dotnet CLI NuGet.
+ /// </summary>
+ public static void AddFallbackFolderToUserNuGetConfigs(string name, string path)
+ {
+ foreach (string nuGetConfigPath in GetAllUserNuGetConfigFilePaths())
+ {
+ if (!System.IO.File.Exists(nuGetConfigPath))
+ {
+ // It doesn't exist, so we create a default one
+ const string defaultConfig = @"<?xml version=""1.0"" encoding=""utf-8""?>
+<configuration>
+ <packageSources>
+ <add key=""nuget.org"" value=""https://api.nuget.org/v3/index.json"" protocolVersion=""3"" />
+ </packageSources>
+</configuration>
+";
+ System.IO.File.WriteAllText(nuGetConfigPath, defaultConfig, Encoding.UTF8); // UTF-8 with BOM
+ }
+
+ AddFallbackFolderToNuGetConfig(nuGetConfigPath, name, path);
+ }
+ }
+
+ private static void AddPackageToFallbackFolder(string fallbackFolder,
+ string nupkgPath, string packageId, string packageVersion)
+ {
+ // dotnet CLI provides no command for this, but we can do it manually.
+ //
+ // - The expected structure is as follows:
+ // fallback_folder/
+ // <package.name>/<version>/
+ // <package.name>.<version>.nupkg
+ // <package.name>.<version>.nupkg.sha512
+ // <package.name>.nuspec
+ // ... extracted nupkg files (check code for excluded files) ...
+ //
+ // - <package.name> and <version> must be in lower case.
+ // - The sha512 of the nupkg is base64 encoded.
+ // - We can get the nuspec from the nupkg which is a Zip file.
+
+ string packageIdLower = packageId.ToLower();
+ string packageVersionLower = packageVersion.ToLower();
+
+ string destDir = Path.Combine(fallbackFolder, packageIdLower, packageVersionLower);
+ string nupkgDestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg");
+ string nupkgSha512DestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg.sha512");
+
+ if (File.Exists(nupkgDestPath) && File.Exists(nupkgSha512DestPath))
+ return; // Already added (for speed we don't check if every file is properly extracted)
+
+ Directory.CreateDirectory(destDir);
+
+ // Generate .nupkg.sha512 file
+
+ using (var alg = SHA512.Create())
+ {
+ alg.ComputeHash(File.ReadAllBytes(nupkgPath));
+ string base64Hash = Convert.ToBase64String(alg.Hash);
+ File.WriteAllText(nupkgSha512DestPath, base64Hash);
+ }
+
+ // Extract nupkg
+ ExtractNupkg(destDir, nupkgPath, packageId, packageVersion);
+
+ // Copy .nupkg
+ File.Copy(nupkgPath, nupkgDestPath);
+ }
+
+ private static readonly string[] NupkgExcludePaths =
+ {
+ "_rels/",
+ "package/",
+ "[Content_Types].xml"
+ };
+
+ private static void ExtractNupkg(string destDir, string nupkgPath, string packageId, string packageVersion)
+ {
+ // NOTE: Must use SimplifyGodotPath to make sure we don't extract files outside the destination directory.
+
+ using (var archive = ZipFile.OpenRead(nupkgPath))
+ {
+ // Extract .nuspec manually as it needs to be in lower case
+
+ var nuspecEntry = archive.GetEntry(packageId + ".nuspec");
+
+ if (nuspecEntry == null)
+ throw new InvalidOperationException($"Failed to extract package {packageId}.{packageVersion}. Could not find the nuspec file.");
+
+ nuspecEntry.ExtractToFile(Path.Combine(destDir, nuspecEntry.Name.ToLower().SimplifyGodotPath()));
+
+ // Extract the other package files
+
+ foreach (var entry in archive.Entries)
+ {
+ // NOTE: SimplifyGodotPath() removes trailing slash and backslash,
+ // so we can't use the result to check if the entry is a directory.
+
+ string entryFullName = entry.FullName.Replace('\\', '/');
+
+ // Check if the file must be ignored
+ if ( // Excluded files.
+ NupkgExcludePaths.Any(e => entryFullName.StartsWith(e, StringComparison.OrdinalIgnoreCase)) ||
+ // Nupkg hash files and nupkg metadata files on all directory.
+ entryFullName.EndsWith(".nupkg.sha512", StringComparison.OrdinalIgnoreCase) ||
+ entryFullName.EndsWith(".nupkg.metadata", StringComparison.OrdinalIgnoreCase) ||
+ // Nuspec at root level. We already extracted it previously but in lower case.
+ entryFullName.IndexOf('/') == -1 && entryFullName.EndsWith(".nuspec"))
+ {
+ continue;
+ }
+
+ string entryFullNameSimplified = entryFullName.SimplifyGodotPath();
+ string destFilePath = Path.Combine(destDir, entryFullNameSimplified);
+ bool isDir = entryFullName.EndsWith("/");
+
+ if (isDir)
+ {
+ Directory.CreateDirectory(destFilePath);
+ }
+ else
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
+ entry.ExtractToFile(destFilePath, overwrite: true);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Copies and extracts all the Godot bundled packages to the Godot NuGet fallback folder.
+ /// Does nothing if the packages were already copied.
+ /// </summary>
+ public static void AddBundledPackagesToFallbackFolder(string fallbackFolder)
+ {
+ GD.Print("Copying Godot Offline Packages...");
+
+ string nupkgsLocation = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "nupkgs");
+
+ void AddPackage(string packageId, string packageVersion)
+ {
+ string nupkgPath = Path.Combine(nupkgsLocation, $"{packageId}.{packageVersion}.nupkg");
+ AddPackageToFallbackFolder(fallbackFolder, nupkgPath, packageId, packageVersion);
+ }
+
+ foreach (var (packageId, packageVersion) in PackagesToAdd)
+ AddPackage(packageId, packageVersion);
+ }
+
+ private static readonly (string packageId, string packageVersion)[] PackagesToAdd =
+ {
+ ("Godot.NET.Sdk", GeneratedGodotNupkgsVersions.GodotNETSdk)
+ };
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs b/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs
deleted file mode 100644
index 520e665595..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/BuildManager.cs
+++ /dev/null
@@ -1,273 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Threading.Tasks;
-using GodotTools.Build;
-using GodotTools.Ides.Rider;
-using GodotTools.Internals;
-using GodotTools.Utils;
-using static GodotTools.Internals.Globals;
-using File = GodotTools.Utils.File;
-
-namespace GodotTools
-{
- public static class BuildManager
- {
- private static readonly List<BuildInfo> BuildsInProgress = new List<BuildInfo>();
-
- public const string PropNameMsbuildMono = "MSBuild (Mono)";
- public const string PropNameMsbuildVs = "MSBuild (VS Build Tools)";
- public const string PropNameMsbuildJetBrains = "MSBuild (JetBrains Rider)";
-
- public const string MsBuildIssuesFileName = "msbuild_issues.csv";
- public const string MsBuildLogFileName = "msbuild_log.txt";
-
- public enum BuildTool
- {
- MsBuildMono,
- MsBuildVs,
- JetBrainsMsBuild
- }
-
- private static void RemoveOldIssuesFile(BuildInfo buildInfo)
- {
- var issuesFile = GetIssuesFilePath(buildInfo);
-
- if (!File.Exists(issuesFile))
- return;
-
- File.Delete(issuesFile);
- }
-
- private static void ShowBuildErrorDialog(string message)
- {
- GodotSharpEditor.Instance.ShowErrorDialog(message, "Build error");
- GodotSharpEditor.Instance.BottomPanel.ShowBuildTab();
- }
-
- public static void RestartBuild(BuildTab buildTab) => throw new NotImplementedException();
- public static void StopBuild(BuildTab buildTab) => throw new NotImplementedException();
-
- private static string GetLogFilePath(BuildInfo buildInfo)
- {
- return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName);
- }
-
- private static string GetIssuesFilePath(BuildInfo buildInfo)
- {
- return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName);
- }
-
- private static void PrintVerbose(string text)
- {
- if (Godot.OS.IsStdoutVerbose())
- Godot.GD.Print(text);
- }
-
- public static bool Build(BuildInfo buildInfo)
- {
- if (BuildsInProgress.Contains(buildInfo))
- throw new InvalidOperationException("A build is already in progress");
-
- BuildsInProgress.Add(buildInfo);
-
- try
- {
- BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.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 ? BuildTab.BuildResults.Success : BuildTab.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(BuildInfo buildInfo)
- {
- if (BuildsInProgress.Contains(buildInfo))
- throw new InvalidOperationException("A build is already in progress");
-
- BuildsInProgress.Add(buildInfo);
-
- try
- {
- BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.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 ? BuildTab.BuildResults.Success : BuildTab.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 BuildProjectBlocking(string config, IEnumerable<string> godotDefines)
- {
- if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
- return true; // No solution to build
-
- // Make sure the API assemblies are up to date before building the project.
- // We may not have had the chance to update the release API assemblies, and the debug ones
- // may have been deleted by the user at some point after they were loaded by the Godot editor.
- string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(config == "ExportRelease" ? "Release" : "Debug");
-
- if (!string.IsNullOrEmpty(apiAssembliesUpdateError))
- {
- ShowBuildErrorDialog("Failed to update the Godot API assemblies");
- return false;
- }
-
- var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
- var buildTool = (BuildTool)editorSettings.GetSetting("mono/builds/build_tool");
-
- using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1))
- {
- pr.Step("Building project solution", 0);
-
- var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, config);
-
- // Add Godot defines
- string constants = buildTool != BuildTool.MsBuildMono ? "GodotDefineConstants=\"" : "GodotDefineConstants=\\\"";
-
- foreach (var godotDefine in godotDefines)
- constants += $"GODOT_{godotDefine.ToUpper().Replace("-", "_").Replace(" ", "_").Replace(";", "_")};";
-
- if (Internal.GodotIsRealTDouble())
- constants += "GODOT_REAL_T_IS_DOUBLE;";
-
- constants += buildTool != BuildTool.MsBuildMono ? "\"" : "\\\"";
-
- 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");
-
- CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath);
-
- if (File.Exists(editorScriptsMetadataPath))
- File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath);
-
- var currentPlayRequest = GodotSharpEditor.Instance.GodotIdeManager.GodotIdeServer.CurrentPlayRequest;
-
- if (currentPlayRequest != null)
- {
- if (currentPlayRequest.Value.HasDebugger)
- {
- // Set the environment variable that will tell the player to connect to the IDE debugger
- // TODO: We should probably add a better way to do this
- Environment.SetEnvironmentVariable("GODOT_MONO_DEBUGGER_AGENT",
- "--debugger-agent=transport=dt_socket" +
- $",address={currentPlayRequest.Value.DebuggerHost}:{currentPlayRequest.Value.DebuggerPort}" +
- ",server=n");
- }
-
- return true; // Requested play from an external editor/IDE which already built the project
- }
-
- var godotDefines = new[]
- {
- Godot.OS.GetName(),
- Internal.GodotIs32Bits() ? "32" : "64"
- };
-
- return BuildProjectBlocking("Debug", godotDefines);
- }
-
- public static void Initialize()
- {
- // Build tool settings
- var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
- var msbuild = BuildTool.MsBuildMono;
- if (OS.IsWindows)
- msbuild = RiderPathManager.IsExternalEditorSetToRider(editorSettings)
- ? BuildTool.JetBrainsMsBuild
- : BuildTool.MsBuildVs;
-
- EditorDef("mono/builds/build_tool", msbuild);
-
- 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},{PropNameMsbuildJetBrains}" :
- $"{PropNameMsbuildMono}"
- });
-
- EditorDef("mono/builds/print_build_output", false);
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs b/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs
deleted file mode 100644
index 938c3d8be1..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/BuildTab.cs
+++ /dev/null
@@ -1,267 +0,0 @@
-using Godot;
-using System;
-using Godot.Collections;
-using GodotTools.Internals;
-using File = GodotTools.Utils.File;
-using Path = System.IO.Path;
-
-namespace GodotTools
-{
- public class BuildTab : 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 Texture2D IconTexture
- {
- get
- {
- if (!BuildExited)
- return GetThemeIcon("Stop", "EditorIcons");
-
- if (BuildResult == BuildResults.Error)
- return GetThemeIcon("StatusError", "EditorIcons");
-
- return GetThemeIcon("StatusSuccess", "EditorIcons");
- }
- }
-
- public BuildInfo BuildInfo { get; private set; }
-
- private void _LoadIssuesFromFile(string csvFile)
- {
- using (var file = new Godot.File())
- {
- try
- {
- 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);
- }
- }
- finally
- {
- file.Close(); // Disposing it is not enough. We need to call Close()
- }
- }
- }
-
- 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 = GetThemeIcon("Warning", "EditorIcons"))
- using (var errorIcon = GetThemeIcon("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.BottomPanel.RaiseBuildTab(this);
- }
-
- public void OnBuildExit(BuildResults result)
- {
- BuildExited = true;
- BuildResult = result;
-
- _LoadIssuesFromFile(Path.Combine(BuildInfo.LogsDirPath, BuildManager.MsBuildIssuesFileName));
- UpdateIssuesList();
-
- GodotSharpEditor.Instance.BottomPanel.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.BottomPanel.RaiseBuildTab(this);
- }
-
- public void RestartBuild()
- {
- if (!BuildExited)
- throw new InvalidOperationException("Build already started");
-
- BuildManager.RestartBuild(this);
- }
-
- public void StopBuild()
- {
- if (!BuildExited)
- throw new InvalidOperationException("Build is not in progress");
-
- BuildManager.StopBuild(this);
- }
-
- public override void _Ready()
- {
- base._Ready();
-
- issuesList = new ItemList { SizeFlagsVertical = (int)SizeFlags.ExpandFill };
- issuesList.ItemActivated += _IssueActivated;
- AddChild(issuesList);
- }
-
- private BuildTab()
- {
- }
-
- public BuildTab(BuildInfo buildInfo)
- {
- BuildInfo = buildInfo;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs b/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs
index 421729cc11..1d800b8151 100644
--- a/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/CsProjOperations.cs
@@ -1,9 +1,9 @@
using Godot;
using System;
+using System.Linq;
using Godot.Collections;
using GodotTools.Internals;
using GodotTools.ProjectEditor;
-using static GodotTools.Internals.Globals;
using File = GodotTools.Utils.File;
using Directory = GodotTools.Utils.Directory;
@@ -15,7 +15,7 @@ namespace GodotTools
{
try
{
- return ProjectGenerator.GenGameProject(dir, name, compileItems: new string[] { });
+ return ProjectGenerator.GenAndSaveGameProject(dir, name);
}
catch (Exception e)
{
@@ -24,14 +24,6 @@ namespace GodotTools
}
}
- 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);
- }
-
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static ulong ConvertToTimestamp(this DateTime value)
@@ -40,81 +32,77 @@ namespace GodotTools
return (ulong)elapsedTime.TotalSeconds;
}
- public static void GenerateScriptsMetadata(string projectPath, string outputPath)
+ private static bool TryParseFileMetadata(string includeFile, ulong modifiedTime, out Dictionary fileMetadata)
{
- if (File.Exists(outputPath))
- File.Delete(outputPath);
+ fileMetadata = null;
- var oldDict = Internal.GetScriptsMetadataOrNothing();
- var newDict = new Godot.Collections.Dictionary<string, object>();
+ var parseError = ScriptClassParser.ParseFile(includeFile, out var classes, out string errorStr);
- foreach (var includeFile in ProjectUtils.GetIncludeFiles(projectPath, "Compile"))
+ if (parseError != Error.Ok)
{
- string projectIncludeFile = ("res://" + includeFile).SimplifyGodotPath();
+ GD.PushError($"Failed to determine namespace and class for script: {includeFile}. Parse error: {errorStr ?? parseError.ToString()}");
+ return false;
+ }
- ulong modifiedTime = File.GetLastWriteTime(projectIncludeFile).ConvertToTimestamp();
+ string searchName = System.IO.Path.GetFileNameWithoutExtension(includeFile);
- 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;
- }
- }
- }
+ var firstMatch = classes.FirstOrDefault(classDecl =>
+ classDecl.BaseCount != 0 && // If it doesn't inherit anything, it can't be a Godot.Object.
+ classDecl.SearchName == searchName // Filter by the name we're looking for
+ );
+
+ if (firstMatch == null)
+ return false; // Not found
- Error parseError = ScriptClassParser.ParseFile(projectIncludeFile, out var classes, out string errorStr);
- if (parseError != Error.Ok)
+ fileMetadata = new Dictionary
+ {
+ ["modified_time"] = $"{modifiedTime}",
+ ["class"] = new Dictionary
{
- GD.PushError($"Failed to determine namespace and class for script: {projectIncludeFile}. Parse error: {errorStr ?? parseError.ToString()}");
- continue;
+ ["namespace"] = firstMatch.Namespace,
+ ["class_name"] = firstMatch.Name,
+ ["nested"] = firstMatch.Nested
}
+ };
- string searchName = System.IO.Path.GetFileNameWithoutExtension(projectIncludeFile);
-
- var classDict = new Dictionary();
+ return true;
+ }
- foreach (var classDecl in classes)
- {
- if (classDecl.BaseCount == 0)
- continue; // Does not inherit nor implement anything, so it can't be a script class
+ public static void GenerateScriptsMetadata(string projectPath, string outputPath)
+ {
+ var metadataDict = Internal.GetScriptsMetadataOrNothing().Duplicate();
- string classCmp = classDecl.Nested ?
- classDecl.Name.Substring(classDecl.Name.LastIndexOf(".", StringComparison.Ordinal) + 1) :
- classDecl.Name;
+ bool IsUpToDate(string includeFile, ulong modifiedTime)
+ {
+ return metadataDict.TryGetValue(includeFile, out var oldFileVar) &&
+ ulong.TryParse(((Dictionary)oldFileVar)["modified_time"] as string,
+ out ulong storedModifiedTime) && storedModifiedTime == modifiedTime;
+ }
- if (classCmp != searchName)
- continue;
+ var outdatedFiles = ProjectUtils.GetIncludeFiles(projectPath, "Compile")
+ .Select(path => ("res://" + path).SimplifyGodotPath())
+ .ToDictionary(path => path, path => File.GetLastWriteTime(path).ConvertToTimestamp())
+ .Where(pair => !IsUpToDate(includeFile: pair.Key, modifiedTime: pair.Value))
+ .ToArray();
- classDict["namespace"] = classDecl.Namespace;
- classDict["class_name"] = classDecl.Name;
- classDict["nested"] = classDecl.Nested;
- break;
- }
+ foreach (var pair in outdatedFiles)
+ {
+ metadataDict.Remove(pair.Key);
- if (classDict.Count == 0)
- continue; // Not found
+ string includeFile = pair.Key;
- newDict[projectIncludeFile] = new Dictionary { ["modified_time"] = $"{modifiedTime}", ["class"] = classDict };
+ if (TryParseFileMetadata(includeFile, modifiedTime: pair.Value, out var fileMetadata))
+ metadataDict[includeFile] = fileMetadata;
}
- if (newDict.Count > 0)
- {
- string json = JSON.Print(newDict);
+ string json = metadataDict.Count <= 0 ? "{}" : JSON.Print(metadataDict);
- string baseDir = outputPath.GetBaseDir();
+ string baseDir = outputPath.GetBaseDir();
- if (!Directory.Exists(baseDir))
- Directory.CreateDirectory(baseDir);
+ if (!Directory.Exists(baseDir))
+ Directory.CreateDirectory(baseDir);
- File.WriteAllText(outputPath, json);
- }
+ File.WriteAllText(outputPath, json);
}
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
index f1765f7e19..5bb8d444c2 100755
--- a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs
@@ -120,7 +120,7 @@ namespace GodotTools.Export
string assemblyPath = assembly.Value;
string outputFileExtension = platform == OS.Platforms.Windows ? ".dll" :
- platform == OS.Platforms.OSX ? ".dylib" :
+ platform == OS.Platforms.MacOS ? ".dylib" :
".so";
string outputFileName = assemblyName + ".dll" + outputFileExtension;
@@ -132,7 +132,7 @@ namespace GodotTools.Export
ExecuteCompiler(FindCrossCompiler(compilerDirPath), compilerArgs, bclDir);
- if (platform == OS.Platforms.OSX)
+ if (platform == OS.Platforms.MacOS)
{
exporter.AddSharedObject(tempOutputFilePath, tags: null);
}
@@ -328,7 +328,7 @@ MONO_AOT_MODE_LAST = 1000,
if (lipoExitCode != 0)
throw new Exception($"Command 'lipo' exited with code: {lipoExitCode}");
- // TODO: Add the AOT lib and interpreter libs as device only to supress warnings when targeting the simulator
+ // TODO: Add the AOT lib and interpreter libs as device only to suppress warnings when targeting the simulator
// Add the fat AOT static library to the Xcode project
exporter.AddIosProjectStaticLib(fatOutputFilePath);
@@ -581,13 +581,13 @@ MONO_AOT_MODE_LAST = 1000,
string arch = bits == "64" ? "x86_64" : "i686";
return $"windows-{arch}";
}
- case OS.Platforms.OSX:
+ case OS.Platforms.MacOS:
{
Debug.Assert(bits == null || bits == "64");
string arch = "x86_64";
return $"{platform}-{arch}";
}
- case OS.Platforms.X11:
+ case OS.Platforms.LinuxBSD:
case OS.Platforms.Server:
{
string arch = bits == "64" ? "x86_64" : "i686";
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
index 2ceb4888a2..e9bb701562 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs
@@ -5,8 +5,10 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
+using GodotTools.Build;
using GodotTools.Core;
using GodotTools.Internals;
+using JetBrains.Annotations;
using static GodotTools.Internals.Globals;
using Directory = GodotTools.Utils.Directory;
using File = GodotTools.Utils.File;
@@ -18,7 +20,7 @@ namespace GodotTools.Export
public class ExportPlugin : EditorExportPlugin
{
[Flags]
- enum I18NCodesets
+ enum I18NCodesets : long
{
None = 0,
CJK = 1,
@@ -142,12 +144,12 @@ namespace GodotTools.Export
private void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags)
{
+ _ = flags; // Unused
+
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
return;
- string platform = DeterminePlatformFromFeatures(features);
-
- if (platform == null)
+ if (!DeterminePlatformFromFeatures(features, out string platform))
throw new NotSupportedException("Target platform not supported");
string outputDir = new FileInfo(path).Directory?.FullName ??
@@ -155,15 +157,10 @@ namespace GodotTools.Export
string buildConfig = isDebug ? "ExportDebug" : "ExportRelease";
- string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}");
- CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath);
-
+ string scriptsMetadataPath = BuildManager.GenerateExportedGameScriptMetadata(isDebug);
AddFile(scriptsMetadataPath, scriptsMetadataPath);
- // Turn export features into defines
- var godotDefines = features;
-
- if (!BuildManager.BuildProjectBlocking(buildConfig, godotDefines))
+ if (!BuildManager.BuildProjectBlocking(buildConfig, platform: platform))
throw new Exception("Failed to build project");
// Add dependency assemblies
@@ -176,6 +173,8 @@ namespace GodotTools.Export
assemblies[projectDllName] = projectDllSrcPath;
+ string bclDir = DeterminePlatformBclDir(platform);
+
if (platform == OS.Platforms.Android)
{
string godotAndroidExtProfileDir = GetBclProfileDir("godot_android_ext");
@@ -186,8 +185,49 @@ namespace GodotTools.Export
assemblies["Mono.Android"] = monoAndroidAssemblyPath;
}
+ else if (platform == OS.Platforms.HTML5)
+ {
+ // Ideally these would be added automatically since they're referenced by the wasm BCL assemblies.
+ // However, at least in the case of 'WebAssembly.Net.Http' for some reason the BCL assemblies
+ // reference a different version even though the assembly is the same, for some weird reason.
- string bclDir = DeterminePlatformBclDir(platform);
+ var wasmFrameworkAssemblies = new[] {"WebAssembly.Bindings", "WebAssembly.Net.WebSockets"};
+
+ foreach (string thisWasmFrameworkAssemblyName in wasmFrameworkAssemblies)
+ {
+ string thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName + ".dll");
+ if (!File.Exists(thisWasmFrameworkAssemblyPath))
+ throw new FileNotFoundException($"Assembly not found: '{thisWasmFrameworkAssemblyName}'", thisWasmFrameworkAssemblyPath);
+ assemblies[thisWasmFrameworkAssemblyName] = thisWasmFrameworkAssemblyPath;
+ }
+
+ // Assemblies that can have a different name in a newer version. Newer version must come first and it has priority.
+ (string newName, string oldName)[] wasmFrameworkAssembliesOneOf = new[]
+ {
+ ("System.Net.Http.WebAssemblyHttpHandler", "WebAssembly.Net.Http")
+ };
+
+ foreach (var thisWasmFrameworkAssemblyName in wasmFrameworkAssembliesOneOf)
+ {
+ string thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName.newName + ".dll");
+ if (File.Exists(thisWasmFrameworkAssemblyPath))
+ {
+ assemblies[thisWasmFrameworkAssemblyName.newName] = thisWasmFrameworkAssemblyPath;
+ }
+ else
+ {
+ thisWasmFrameworkAssemblyPath = Path.Combine(bclDir, thisWasmFrameworkAssemblyName.oldName + ".dll");
+ if (!File.Exists(thisWasmFrameworkAssemblyPath))
+ {
+ throw new FileNotFoundException("Expected one of the following assemblies but none were found: " +
+ $"'{thisWasmFrameworkAssemblyName.newName}' / '{thisWasmFrameworkAssemblyName.oldName}'",
+ thisWasmFrameworkAssemblyPath);
+ }
+
+ assemblies[thisWasmFrameworkAssemblyName.oldName] = thisWasmFrameworkAssemblyPath;
+ }
+ }
+ }
var initialAssemblies = assemblies.Duplicate();
internal_GetExportedAssemblyDependencies(initialAssemblies, buildConfig, bclDir, assemblies);
@@ -289,6 +329,7 @@ namespace GodotTools.Export
}
}
+ [NotNull]
private static string ExportDataDirectory(string[] features, string platform, bool isDebug, string outputDir)
{
string target = isDebug ? "release_debug" : "release";
@@ -343,18 +384,19 @@ namespace GodotTools.Export
private static bool PlatformHasTemplateDir(string platform)
{
// OSX export templates are contained in a zip, so we place our custom template inside it and let Godot do the rest.
- return !new[] { OS.Platforms.OSX, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform);
+ return !new[] {OS.Platforms.MacOS, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform);
}
- private static string DeterminePlatformFromFeatures(IEnumerable<string> features)
+ private static bool DeterminePlatformFromFeatures(IEnumerable<string> features, out string platform)
{
foreach (var feature in features)
{
- if (OS.PlatformNameMap.TryGetValue(feature, out string platform))
- return platform;
+ if (OS.PlatformNameMap.TryGetValue(feature, out platform))
+ return true;
}
- return null;
+ platform = null;
+ return false;
}
private static string GetBclProfileDir(string profile)
@@ -391,7 +433,7 @@ namespace GodotTools.Export
/// </summary>
private static bool PlatformRequiresCustomBcl(string platform)
{
- if (new[] { OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform))
+ if (new[] {OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform))
return true;
// The 'net_4_x' BCL is not compatible between Windows and the other platforms.
@@ -413,8 +455,8 @@ namespace GodotTools.Export
case OS.Platforms.Windows:
case OS.Platforms.UWP:
return "net_4_x_win";
- case OS.Platforms.OSX:
- case OS.Platforms.X11:
+ case OS.Platforms.MacOS:
+ case OS.Platforms.LinuxBSD:
case OS.Platforms.Server:
case OS.Platforms.Haiku:
return "net_4_x";
@@ -432,7 +474,7 @@ namespace GodotTools.Export
private static string DetermineDataDirNameForProject()
{
var appName = (string)ProjectSettings.GetSetting("application/config/name");
- string appNameSafe = appName.ToSafeDirName(allowDirSeparator: false);
+ string appNameSafe = appName.ToSafeDirName();
return $"data_{appNameSafe}";
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/XcodeHelper.cs b/modules/mono/editor/GodotTools/GodotTools/Export/XcodeHelper.cs
index 219b7a698a..93ef837a83 100755
--- a/modules/mono/editor/GodotTools/GodotTools/Export/XcodeHelper.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Export/XcodeHelper.cs
@@ -27,7 +27,7 @@ namespace GodotTools.Export
{
var outputWrapper = new Godot.Collections.Array();
- int exitCode = Godot.OS.Execute("xcode-select", new string[] { "--print-path" }, blocking: true, output: outputWrapper);
+ int exitCode = Godot.OS.Execute("xcode-select", new string[] { "--print-path" }, output: outputWrapper);
if (exitCode == 0)
{
diff --git a/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs b/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs
index bb218c2f19..90d6eb960e 100644
--- a/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/ExternalEditorId.cs
@@ -1,6 +1,6 @@
namespace GodotTools
{
- public enum ExternalEditorId
+ public enum ExternalEditorId : long
{
None,
VisualStudio, // TODO (Windows-only)
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
index c070cb16d9..58561c5097 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -4,8 +4,9 @@ using GodotTools.Export;
using GodotTools.Utils;
using System;
using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using System.IO;
+using System.Linq;
+using GodotTools.Build;
using GodotTools.Ides;
using GodotTools.Ides.Rider;
using GodotTools.Internals;
@@ -18,7 +19,6 @@ using Path = System.IO.Path;
namespace GodotTools
{
- [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class GodotSharpEditor : EditorPlugin, ISerializationListener
{
private EditorSettings editorSettings;
@@ -29,19 +29,23 @@ namespace GodotTools
private AcceptDialog aboutDialog;
private CheckBox aboutDialogCheckBox;
- private ToolButton bottomPanelBtn;
+ private Button bottomPanelBtn;
+ private Button toolBarBuildButton;
public GodotIdeManager GodotIdeManager { get; private set; }
private WeakRef exportPluginWeak; // TODO Use WeakReference once we have proper serialization
- public BottomPanel BottomPanel { get; private set; }
+ public MSBuildPanel MSBuildPanel { get; private set; }
+
+ public bool SkipBuildBeforePlaying { get; set; } = false;
public static string ProjectAssemblyName
{
get
{
var projectAssemblyName = (string)ProjectSettings.GetSetting("application/config/name");
+ projectAssemblyName = projectAssemblyName.ToSafeDirName();
if (string.IsNullOrEmpty(projectAssemblyName))
projectAssemblyName = "UnnamedProject";
return projectAssemblyName;
@@ -123,6 +127,7 @@ namespace GodotTools
{
menuPopup.RemoveItem(menuPopup.GetItemIndex((int)MenuOptions.CreateSln));
bottomPanelBtn.Show();
+ toolBarBuildButton.Show();
}
private void _ShowAboutDialog()
@@ -142,12 +147,27 @@ namespace GodotTools
case MenuOptions.AboutCSharp:
_ShowAboutDialog();
break;
+ case MenuOptions.SetupGodotNugetFallbackFolder:
+ {
+ try
+ {
+ string fallbackFolder = NuGetUtils.GodotFallbackFolderPath;
+ NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, fallbackFolder);
+ NuGetUtils.AddBundledPackagesToFallbackFolder(fallbackFolder);
+ }
+ catch (Exception e)
+ {
+ ShowErrorDialog("Failed to setup Godot NuGet Offline Packages: " + e.Message);
+ }
+
+ break;
+ }
default:
throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid menu option");
}
}
- private void _BuildSolutionPressed()
+ private void BuildSolutionPressed()
{
if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
{
@@ -155,53 +175,22 @@ namespace GodotTools
return; // Failed to create solution
}
- Instance.BottomPanel.BuildProjectPressed();
+ Instance.MSBuildPanel.BuildSolution();
}
- public override void _Notification(int what)
+ public override void _Ready()
{
- base._Notification(what);
+ base._Ready();
- if (what == NotificationReady)
- {
- bool showInfoDialog = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start");
- if (showInfoDialog)
- {
- aboutDialog.Exclusive = 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.Exclusive = false;
- }
-
- var fileSystemDock = GetEditorInterface().GetFileSystemDock();
-
- fileSystemDock.FilesMoved += (file, newFile) =>
- {
- if (Path.GetExtension(file) == Internal.CSharpLanguageExtension)
- {
- ProjectUtils.RenameItemInProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile",
- ProjectSettings.GlobalizePath(file), ProjectSettings.GlobalizePath(newFile));
- }
- };
-
- fileSystemDock.FileRemoved += file =>
- {
- if (Path.GetExtension(file) == Internal.CSharpLanguageExtension)
- ProjectUtils.RemoveItemFromProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile",
- ProjectSettings.GlobalizePath(file));
- };
-
- fileSystemDock.FolderMoved += (oldFolder, newFolder) =>
- {
- ProjectUtils.RenameItemsToNewFolderInProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile",
- ProjectSettings.GlobalizePath(oldFolder), ProjectSettings.GlobalizePath(newFolder));
- };
+ MSBuildPanel.BuildOutputView.BuildStateChanged += BuildStateChanged;
- fileSystemDock.FolderRemoved += oldFolder =>
- {
- ProjectUtils.RemoveItemsInFolderFromProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile",
- ProjectSettings.GlobalizePath(oldFolder));
- };
+ bool showInfoDialog = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start");
+ if (showInfoDialog)
+ {
+ aboutDialog.Exclusive = 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.Exclusive = false;
}
}
@@ -209,6 +198,7 @@ namespace GodotTools
{
CreateSln,
AboutCSharp,
+ SetupGodotNugetFallbackFolder,
}
public void ShowErrorDialog(string message, string title = "Error")
@@ -228,15 +218,39 @@ namespace GodotTools
[UsedImplicitly]
public Error OpenInExternalEditor(Script script, int line, int col)
{
- var editor = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor");
+ var editorId = (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor");
- switch (editor)
+ switch (editorId)
{
case ExternalEditorId.None:
- // Tells the caller to fallback to the global external editor settings or the built-in editor
+ // Not an error. Tells the caller to fallback to the global external editor settings or the built-in editor.
return Error.Unavailable;
case ExternalEditorId.VisualStudio:
- throw new NotSupportedException();
+ {
+ string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
+
+ var args = new List<string>
+ {
+ GodotSharpDirs.ProjectSlnPath,
+ line >= 0 ? $"{scriptPath};{line + 1};{col + 1}" : scriptPath
+ };
+
+ string command = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "GodotTools.OpenVisualStudio.exe");
+
+ try
+ {
+ if (Godot.OS.IsStdoutVerbose())
+ Console.WriteLine($"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}");
+
+ OS.RunProcess(command, args);
+ }
+ catch (Exception e)
+ {
+ GD.PushError($"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'");
+ }
+
+ break;
+ }
case ExternalEditorId.VisualStudioForMac:
goto case ExternalEditorId.MonoDevelop;
case ExternalEditorId.Rider:
@@ -249,17 +263,20 @@ namespace GodotTools
{
string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
- if (line >= 0)
- GodotIdeManager.SendOpenFile(scriptPath, line + 1, col);
- else
- GodotIdeManager.SendOpenFile(scriptPath);
+ GodotIdeManager.LaunchIdeAsync().ContinueWith(launchTask =>
+ {
+ var editorPick = launchTask.Result;
+ if (line >= 0)
+ editorPick?.SendOpenFile(scriptPath, line + 1, col);
+ else
+ editorPick?.SendOpenFile(scriptPath);
+ });
break;
}
-
case ExternalEditorId.VsCode:
{
- if (_vsCodePath.Empty() || !File.Exists(_vsCodePath))
+ if (string.IsNullOrEmpty(_vsCodePath) || !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);
@@ -269,7 +286,7 @@ namespace GodotTools
bool osxAppBundleInstalled = false;
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
// The package path is '/Applications/Visual Studio Code.app'
const string vscodeBundleId = "com.microsoft.VSCode";
@@ -300,7 +317,7 @@ namespace GodotTools
if (line >= 0)
{
args.Add("-g");
- args.Add($"{scriptPath}:{line + 1}:{col}");
+ args.Add($"{scriptPath}:{line}:{col}");
}
else
{
@@ -309,9 +326,9 @@ namespace GodotTools
string command;
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
- if (!osxAppBundleInstalled && _vsCodePath.Empty())
+ if (!osxAppBundleInstalled && string.IsNullOrEmpty(_vsCodePath))
{
GD.PushError("Cannot find code editor: VSCode");
return Error.FileNotFound;
@@ -321,7 +338,7 @@ namespace GodotTools
}
else
{
- if (_vsCodePath.Empty())
+ if (string.IsNullOrEmpty(_vsCodePath))
{
GD.PushError("Cannot find code editor: VSCode");
return Error.FileNotFound;
@@ -341,7 +358,6 @@ namespace GodotTools
break;
}
-
default:
throw new ArgumentOutOfRangeException();
}
@@ -360,6 +376,43 @@ namespace GodotTools
return BuildManager.EditorBuildCallback();
}
+ private void ApplyNecessaryChangesToSolution()
+ {
+ try
+ {
+ // Migrate solution from old configuration names to: Debug, ExportDebug and ExportRelease
+ DotNetSolution.MigrateFromOldConfigNames(GodotSharpDirs.ProjectSlnPath);
+
+ var msbuildProject = ProjectUtils.Open(GodotSharpDirs.ProjectCsProjPath)
+ ?? throw new Exception("Cannot open C# project");
+
+ // NOTE: The order in which changes are made to the project is important
+
+ // Migrate to MSBuild project Sdks style if using the old style
+ ProjectUtils.MigrateToProjectSdksStyle(msbuildProject, ProjectAssemblyName);
+
+ ProjectUtils.EnsureGodotSdkIsUpToDate(msbuildProject);
+
+ if (msbuildProject.HasUnsavedChanges)
+ {
+ // Save a copy of the project before replacing it
+ FileUtils.SaveBackupCopy(GodotSharpDirs.ProjectCsProjPath);
+
+ msbuildProject.Save();
+ }
+ }
+ catch (Exception e)
+ {
+ GD.PushError(e.ToString());
+ }
+ }
+
+ private void BuildStateChanged()
+ {
+ if (bottomPanelBtn != null)
+ bottomPanelBtn.Icon = MSBuildPanel.BuildOutputView.BuildStateIcon;
+ }
+
public override void EnablePlugin()
{
base.EnablePlugin();
@@ -376,20 +429,20 @@ namespace GodotTools
errorDialog = new AcceptDialog();
editorBaseControl.AddChild(errorDialog);
- BottomPanel = new BottomPanel();
-
- bottomPanelBtn = AddControlToBottomPanel(BottomPanel, "Mono".TTR());
+ MSBuildPanel = new MSBuildPanel();
+ bottomPanelBtn = AddControlToBottomPanel(MSBuildPanel, "MSBuild".TTR());
AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"});
menuPopup = new PopupMenu();
menuPopup.Hide();
- AddToolSubmenuItem("Mono", menuPopup);
+ AddToolSubmenuItem("C#", 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);
+ menuPopup.AddItem("Setup Godot NuGet Offline Packages".TTR(), (int)MenuOptions.SetupGodotNugetFallbackFolder);
aboutDialog = new AcceptDialog();
editorBaseControl.AddChild(aboutDialog);
aboutDialog.Title = "Important: C# support is not feature-complete";
@@ -417,7 +470,7 @@ namespace GodotTools
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, Windows and Android, but not yet to iOS, HTML5 or UWP. " +
+ "Projects can be exported to Linux, macOS, Windows, Android, iOS and HTML5, but not yet to UWP. " +
"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" +
@@ -437,56 +490,28 @@ namespace GodotTools
aboutVBox.AddChild(aboutDialogCheckBox);
}
- if (File.Exists(GodotSharpDirs.ProjectSlnPath) && File.Exists(GodotSharpDirs.ProjectCsProjPath))
+ toolBarBuildButton = new Button
{
- try
- {
- // Migrate solution from old configuration names to: Debug, ExportDebug and ExportRelease
- DotNetSolution.MigrateFromOldConfigNames(GodotSharpDirs.ProjectSlnPath);
-
- var msbuildProject = ProjectUtils.Open(GodotSharpDirs.ProjectCsProjPath)
- ?? throw new Exception("Cannot open C# project");
-
- // NOTE: The order in which changes are made to the project is important
-
- // Migrate csproj from old configuration names to: Debug, ExportDebug and ExportRelease
- ProjectUtils.MigrateFromOldConfigNames(msbuildProject);
-
- // Apply the other fixes only after configurations have been migrated
-
- // Make sure the existing project has Api assembly references configured correctly
- ProjectUtils.FixApiHintPath(msbuildProject);
-
- if (msbuildProject.HasUnsavedChanges)
- {
- // Save a copy of the project before replacing it
- FileUtils.SaveBackupCopy(GodotSharpDirs.ProjectCsProjPath);
+ Text = "Build",
+ HintTooltip = "Build solution",
+ FocusMode = Control.FocusModeEnum.None
+ };
+ toolBarBuildButton.PressedSignal += BuildSolutionPressed;
+ AddControlToContainer(CustomControlContainer.Toolbar, toolBarBuildButton);
- msbuildProject.Save();
- }
- }
- catch (Exception e)
- {
- GD.PushError(e.ToString());
- }
+ if (File.Exists(GodotSharpDirs.ProjectSlnPath) && File.Exists(GodotSharpDirs.ProjectCsProjPath))
+ {
+ ApplyNecessaryChangesToSolution();
}
else
{
bottomPanelBtn.Hide();
+ toolBarBuildButton.Hide();
menuPopup.AddItem("Create C# solution".TTR(), (int)MenuOptions.CreateSln);
}
menuPopup.IdPressed += _MenuOptionPressed;
- var buildButton = new ToolButton
- {
- Text = "Build",
- HintTooltip = "Build solution",
- FocusMode = Control.FocusModeEnum.None
- };
- buildButton.PressedSignal += _BuildSolutionPressed;
- AddControlToContainer(CustomControlContainer.Toolbar, buildButton);
-
// External editor settings
EditorDef("mono/editor/external_editor", ExternalEditorId.None);
@@ -494,18 +519,19 @@ namespace GodotTools
if (OS.IsWindows)
{
- settingsHintStr += $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" +
+ settingsHintStr += $",Visual Studio:{(int)ExternalEditorId.VisualStudio}" +
+ $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" +
$",Visual Studio Code:{(int)ExternalEditorId.VsCode}" +
$",JetBrains Rider:{(int)ExternalEditorId.Rider}";
}
- else if (OS.IsOSX)
+ else if (OS.IsMacOS)
{
settingsHintStr += $",Visual Studio:{(int)ExternalEditorId.VisualStudioForMac}" +
$",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" +
$",Visual Studio Code:{(int)ExternalEditorId.VsCode}" +
$",JetBrains Rider:{(int)ExternalEditorId.Rider}";
}
- else if (OS.IsUnixLike())
+ else if (OS.IsUnixLike)
{
settingsHintStr += $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" +
$",Visual Studio Code:{(int)ExternalEditorId.VsCode}" +
@@ -526,6 +552,16 @@ namespace GodotTools
exportPlugin.RegisterExportSettings();
exportPluginWeak = WeakRef(exportPlugin);
+ try
+ {
+ // At startup we make sure NuGet.Config files have our Godot NuGet fallback folder included
+ NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, NuGetUtils.GodotFallbackFolderPath);
+ }
+ catch (Exception e)
+ {
+ GD.PushError("Failed to add Godot NuGet Offline Packages to NuGet.Config: " + e.Message);
+ }
+
BuildManager.Initialize();
RiderPathManager.Initialize();
@@ -564,6 +600,7 @@ namespace GodotTools
public static GodotSharpEditor Instance { get; private set; }
+ [UsedImplicitly]
private GodotSharpEditor()
{
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
index ac9379adf8..3f14629b11 100644
--- a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
@@ -1,123 +1,39 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project Sdk="Microsoft.NET.Sdk">
<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.7</TargetFrameworkVersion>
+ <TargetFramework>net472</TargetFramework>
+ <LangVersion>7.2</LangVersion>
+ <GodotApiConfiguration>Debug</GodotApiConfiguration> <!-- The Godot editor uses the Debug Godot API assemblies -->
<GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
- <DataDirToolsOutputPath>$(GodotSourceRootPath)/bin/GodotSharp/Tools</DataDirToolsOutputPath>
- <GodotApiConfiguration>Debug</GodotApiConfiguration>
- <LangVersion>7</LangVersion>
+ <GodotOutputDataDir>$(GodotSourceRootPath)/bin/GodotSharp</GodotOutputDataDir>
+ <GodotApiAssembliesDir>$(GodotOutputDataDir)/Api/$(GodotApiConfiguration)</GodotApiAssembliesDir>
</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 Condition=" Exists('$(GodotApiAssembliesDir)/GodotSharp.dll') ">
+ <!-- The project is part of the Godot source tree -->
+ <!-- Use the Godot source tree output folder instead of '$(ProjectDir)/bin' -->
+ <OutputPath>$(GodotOutputDataDir)/Tools</OutputPath>
+ <!-- Must not append '$(TargetFramework)' to the output path in this case -->
+ <AppendTargetFrameworkToOutputPath>False</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
- <Reference Include="JetBrains.Annotations, Version=2019.1.3.0, Culture=neutral, PublicKeyToken=1010a0d8d6380325">
- <HintPath>..\packages\JetBrains.Annotations.2019.1.3\lib\net20\JetBrains.Annotations.dll</HintPath>
- <Private>True</Private>
- </Reference>
- <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed">
- <HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
- <Private>True</Private>
- </Reference>
- <Reference Include="System" />
+ <PackageReference Include="JetBrains.Annotations" Version="2019.1.3.0" ExcludeAssets="runtime" PrivateAssets="all" />
+ <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
+ <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<Reference Include="GodotSharp">
- <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharp.dll</HintPath>
+ <HintPath>$(GodotApiAssembliesDir)/GodotSharp.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="GodotSharpEditor">
- <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharpEditor.dll</HintPath>
+ <HintPath>$(GodotApiAssembliesDir)/GodotSharpEditor.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
- <Compile Include="Build\MsBuildFinder.cs" />
- <Compile Include="Export\AotBuilder.cs" />
- <Compile Include="Export\ExportPlugin.cs" />
- <Compile Include="Export\XcodeHelper.cs" />
- <Compile Include="ExternalEditorId.cs" />
- <Compile Include="Ides\GodotIdeManager.cs" />
- <Compile Include="Ides\GodotIdeServer.cs" />
- <Compile Include="Ides\MonoDevelop\EditorId.cs" />
- <Compile Include="Ides\MonoDevelop\Instance.cs" />
- <Compile Include="Ides\Rider\RiderPathLocator.cs" />
- <Compile Include="Ides\Rider\RiderPathManager.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="Properties\AssemblyInfo.cs" />
- <Compile Include="Build\BuildSystem.cs" />
- <Compile Include="Utils\Directory.cs" />
- <Compile Include="Utils\File.cs" />
- <Compile Include="Utils\NotifyAwaiter.cs" />
- <Compile Include="Utils\OS.cs" />
- <Compile Include="GodotSharpEditor.cs" />
- <Compile Include="BuildManager.cs" />
- <Compile Include="HotReloadAssemblyWatcher.cs" />
- <Compile Include="BuildInfo.cs" />
- <Compile Include="BuildTab.cs" />
- <Compile Include="BottomPanel.cs" />
- <Compile Include="CsProjOperations.cs" />
- <Compile Include="Utils\CollectionExtensions.cs" />
- <Compile Include="Utils\User32Dll.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.IdeConnection\GodotTools.IdeConnection.csproj">
- <Project>{92600954-25f0-4291-8e11-1fee9fc4be20}</Project>
- <Name>GodotTools.IdeConnection</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>
- <None Include="packages.config" />
+ <ProjectReference Include="..\GodotTools.BuildLogger\GodotTools.BuildLogger.csproj" />
+ <ProjectReference Include="..\GodotTools.IdeMessaging\GodotTools.IdeMessaging.csproj" />
+ <ProjectReference Include="..\GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj" />
+ <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj" />
+ <!-- Include it if this is an SCons build targeting Windows, or if it's not an SCons build but we're on Windows -->
+ <ProjectReference Include="..\GodotTools.OpenVisualStudio\GodotTools.OpenVisualStudio.csproj" Condition=" '$(GodotPlatform)' == 'windows' Or ( '$(GodotPlatform)' == '' And '$(OS)' == 'Windows_NT' ) " />
</ItemGroup>
- <Target Name="CopyToDataDir" AfterTargets="Build">
- <ItemGroup>
- <GodotToolsCopy Include="$(OutputPath)\GodotTools*.dll" />
- <GodotToolsCopy Include="$(OutputPath)\Newtonsoft.Json.dll" />
- <GodotToolsCopy Include="$(OutputPath)\DotNet.Glob.dll" />
- </ItemGroup>
- <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
- <GodotToolsCopy Include="$(OutputPath)\GodotTools*.pdb" />
- </ItemGroup>
- <Copy SourceFiles="@(GodotToolsCopy)" DestinationFolder="$(DataDirToolsOutputPath)" ContinueOnError="false" />
- </Target>
- <Target Name="BuildAlwaysCopyToDataDir">
- <!-- Custom target run by SCons to make sure the CopyToDataDir target is always executed, without having to use DisableFastUpToDateCheck -->
- <CallTarget Targets="Build" />
- <CallTarget Targets="CopyToDataDir" />
- </Target>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
diff --git a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
index ae05710f4f..b30c857c64 100644
--- a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
@@ -10,7 +10,7 @@ namespace GodotTools
public override void _Notification(int what)
{
- if (what == Node.NotificationWmFocusIn)
+ if (what == Node.NotificationWmWindowFocusIn)
{
RestartTimer();
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
index 54f0ffab96..451ce39f5c 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeManager.cs
@@ -1,73 +1,104 @@
using System;
using System.IO;
+using System.Threading.Tasks;
using Godot;
-using GodotTools.IdeConnection;
+using GodotTools.IdeMessaging;
+using GodotTools.IdeMessaging.Requests;
using GodotTools.Internals;
namespace GodotTools.Ides
{
- public class GodotIdeManager : Node, ISerializationListener
+ public sealed class GodotIdeManager : Node, ISerializationListener
{
- public GodotIdeServer GodotIdeServer { get; private set; }
+ private MessagingServer MessagingServer { get; set; }
private MonoDevelop.Instance monoDevelInstance;
private MonoDevelop.Instance vsForMacInstance;
- private GodotIdeServer GetRunningServer()
+ private MessagingServer GetRunningOrNewServer()
{
- if (GodotIdeServer != null && !GodotIdeServer.IsDisposed)
- return GodotIdeServer;
- StartServer();
- return GodotIdeServer;
+ if (MessagingServer != null && !MessagingServer.IsDisposed)
+ return MessagingServer;
+
+ MessagingServer?.Dispose();
+ MessagingServer = new MessagingServer(OS.GetExecutablePath(), ProjectSettings.GlobalizePath(GodotSharpDirs.ResMetadataDir), new GodotLogger());
+
+ _ = MessagingServer.Listen();
+
+ return MessagingServer;
}
public override void _Ready()
{
- StartServer();
+ _ = GetRunningOrNewServer();
}
public void OnBeforeSerialize()
{
- GodotIdeServer?.Dispose();
}
public void OnAfterDeserialize()
{
- StartServer();
+ _ = GetRunningOrNewServer();
}
- private ILogger logger;
+ protected override void Dispose(bool disposing)
+ {
+ base.Dispose(disposing);
- protected ILogger Logger
+ if (disposing)
+ {
+ MessagingServer?.Dispose();
+ }
+ }
+
+ private string GetExternalEditorIdentity(ExternalEditorId editorId)
{
- get => logger ?? (logger = new GodotLogger());
+ // Manually convert to string to avoid breaking compatibility in case we rename the enum fields.
+ switch (editorId)
+ {
+ case ExternalEditorId.None:
+ return null;
+ case ExternalEditorId.VisualStudio:
+ return "VisualStudio";
+ case ExternalEditorId.VsCode:
+ return "VisualStudioCode";
+ case ExternalEditorId.Rider:
+ return "Rider";
+ case ExternalEditorId.VisualStudioForMac:
+ return "VisualStudioForMac";
+ case ExternalEditorId.MonoDevelop:
+ return "MonoDevelop";
+ default:
+ throw new NotImplementedException();
+ }
}
- private void StartServer()
+ public async Task<EditorPick?> LaunchIdeAsync(int millisecondsTimeout = 10000)
{
- GodotIdeServer?.Dispose();
- GodotIdeServer = new GodotIdeServer(LaunchIde,
- OS.GetExecutablePath(),
- ProjectSettings.GlobalizePath(GodotSharpDirs.ResMetadataDir));
+ var editorId = (ExternalEditorId)GodotSharpEditor.Instance.GetEditorInterface()
+ .GetEditorSettings().GetSetting("mono/editor/external_editor");
+ string editorIdentity = GetExternalEditorIdentity(editorId);
- GodotIdeServer.Logger = Logger;
+ var runningServer = GetRunningOrNewServer();
- GodotIdeServer.StartServer();
- }
+ if (runningServer.IsAnyConnected(editorIdentity))
+ return new EditorPick(editorIdentity);
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
+ LaunchIde(editorId, editorIdentity);
+
+ var timeoutTask = Task.Delay(millisecondsTimeout);
+ var completedTask = await Task.WhenAny(timeoutTask, runningServer.AwaitClientConnected(editorIdentity));
+
+ if (completedTask != timeoutTask)
+ return new EditorPick(editorIdentity);
- GodotIdeServer?.Dispose();
+ return null;
}
- private void LaunchIde()
+ private void LaunchIde(ExternalEditorId editorId, string editorIdentity)
{
- var editor = (ExternalEditorId)GodotSharpEditor.Instance.GetEditorInterface()
- .GetEditorSettings().GetSetting("mono/editor/external_editor");
-
- switch (editor)
+ switch (editorId)
{
case ExternalEditorId.None:
case ExternalEditorId.VisualStudio:
@@ -80,14 +111,14 @@ namespace GodotTools.Ides
{
MonoDevelop.Instance GetMonoDevelopInstance(string solutionPath)
{
- if (Utils.OS.IsOSX && editor == ExternalEditorId.VisualStudioForMac)
+ if (Utils.OS.IsMacOS && editorId == ExternalEditorId.VisualStudioForMac)
{
- vsForMacInstance = vsForMacInstance ??
+ vsForMacInstance = (vsForMacInstance?.IsDisposed ?? true ? null : vsForMacInstance) ??
new MonoDevelop.Instance(solutionPath, MonoDevelop.EditorId.VisualStudioForMac);
return vsForMacInstance;
}
- monoDevelInstance = monoDevelInstance ??
+ monoDevelInstance = (monoDevelInstance?.IsDisposed ?? true ? null : monoDevelInstance) ??
new MonoDevelop.Instance(solutionPath, MonoDevelop.EditorId.MonoDevelop);
return monoDevelInstance;
}
@@ -96,12 +127,25 @@ namespace GodotTools.Ides
{
var instance = GetMonoDevelopInstance(GodotSharpDirs.ProjectSlnPath);
- if (!instance.IsRunning)
+ if (instance.IsRunning && !GetRunningOrNewServer().IsAnyConnected(editorIdentity))
+ {
+ // After launch we wait up to 30 seconds for the IDE to connect to our messaging server.
+ var waitAfterLaunch = TimeSpan.FromSeconds(30);
+ var timeSinceLaunch = DateTime.Now - instance.LaunchTime;
+ if (timeSinceLaunch > waitAfterLaunch)
+ {
+ instance.Dispose();
+ instance.Execute();
+ }
+ }
+ else if (!instance.IsRunning)
+ {
instance.Execute();
+ }
}
catch (FileNotFoundException)
{
- string editorName = editor == ExternalEditorId.VisualStudioForMac ? "Visual Studio" : "MonoDevelop";
+ string editorName = editorId == ExternalEditorId.VisualStudioForMac ? "Visual Studio" : "MonoDevelop";
GD.PushError($"Cannot find code editor: {editorName}");
}
@@ -113,26 +157,45 @@ namespace GodotTools.Ides
}
}
- private void WriteMessage(string id, params string[] arguments)
+ public readonly struct EditorPick
{
- GetRunningServer().WriteMessage(new Message(id, arguments));
- }
+ private readonly string identity;
- public void SendOpenFile(string file)
- {
- WriteMessage("OpenFile", file);
- }
+ public EditorPick(string identity)
+ {
+ this.identity = identity;
+ }
- public void SendOpenFile(string file, int line)
- {
- WriteMessage("OpenFile", file, line.ToString());
- }
+ public bool IsAnyConnected() =>
+ GodotSharpEditor.Instance.GodotIdeManager.GetRunningOrNewServer().IsAnyConnected(identity);
- public void SendOpenFile(string file, int line, int column)
- {
- WriteMessage("OpenFile", file, line.ToString(), column.ToString());
+ private void SendRequest<TResponse>(Request request)
+ where TResponse : Response, new()
+ {
+ // Logs an error if no client is connected with the specified identity
+ GodotSharpEditor.Instance.GodotIdeManager
+ .GetRunningOrNewServer()
+ .BroadcastRequest<TResponse>(identity, request);
+ }
+
+ public void SendOpenFile(string file)
+ {
+ SendRequest<OpenFileResponse>(new OpenFileRequest {File = file});
+ }
+
+ public void SendOpenFile(string file, int line)
+ {
+ SendRequest<OpenFileResponse>(new OpenFileRequest {File = file, Line = line});
+ }
+
+ public void SendOpenFile(string file, int line, int column)
+ {
+ SendRequest<OpenFileResponse>(new OpenFileRequest {File = file, Line = line, Column = column});
+ }
}
+ public EditorPick PickEditor(ExternalEditorId editorId) => new EditorPick(GetExternalEditorIdentity(editorId));
+
private class GodotLogger : ILogger
{
public void LogDebug(string message)
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs
deleted file mode 100644
index 72676a8b24..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/GodotIdeServer.cs
+++ /dev/null
@@ -1,212 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using GodotTools.IdeConnection;
-using GodotTools.Internals;
-using GodotTools.Utils;
-using Directory = System.IO.Directory;
-using File = System.IO.File;
-using Thread = System.Threading.Thread;
-
-namespace GodotTools.Ides
-{
- public class GodotIdeServer : GodotIdeBase
- {
- private readonly TcpListener listener;
- private readonly FileStream metaFile;
- private readonly Action launchIdeAction;
- private readonly NotifyAwaiter<bool> clientConnectedAwaiter = new NotifyAwaiter<bool>();
-
- private async Task<bool> AwaitClientConnected()
- {
- return await clientConnectedAwaiter.Reset();
- }
-
- public GodotIdeServer(Action launchIdeAction, string editorExecutablePath, string projectMetadataDir)
- : base(projectMetadataDir)
- {
- messageHandlers = InitializeMessageHandlers();
-
- this.launchIdeAction = launchIdeAction;
-
- // Make sure the directory exists
- Directory.CreateDirectory(projectMetadataDir);
-
- // The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing...
- const FileShare metaFileShare = FileShare.ReadWrite;
-
- metaFile = File.Open(MetaFilePath, FileMode.Create, FileAccess.Write, metaFileShare);
-
- listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port: 0));
- listener.Start();
-
- int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;
- using (var metaFileWriter = new StreamWriter(metaFile, Encoding.UTF8))
- {
- metaFileWriter.WriteLine(port);
- metaFileWriter.WriteLine(editorExecutablePath);
- }
-
- StartServer();
- }
-
- public void StartServer()
- {
- var serverThread = new Thread(RunServerThread) { Name = "Godot Ide Connection Server" };
- serverThread.Start();
- }
-
- private void RunServerThread()
- {
- SynchronizationContext.SetSynchronizationContext(Godot.Dispatcher.SynchronizationContext);
-
- try
- {
- while (!IsDisposed)
- {
- TcpClient tcpClient = listener.AcceptTcpClient();
-
- Logger.LogInfo("Connection open with Ide Client");
-
- lock (ConnectionLock)
- {
- Connection = new GodotIdeConnectionServer(tcpClient, HandleMessage);
- Connection.Logger = Logger;
- }
-
- Connected += () => clientConnectedAwaiter.SetResult(true);
-
- Connection.Start();
- }
- }
- catch (Exception e)
- {
- if (!IsDisposed && !(e is SocketException se && se.SocketErrorCode == SocketError.Interrupted))
- throw;
- }
- }
-
- public async void WriteMessage(Message message)
- {
- async Task LaunchIde()
- {
- if (IsConnected)
- return;
-
- launchIdeAction();
- await Task.WhenAny(Task.Delay(10000), AwaitClientConnected());
- }
-
- await LaunchIde();
-
- if (!IsConnected)
- {
- Logger.LogError("Cannot write message: Godot Ide Server not connected");
- return;
- }
-
- Connection.WriteMessage(message);
- }
-
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
-
- if (disposing)
- {
- listener?.Stop();
-
- metaFile?.Dispose();
-
- File.Delete(MetaFilePath);
- }
- }
-
- protected virtual bool HandleMessage(Message message)
- {
- if (messageHandlers.TryGetValue(message.Id, out var action))
- {
- action(message.Arguments);
- return true;
- }
-
- return false;
- }
-
- private readonly Dictionary<string, Action<string[]>> messageHandlers;
-
- private Dictionary<string, Action<string[]>> InitializeMessageHandlers()
- {
- return new Dictionary<string, Action<string[]>>
- {
- ["Play"] = args =>
- {
- switch (args.Length)
- {
- case 0:
- Play();
- return;
- case 2:
- Play(debuggerHost: args[0], debuggerPort: int.Parse(args[1]));
- return;
- default:
- throw new ArgumentException();
- }
- },
- ["ReloadScripts"] = args => ReloadScripts()
- };
- }
-
- private void DispatchToMainThread(Action action)
- {
- var d = new SendOrPostCallback(state => action());
- Godot.Dispatcher.SynchronizationContext.Post(d, null);
- }
-
- private void Play()
- {
- DispatchToMainThread(() =>
- {
- CurrentPlayRequest = new PlayRequest();
- Internal.EditorRunPlay();
- CurrentPlayRequest = null;
- });
- }
-
- private void Play(string debuggerHost, int debuggerPort)
- {
- DispatchToMainThread(() =>
- {
- CurrentPlayRequest = new PlayRequest(debuggerHost, debuggerPort);
- Internal.EditorRunPlay();
- CurrentPlayRequest = null;
- });
- }
-
- private void ReloadScripts()
- {
- DispatchToMainThread(Internal.ScriptEditorDebugger_ReloadScripts);
- }
-
- public PlayRequest? CurrentPlayRequest { get; private set; }
-
- public struct PlayRequest
- {
- public bool HasDebugger { get; }
- public string DebuggerHost { get; }
- public int DebuggerPort { get; }
-
- public PlayRequest(string debuggerHost, int debuggerPort)
- {
- HasDebugger = true;
- DebuggerHost = debuggerHost;
- DebuggerPort = debuggerPort;
- }
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/MessagingServer.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/MessagingServer.cs
new file mode 100644
index 0000000000..eb34a2d0f7
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/MessagingServer.cs
@@ -0,0 +1,390 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading;
+using System.Threading.Tasks;
+using GodotTools.IdeMessaging;
+using GodotTools.IdeMessaging.Requests;
+using GodotTools.IdeMessaging.Utils;
+using GodotTools.Internals;
+using GodotTools.Utils;
+using Newtonsoft.Json;
+using Directory = System.IO.Directory;
+using File = System.IO.File;
+
+namespace GodotTools.Ides
+{
+ public sealed class MessagingServer : IDisposable
+ {
+ private readonly ILogger logger;
+
+ private readonly FileStream metaFile;
+ private string MetaFilePath { get; }
+
+ private readonly SemaphoreSlim peersSem = new SemaphoreSlim(1);
+
+ private readonly TcpListener listener;
+
+ private readonly Dictionary<string, Queue<NotifyAwaiter<bool>>> clientConnectedAwaiters = new Dictionary<string, Queue<NotifyAwaiter<bool>>>();
+ private readonly Dictionary<string, Queue<NotifyAwaiter<bool>>> clientDisconnectedAwaiters = new Dictionary<string, Queue<NotifyAwaiter<bool>>>();
+
+ public async Task<bool> AwaitClientConnected(string identity)
+ {
+ if (!clientConnectedAwaiters.TryGetValue(identity, out var queue))
+ {
+ queue = new Queue<NotifyAwaiter<bool>>();
+ clientConnectedAwaiters.Add(identity, queue);
+ }
+
+ var awaiter = new NotifyAwaiter<bool>();
+ queue.Enqueue(awaiter);
+ return await awaiter;
+ }
+
+ public async Task<bool> AwaitClientDisconnected(string identity)
+ {
+ if (!clientDisconnectedAwaiters.TryGetValue(identity, out var queue))
+ {
+ queue = new Queue<NotifyAwaiter<bool>>();
+ clientDisconnectedAwaiters.Add(identity, queue);
+ }
+
+ var awaiter = new NotifyAwaiter<bool>();
+ queue.Enqueue(awaiter);
+ return await awaiter;
+ }
+
+ public bool IsDisposed { get; private set; }
+
+ public bool IsAnyConnected(string identity) => string.IsNullOrEmpty(identity) ?
+ Peers.Count > 0 :
+ Peers.Any(c => c.RemoteIdentity == identity);
+
+ private List<Peer> Peers { get; } = new List<Peer>();
+
+ ~MessagingServer()
+ {
+ Dispose(disposing: false);
+ }
+
+ public async void Dispose()
+ {
+ if (IsDisposed)
+ return;
+
+ using (await peersSem.UseAsync())
+ {
+ if (IsDisposed) // lock may not be fair
+ return;
+ IsDisposed = true;
+ }
+
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ foreach (var connection in Peers)
+ connection.Dispose();
+ Peers.Clear();
+ listener?.Stop();
+
+ metaFile?.Dispose();
+
+ File.Delete(MetaFilePath);
+ }
+ }
+
+ public MessagingServer(string editorExecutablePath, string projectMetadataDir, ILogger logger)
+ {
+ this.logger = logger;
+
+ MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName);
+
+ // Make sure the directory exists
+ Directory.CreateDirectory(projectMetadataDir);
+
+ // The Godot editor's file system thread can keep the file open for writing, so we are forced to allow write sharing...
+ const FileShare metaFileShare = FileShare.ReadWrite;
+
+ metaFile = File.Open(MetaFilePath, FileMode.Create, FileAccess.Write, metaFileShare);
+
+ listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port: 0));
+ listener.Start();
+
+ int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;
+ using (var metaFileWriter = new StreamWriter(metaFile, Encoding.UTF8))
+ {
+ metaFileWriter.WriteLine(port);
+ metaFileWriter.WriteLine(editorExecutablePath);
+ }
+ }
+
+ private async Task AcceptClient(TcpClient tcpClient)
+ {
+ logger.LogDebug("Accept client...");
+
+ using (var peer = new Peer(tcpClient, new ServerHandshake(), new ServerMessageHandler(), logger))
+ {
+ // ReSharper disable AccessToDisposedClosure
+ peer.Connected += () =>
+ {
+ logger.LogInfo("Connection open with Ide Client");
+
+ if (clientConnectedAwaiters.TryGetValue(peer.RemoteIdentity, out var queue))
+ {
+ while (queue.Count > 0)
+ queue.Dequeue().SetResult(true);
+ clientConnectedAwaiters.Remove(peer.RemoteIdentity);
+ }
+ };
+
+ peer.Disconnected += () =>
+ {
+ if (clientDisconnectedAwaiters.TryGetValue(peer.RemoteIdentity, out var queue))
+ {
+ while (queue.Count > 0)
+ queue.Dequeue().SetResult(true);
+ clientDisconnectedAwaiters.Remove(peer.RemoteIdentity);
+ }
+ };
+ // ReSharper restore AccessToDisposedClosure
+
+ try
+ {
+ if (!await peer.DoHandshake("server"))
+ {
+ logger.LogError("Handshake failed");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ logger.LogError("Handshake failed with unhandled exception: ", e);
+ return;
+ }
+
+ using (await peersSem.UseAsync())
+ Peers.Add(peer);
+
+ try
+ {
+ await peer.Process();
+ }
+ finally
+ {
+ using (await peersSem.UseAsync())
+ Peers.Remove(peer);
+ }
+ }
+ }
+
+ public async Task Listen()
+ {
+ try
+ {
+ while (!IsDisposed)
+ _ = AcceptClient(await listener.AcceptTcpClientAsync());
+ }
+ catch (Exception e)
+ {
+ if (!IsDisposed && !(e is SocketException se && se.SocketErrorCode == SocketError.Interrupted))
+ throw;
+ }
+ }
+
+ public async void BroadcastRequest<TResponse>(string identity, Request request)
+ where TResponse : Response, new()
+ {
+ using (await peersSem.UseAsync())
+ {
+ if (!IsAnyConnected(identity))
+ {
+ logger.LogError("Cannot write request. No client connected to the Godot Ide Server.");
+ return;
+ }
+
+ var selectedConnections = string.IsNullOrEmpty(identity) ?
+ Peers :
+ Peers.Where(c => c.RemoteIdentity == identity);
+
+ string body = JsonConvert.SerializeObject(request);
+
+ foreach (var connection in selectedConnections)
+ _ = connection.SendRequest<TResponse>(request.Id, body);
+ }
+ }
+
+ private class ServerHandshake : IHandshake
+ {
+ private static readonly string ServerHandshakeBase = $"{Peer.ServerHandshakeName},Version={Peer.ProtocolVersionMajor}.{Peer.ProtocolVersionMinor}.{Peer.ProtocolVersionRevision}";
+ private static readonly string ClientHandshakePattern = $@"{Regex.Escape(Peer.ClientHandshakeName)},Version=([0-9]+)\.([0-9]+)\.([0-9]+),([_a-zA-Z][_a-zA-Z0-9]{{0,63}})";
+
+ public string GetHandshakeLine(string identity) => $"{ServerHandshakeBase},{identity}";
+
+ public bool IsValidPeerHandshake(string handshake, out string identity, ILogger logger)
+ {
+ identity = null;
+
+ var match = Regex.Match(handshake, ClientHandshakePattern);
+
+ if (!match.Success)
+ return false;
+
+ if (!uint.TryParse(match.Groups[1].Value, out uint clientMajor) || Peer.ProtocolVersionMajor != clientMajor)
+ {
+ logger.LogDebug("Incompatible major version: " + match.Groups[1].Value);
+ return false;
+ }
+
+ // ReSharper disable once ConditionIsAlwaysTrueOrFalse
+ if (!uint.TryParse(match.Groups[2].Value, out uint clientMinor) || Peer.ProtocolVersionMinor > clientMinor)
+ {
+ logger.LogDebug("Incompatible minor version: " + match.Groups[2].Value);
+ return false;
+ }
+
+ if (!uint.TryParse(match.Groups[3].Value, out uint _)) // Revision
+ {
+ logger.LogDebug("Incompatible revision build: " + match.Groups[3].Value);
+ return false;
+ }
+
+ identity = match.Groups[4].Value;
+
+ return true;
+ }
+ }
+
+ private class ServerMessageHandler : IMessageHandler
+ {
+ private static void DispatchToMainThread(Action action)
+ {
+ var d = new SendOrPostCallback(state => action());
+ Godot.Dispatcher.SynchronizationContext.Post(d, null);
+ }
+
+ private readonly Dictionary<string, Peer.RequestHandler> requestHandlers = InitializeRequestHandlers();
+
+ public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
+ {
+ if (!requestHandlers.TryGetValue(id, out var handler))
+ {
+ logger.LogError($"Received unknown request: {id}");
+ return new MessageContent(MessageStatus.RequestNotSupported, "null");
+ }
+
+ try
+ {
+ var response = await handler(peer, content);
+ return new MessageContent(response.Status, JsonConvert.SerializeObject(response));
+ }
+ catch (JsonException)
+ {
+ logger.LogError($"Received request with invalid body: {id}");
+ return new MessageContent(MessageStatus.InvalidRequestBody, "null");
+ }
+ }
+
+ private static Dictionary<string, Peer.RequestHandler> InitializeRequestHandlers()
+ {
+ return new Dictionary<string, Peer.RequestHandler>
+ {
+ [PlayRequest.Id] = async (peer, content) =>
+ {
+ _ = JsonConvert.DeserializeObject<PlayRequest>(content.Body);
+ return await HandlePlay();
+ },
+ [DebugPlayRequest.Id] = async (peer, content) =>
+ {
+ var request = JsonConvert.DeserializeObject<DebugPlayRequest>(content.Body);
+ return await HandleDebugPlay(request);
+ },
+ [StopPlayRequest.Id] = async (peer, content) =>
+ {
+ var request = JsonConvert.DeserializeObject<StopPlayRequest>(content.Body);
+ return await HandleStopPlay(request);
+ },
+ [ReloadScriptsRequest.Id] = async (peer, content) =>
+ {
+ _ = JsonConvert.DeserializeObject<ReloadScriptsRequest>(content.Body);
+ return await HandleReloadScripts();
+ },
+ [CodeCompletionRequest.Id] = async (peer, content) =>
+ {
+ var request = JsonConvert.DeserializeObject<CodeCompletionRequest>(content.Body);
+ return await HandleCodeCompletionRequest(request);
+ }
+ };
+ }
+
+ private static Task<Response> HandlePlay()
+ {
+ DispatchToMainThread(() =>
+ {
+ // TODO: Add BuildBeforePlaying flag to PlayRequest
+
+ // Run the game
+ Internal.EditorRunPlay();
+ });
+ return Task.FromResult<Response>(new PlayResponse());
+ }
+
+ private static Task<Response> HandleDebugPlay(DebugPlayRequest request)
+ {
+ DispatchToMainThread(() =>
+ {
+ // Tell the build callback whether the editor already built the solution or not
+ GodotSharpEditor.Instance.SkipBuildBeforePlaying = !(request.BuildBeforePlaying ?? true);
+
+ // Pass the debugger agent settings to the player via an environment variables
+ // TODO: It would be better if this was an argument in EditorRunPlay instead
+ Environment.SetEnvironmentVariable("GODOT_MONO_DEBUGGER_AGENT",
+ "--debugger-agent=transport=dt_socket" +
+ $",address={request.DebuggerHost}:{request.DebuggerPort}" +
+ ",server=n");
+
+ // Run the game
+ Internal.EditorRunPlay();
+
+ // Restore normal settings
+ Environment.SetEnvironmentVariable("GODOT_MONO_DEBUGGER_AGENT", "");
+ GodotSharpEditor.Instance.SkipBuildBeforePlaying = false;
+ });
+ return Task.FromResult<Response>(new DebugPlayResponse());
+ }
+
+ private static Task<Response> HandleStopPlay(StopPlayRequest request)
+ {
+ DispatchToMainThread(Internal.EditorRunStop);
+ return Task.FromResult<Response>(new StopPlayResponse());
+ }
+
+ private static Task<Response> HandleReloadScripts()
+ {
+ DispatchToMainThread(Internal.ScriptEditorDebugger_ReloadScripts);
+ return Task.FromResult<Response>(new ReloadScriptsResponse());
+ }
+
+ private static async Task<Response> HandleCodeCompletionRequest(CodeCompletionRequest request)
+ {
+ // This is needed if the "resource path" part of the path is case insensitive.
+ // However, it doesn't fix resource loading if the rest of the path is also case insensitive.
+ string scriptFileLocalized = FsPathUtils.LocalizePathWithCaseChecked(request.ScriptFile);
+
+ var response = new CodeCompletionResponse {Kind = request.Kind, ScriptFile = request.ScriptFile};
+ response.Suggestions = await Task.Run(() =>
+ Internal.CodeCompletionRequest(response.Kind, scriptFileLocalized ?? request.ScriptFile));
+ return response;
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs
index 6026c109ad..fd7bbd5578 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/MonoDevelop/Instance.cs
@@ -7,14 +7,16 @@ using GodotTools.Utils;
namespace GodotTools.Ides.MonoDevelop
{
- public class Instance
+ public class Instance : IDisposable
{
+ public DateTime LaunchTime { get; private set; }
private readonly string solutionFile;
private readonly EditorId editorId;
private Process process;
public bool IsRunning => process != null && !process.HasExited;
+ public bool IsDisposed { get; private set; }
public void Execute()
{
@@ -24,7 +26,7 @@ namespace GodotTools.Ides.MonoDevelop
string command;
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
string bundleId = BundleIds[editorId];
@@ -59,6 +61,8 @@ namespace GodotTools.Ides.MonoDevelop
if (command == null)
throw new FileNotFoundException();
+ LaunchTime = DateTime.Now;
+
if (newWindow)
{
process = Process.Start(new ProcessStartInfo
@@ -81,19 +85,25 @@ namespace GodotTools.Ides.MonoDevelop
public Instance(string solutionFile, EditorId editorId)
{
- if (editorId == EditorId.VisualStudioForMac && !OS.IsOSX)
+ if (editorId == EditorId.VisualStudioForMac && !OS.IsMacOS)
throw new InvalidOperationException($"{nameof(EditorId.VisualStudioForMac)} not supported on this platform");
this.solutionFile = solutionFile;
this.editorId = editorId;
}
+ public void Dispose()
+ {
+ IsDisposed = true;
+ process?.Dispose();
+ }
+
private static readonly IReadOnlyDictionary<EditorId, string> ExecutableNames;
private static readonly IReadOnlyDictionary<EditorId, string> BundleIds;
static Instance()
{
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
ExecutableNames = new Dictionary<EditorId, string>
{
@@ -118,7 +128,7 @@ namespace GodotTools.Ides.MonoDevelop
{EditorId.MonoDevelop, "MonoDevelop.exe"}
};
}
- else if (OS.IsUnixLike())
+ else if (OS.IsUnixLike)
{
ExecutableNames = new Dictionary<EditorId, string>
{
diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
index e3a4fa7b45..94fc5da425 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs
@@ -32,11 +32,11 @@ namespace GodotTools.Ides.Rider
{
return CollectRiderInfosWindows();
}
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
return CollectRiderInfosMac();
}
- if (OS.IsUnixLike())
+ if (OS.IsUnixLike)
{
return CollectAllRiderPathsLinux();
}
@@ -138,19 +138,19 @@ namespace GodotTools.Ides.Rider
return GetToolboxRiderRootPath(localAppData);
}
- if (OS.IsOSX)
+ if (OS.IsMacOS)
{
var home = Environment.GetEnvironmentVariable("HOME");
- if (string.IsNullOrEmpty(home))
+ if (string.IsNullOrEmpty(home))
return string.Empty;
var localAppData = Path.Combine(home, @"Library/Application Support");
return GetToolboxRiderRootPath(localAppData);
}
- if (OS.IsUnixLike())
+ if (OS.IsUnixLike)
{
var home = Environment.GetEnvironmentVariable("HOME");
- if (string.IsNullOrEmpty(home))
+ if (string.IsNullOrEmpty(home))
return string.Empty;
var localAppData = Path.Combine(home, @".local/share");
return GetToolboxRiderRootPath(localAppData);
@@ -209,9 +209,9 @@ namespace GodotTools.Ides.Rider
private static string GetRelativePathToBuildTxt()
{
- if (OS.IsWindows || OS.IsUnixLike())
+ if (OS.IsWindows || OS.IsUnixLike)
return "../../build.txt";
- if (OS.IsOSX)
+ if (OS.IsMacOS)
return "Contents/Resources/build.txt";
throw new Exception("Unknown OS.");
}
@@ -322,7 +322,7 @@ namespace GodotTools.Ides.Rider
class SettingsJson
{
public string install_location;
-
+
[CanBeNull]
public static string GetInstallLocationFromJson(string json)
{
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
index 026a7db89c..7e5049e4b7 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
@@ -2,6 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using Godot;
using Godot.Collections;
+using GodotTools.IdeMessaging.Requests;
namespace GodotTools.Internals
{
@@ -52,6 +53,9 @@ namespace GodotTools.Internals
public static void ScriptEditorDebugger_ReloadScripts() => internal_ScriptEditorDebugger_ReloadScripts();
+ public static string[] CodeCompletionRequest(CodeCompletionRequest.CompletionKind kind, string scriptFile) =>
+ internal_CodeCompletionRequest((int)kind, scriptFile);
+
#region Internal
[MethodImpl(MethodImplOptions.InternalCall)]
@@ -111,6 +115,9 @@ namespace GodotTools.Internals
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void internal_ScriptEditorDebugger_ReloadScripts();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string[] internal_CodeCompletionRequest(int kind, string scriptFile);
+
#endregion
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs
index 7fb087467f..c72a84c513 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs
@@ -13,9 +13,13 @@ namespace GodotTools.Internals
public string Name { get; }
public string Namespace { get; }
public bool Nested { get; }
- public int BaseCount { get; }
+ public long BaseCount { get; }
- public ClassDecl(string name, string @namespace, bool nested, int baseCount)
+ public string SearchName => Nested ?
+ Name.Substring(Name.LastIndexOf(".", StringComparison.Ordinal) + 1) :
+ Name;
+
+ public ClassDecl(string name, string @namespace, bool nested, long baseCount)
{
Name = name;
Namespace = @namespace;
@@ -45,7 +49,7 @@ namespace GodotTools.Internals
(string)classDeclDict["name"],
(string)classDeclDict["namespace"],
(bool)classDeclDict["nested"],
- (int)classDeclDict["base_count"]
+ (long)classDeclDict["base_count"]
));
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/PlaySettings.cs b/modules/mono/editor/GodotTools/GodotTools/PlaySettings.cs
new file mode 100644
index 0000000000..820d0c0b83
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/PlaySettings.cs
@@ -0,0 +1,19 @@
+namespace GodotTools
+{
+ public struct PlaySettings
+ {
+ public bool HasDebugger { get; }
+ public string DebuggerHost { get; }
+ public int DebuggerPort { get; }
+
+ public bool BuildBeforePlaying { get; }
+
+ public PlaySettings(string debuggerHost, int debuggerPort, bool buildBeforePlaying)
+ {
+ HasDebugger = true;
+ DebuggerHost = debuggerHost;
+ DebuggerPort = debuggerPort;
+ BuildBeforePlaying = buildBeforePlaying;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs
deleted file mode 100644
index f5fe85c722..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-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/FsPathUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs
new file mode 100644
index 0000000000..c6724ccaf7
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/FsPathUtils.cs
@@ -0,0 +1,48 @@
+using System;
+using System.IO;
+using Godot;
+using GodotTools.Core;
+using JetBrains.Annotations;
+
+namespace GodotTools.Utils
+{
+ public static class FsPathUtils
+ {
+ private static readonly string ResourcePath = ProjectSettings.GlobalizePath("res://");
+
+ private static bool PathStartsWithAlreadyNorm(this string childPath, string parentPath)
+ {
+ // This won't work for Linux/macOS case insensitive file systems, but it's enough for our current problems
+ bool caseSensitive = !OS.IsWindows;
+
+ string parentPathNorm = parentPath.NormalizePath() + Path.DirectorySeparatorChar;
+ string childPathNorm = childPath.NormalizePath() + Path.DirectorySeparatorChar;
+
+ return childPathNorm.StartsWith(parentPathNorm,
+ caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool PathStartsWith(this string childPath, string parentPath)
+ {
+ string childPathNorm = childPath.NormalizePath() + Path.DirectorySeparatorChar;
+ string parentPathNorm = parentPath.NormalizePath() + Path.DirectorySeparatorChar;
+
+ return childPathNorm.PathStartsWithAlreadyNorm(parentPathNorm);
+ }
+
+ [CanBeNull]
+ public static string LocalizePathWithCaseChecked(string path)
+ {
+ string pathNorm = path.NormalizePath() + Path.DirectorySeparatorChar;
+ string resourcePathNorm = ResourcePath.NormalizePath() + Path.DirectorySeparatorChar;
+
+ if (!pathNorm.PathStartsWithAlreadyNorm(resourcePathNorm))
+ return null;
+
+ string result = "res://" + pathNorm.Substring(resourcePathNorm.Length);
+
+ // Remove the last separator we added
+ return result.Substring(0, result.Length - 1);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
index b057ac12c6..e745966435 100644
--- a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
@@ -21,8 +21,11 @@ namespace GodotTools.Utils
public static class Names
{
public const string Windows = "Windows";
- public const string OSX = "OSX";
- public const string X11 = "X11";
+ public const string MacOS = "macOS";
+ public const string Linux = "Linux";
+ public const string FreeBSD = "FreeBSD";
+ public const string NetBSD = "NetBSD";
+ public const string BSD = "BSD";
public const string Server = "Server";
public const string UWP = "UWP";
public const string Haiku = "Haiku";
@@ -34,8 +37,8 @@ namespace GodotTools.Utils
public static class Platforms
{
public const string Windows = "windows";
- public const string OSX = "osx";
- public const string X11 = "linuxbsd";
+ public const string MacOS = "osx";
+ public const string LinuxBSD = "linuxbsd";
public const string Server = "server";
public const string UWP = "uwp";
public const string Haiku = "haiku";
@@ -47,8 +50,11 @@ namespace GodotTools.Utils
public static readonly Dictionary<string, string> PlatformNameMap = new Dictionary<string, string>
{
[Names.Windows] = Platforms.Windows,
- [Names.OSX] = Platforms.OSX,
- [Names.X11] = Platforms.X11,
+ [Names.MacOS] = Platforms.MacOS,
+ [Names.Linux] = Platforms.LinuxBSD,
+ [Names.FreeBSD] = Platforms.LinuxBSD,
+ [Names.NetBSD] = Platforms.LinuxBSD,
+ [Names.BSD] = Platforms.LinuxBSD,
[Names.Server] = Platforms.Server,
[Names.UWP] = Platforms.UWP,
[Names.Haiku] = Platforms.Haiku,
@@ -62,38 +68,39 @@ namespace GodotTools.Utils
return name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
}
+ private static bool IsAnyOS(IEnumerable<string> names)
+ {
+ return names.Any(p => p.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase));
+ }
+
+ private static readonly IEnumerable<string> LinuxBSDPlatforms =
+ new[] {Names.Linux, Names.FreeBSD, Names.NetBSD, Names.BSD};
+
+ private static readonly IEnumerable<string> UnixLikePlatforms =
+ new[] {Names.MacOS, Names.Server, Names.Haiku, Names.Android, Names.iOS}
+ .Concat(LinuxBSDPlatforms).ToArray();
+
private static readonly Lazy<bool> _isWindows = new Lazy<bool>(() => IsOS(Names.Windows));
- private static readonly Lazy<bool> _isOSX = new Lazy<bool>(() => IsOS(Names.OSX));
- private static readonly Lazy<bool> _isX11 = new Lazy<bool>(() => IsOS(Names.X11));
+ private static readonly Lazy<bool> _isMacOS = new Lazy<bool>(() => IsOS(Names.MacOS));
+ private static readonly Lazy<bool> _isLinuxBSD = new Lazy<bool>(() => IsAnyOS(LinuxBSDPlatforms));
private static readonly Lazy<bool> _isServer = new Lazy<bool>(() => IsOS(Names.Server));
private static readonly Lazy<bool> _isUWP = new Lazy<bool>(() => IsOS(Names.UWP));
private static readonly Lazy<bool> _isHaiku = new Lazy<bool>(() => IsOS(Names.Haiku));
private static readonly Lazy<bool> _isAndroid = new Lazy<bool>(() => IsOS(Names.Android));
private static readonly Lazy<bool> _isiOS = new Lazy<bool>(() => IsOS(Names.iOS));
private static readonly Lazy<bool> _isHTML5 = new Lazy<bool>(() => IsOS(Names.HTML5));
+ private static readonly Lazy<bool> _isUnixLike = new Lazy<bool>(() => IsAnyOS(UnixLikePlatforms));
public static bool IsWindows => _isWindows.Value || IsUWP;
- public static bool IsOSX => _isOSX.Value;
- public static bool IsX11 => _isX11.Value;
+ public static bool IsMacOS => _isMacOS.Value;
+ public static bool IsLinuxBSD => _isLinuxBSD.Value;
public static bool IsServer => _isServer.Value;
public static bool IsUWP => _isUWP.Value;
public static bool IsHaiku => _isHaiku.Value;
public static bool IsAndroid => _isAndroid.Value;
public static bool IsiOS => _isiOS.Value;
public static bool IsHTML5 => _isHTML5.Value;
-
- private static bool? _isUnixCache;
- private static readonly string[] UnixLikePlatforms = { Names.OSX, Names.X11, Names.Server, Names.Haiku, Names.Android, Names.iOS };
-
- public static bool IsUnixLike()
- {
- if (_isUnixCache.HasValue)
- return _isUnixCache.Value;
-
- string osName = GetPlatformName();
- _isUnixCache = UnixLikePlatforms.Any(p => p.Equals(osName, StringComparison.OrdinalIgnoreCase));
- return _isUnixCache.Value;
- }
+ public static bool IsUnixLike => _isUnixLike.Value;
public static char PathSep => IsWindows ? ';' : ':';
@@ -121,10 +128,10 @@ namespace GodotTools.Utils
return searchDirs.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists);
return (from dir in searchDirs
- select Path.Combine(dir, name)
+ select Path.Combine(dir, name)
into path
- from ext in windowsExts
- select path + ext).FirstOrDefault(File.Exists);
+ from ext in windowsExts
+ select path + ext).FirstOrDefault(File.Exists);
}
private static string PathWhichUnix([NotNull] string name)
@@ -189,7 +196,7 @@ namespace GodotTools.Utils
startInfo.UseShellExecute = false;
- using (var process = new Process { StartInfo = startInfo })
+ using (var process = new Process {StartInfo = startInfo})
{
process.Start();
process.WaitForExit();
diff --git a/modules/mono/editor/GodotTools/GodotTools/packages.config b/modules/mono/editor/GodotTools/GodotTools/packages.config
deleted file mode 100644
index dd3de2865a..0000000000
--- a/modules/mono/editor/GodotTools/GodotTools/packages.config
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<packages>
- <package id="JetBrains.Annotations" version="2019.1.3" targetFramework="net45" />
- <package id="Newtonsoft.Json" version="12.0.3" targetFramework="net45" />
-</packages>
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index bdf9cf965f..38e403b2e1 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,20 +32,19 @@
#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
-#include "core/engine.h"
-#include "core/global_constants.h"
+#include "core/config/engine.h"
+#include "core/core_constants.h"
#include "core/io/compression.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/ucaps.h"
+#include "core/string/ucaps.h"
#include "../glue/cs_glue_version.gen.h"
#include "../godotsharp_defs.h"
#include "../mono_gd/gd_mono_marshal.h"
#include "../utils/path_utils.h"
#include "../utils/string_utils.h"
-#include "csharp_project.h"
#define CS_INDENT " " // 4 whitespaces
@@ -62,10 +61,8 @@
#define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK INDENT3
#define OPEN_BLOCK_L3 INDENT3 OPEN_BLOCK INDENT4
-#define OPEN_BLOCK_L4 INDENT4 OPEN_BLOCK INDENT5
#define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
#define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
-#define CLOSE_BLOCK_L4 INDENT4 CLOSE_BLOCK
#define CS_FIELD_MEMORYOWN "memoryOwn"
#define CS_PARAM_METHODBIND "method"
@@ -100,12 +97,11 @@
#define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL "::signal_info_to_callable"
#define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL "::callable_to_signal_info"
-#define BINDINGS_GENERATOR_VERSION UINT32_C(11)
+#define BINDINGS_GENERATOR_VERSION UINT32_C(13)
const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN("\t%0 %1_in = %1;\n");
static String fix_doc_description(const String &p_bbcode) {
-
// This seems to be the correct way to do this. It's the same EditorHelp does.
return p_bbcode.dedent()
@@ -115,7 +111,6 @@ static String fix_doc_description(const String &p_bbcode) {
}
static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_upper = false) {
-
String ret;
Vector<String> parts = p_identifier.split("_", true);
@@ -125,8 +120,9 @@ static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_u
if (part.length()) {
part[0] = _find_upper(part[0]);
if (p_input_is_upper) {
- for (int j = 1; j < part.length(); j++)
+ for (int j = 1; j < part.length(); j++) {
part[j] = _find_lower(part[j]);
+ }
}
ret += part;
} else {
@@ -148,7 +144,6 @@ static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_u
}
static String snake_to_camel_case(const String &p_identifier, bool p_input_is_upper = false) {
-
String ret;
Vector<String> parts = p_identifier.split("_", true);
@@ -160,8 +155,9 @@ static String snake_to_camel_case(const String &p_identifier, bool p_input_is_up
part[0] = _find_upper(part[0]);
}
if (p_input_is_upper) {
- for (int j = i != 0 ? 1 : 0; j < part.length(); j++)
+ for (int j = i != 0 ? 1 : 0; j < part.length(); j++) {
part[j] = _find_lower(part[j]);
+ }
}
ret += part;
} else {
@@ -183,13 +179,13 @@ static String snake_to_camel_case(const String &p_identifier, bool p_input_is_up
}
String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype) {
-
// Based on the version in EditorHelp
- if (p_bbcode.empty())
+ if (p_bbcode.is_empty()) {
return String();
+ }
- DocData *doc = EditorHelp::get_doc_data();
+ DocTools *doc = EditorHelp::get_doc_data();
String bbcode = p_bbcode;
@@ -204,8 +200,9 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
while (pos < bbcode.length()) {
int brk_pos = bbcode.find("[", pos);
- if (brk_pos < 0)
+ if (brk_pos < 0) {
brk_pos = bbcode.length();
+ }
if (brk_pos > pos) {
String text = bbcode.substr(pos, brk_pos - pos);
@@ -214,19 +211,22 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
} else {
Vector<String> lines = text.split("\n");
for (int i = 0; i < lines.size(); i++) {
- if (i != 0)
+ if (i != 0) {
xml_output.append("<para>");
+ }
xml_output.append(lines[i].xml_escape());
- if (i != lines.size() - 1)
+ if (i != lines.size() - 1) {
xml_output.append("</para>\n");
+ }
}
}
}
- if (brk_pos == bbcode.length())
+ if (brk_pos == bbcode.length()) {
break; // nothing else to add
+ }
int brk_end = bbcode.find("]", brk_pos + 1);
@@ -237,13 +237,15 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
} else {
Vector<String> lines = text.split("\n");
for (int i = 0; i < lines.size(); i++) {
- if (i != 0)
+ if (i != 0) {
xml_output.append("<para>");
+ }
xml_output.append(lines[i].xml_escape());
- if (i != lines.size() - 1)
+ if (i != lines.size() - 1) {
xml_output.append("</para>\n");
+ }
}
}
@@ -363,7 +365,7 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
xml_output.append("</c>");
} else if (link_tag == "enum") {
StringName search_cname = !target_itype ? target_cname :
- StringName(target_itype->name + "." + (String)target_cname);
+ StringName(target_itype->name + "." + (String)target_cname);
const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(search_cname);
@@ -416,8 +418,9 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
for (const List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
target_ienum = &E->get();
target_iconst = find_constant_by_name(target_name, target_ienum->constants);
- if (target_iconst)
+ if (target_iconst) {
break;
+ }
}
if (target_iconst) {
@@ -454,8 +457,9 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
for (const List<EnumInterface>::Element *E = target_itype->enums.front(); E; E = E->next()) {
target_ienum = &E->get();
target_iconst = find_constant_by_name(target_name, target_ienum->constants);
- if (target_iconst)
+ if (target_iconst) {
break;
+ }
}
if (target_iconst) {
@@ -587,8 +591,9 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
tag_stack.push_front(tag);
} else if (tag == "url") {
int end = bbcode.find("[", brk_end);
- if (end == -1)
+ if (end == -1) {
end = bbcode.length();
+ }
String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
xml_output.append("<a href=\"");
xml_output.append(url);
@@ -607,8 +612,9 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
tag_stack.push_front("url");
} else if (tag == "img") {
int end = bbcode.find("[", brk_end);
- if (end == -1)
+ if (end == -1) {
end = bbcode.length();
+ }
String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
// Not supported. Just append the bbcode.
@@ -638,15 +644,15 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf
}
int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
-
- CRASH_COND(p_ienum.constants.empty());
+ CRASH_COND(p_ienum.constants.is_empty());
const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
int candidate_len = front_parts.size() - 1;
- if (candidate_len == 0)
+ if (candidate_len == 0) {
return 0;
+ }
for (const List<ConstantInterface>::Element *E = p_ienum.constants.front()->next(); E; E = E->next()) {
const ConstantInterface &iconstant = E->get();
@@ -658,21 +664,22 @@ int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
if (front_parts[i] != parts[i]) {
// HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
- if (!hardcoded_exc)
+ if (!hardcoded_exc) {
break;
+ }
}
}
candidate_len = i;
- if (candidate_len == 0)
+ if (candidate_len == 0) {
return 0;
+ }
}
return candidate_len;
}
void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
-
if (p_prefix_length > 0) {
for (List<ConstantInterface>::Element *E = p_ienum.constants.front(); E; E = E->next()) {
int curr_prefix_length = p_prefix_length;
@@ -683,22 +690,25 @@ void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumI
Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
- if (parts.size() <= curr_prefix_length)
+ if (parts.size() <= curr_prefix_length) {
continue;
+ }
if (parts[curr_prefix_length][0] >= '0' && parts[curr_prefix_length][0] <= '9') {
// The name of enum constants may begin with a numeric digit when strip from the enum prefix,
// so we make the prefix for this constant one word shorter in those cases.
for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
- if (parts[curr_prefix_length][0] < '0' || parts[curr_prefix_length][0] > '9')
+ if (parts[curr_prefix_length][0] < '0' || parts[curr_prefix_length][0] > '9') {
break;
+ }
}
}
constant_name = "";
for (int i = curr_prefix_length; i < parts.size(); i++) {
- if (i > curr_prefix_length)
+ if (i > curr_prefix_length) {
constant_name += "_";
+ }
constant_name += parts[i];
}
@@ -708,12 +718,12 @@ void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumI
}
void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
-
for (const List<MethodInterface>::Element *E = p_itype.methods.front(); E; E = E->next()) {
const MethodInterface &imethod = E->get();
- if (imethod.is_virtual)
+ if (imethod.is_virtual) {
continue;
+ }
const TypeInterface *return_type = _get_type_or_placeholder(imethod.return_type);
@@ -762,8 +772,9 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
List<InternalCall>::Element *match = method_icalls.find(im_icall);
if (match) {
- if (p_itype.api_type != ClassDB::API_EDITOR)
+ if (p_itype.api_type != ClassDB::API_EDITOR) {
match->get().editor_only = false;
+ }
method_icalls_map.insert(&E->get(), &match->get());
} else {
List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
@@ -773,7 +784,6 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) {
}
void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
-
// Constants (in partial GD class)
p_output.append("\n#pragma warning disable CS1591 // Disable warning: "
@@ -809,8 +819,9 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
p_output.append(";");
}
- if (!global_constants.empty())
+ if (!global_constants.is_empty()) {
p_output.append("\n");
+ }
p_output.append(INDENT1 CLOSE_BLOCK); // end of GD class
@@ -819,7 +830,7 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) {
const EnumInterface &ienum = E->get();
- CRASH_COND(ienum.constants.empty());
+ CRASH_COND(ienum.constants.is_empty());
String enum_proxy_name = ienum.cname.operator String();
@@ -872,8 +883,9 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
p_output.append(INDENT1 CLOSE_BLOCK);
- if (enum_in_static_class)
+ if (enum_in_static_class) {
p_output.append(INDENT1 CLOSE_BLOCK);
+ }
}
p_output.append(CLOSE_BLOCK); // end of namespace
@@ -882,7 +894,6 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
}
Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
-
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -908,8 +919,9 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
_generate_global_constants(constants_source);
String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
Error save_err = _save_file(output_file, constants_source);
- if (save_err != OK)
+ if (save_err != OK) {
return save_err;
+ }
compile_items.push_back(output_file);
}
@@ -917,17 +929,20 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
const TypeInterface &itype = E.get();
- if (itype.api_type == ClassDB::API_EDITOR)
+ if (itype.api_type == ClassDB::API_EDITOR) {
continue;
+ }
String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
- if (err == ERR_SKIP)
+ if (err == ERR_SKIP) {
continue;
+ }
- if (err != OK)
+ if (err != OK) {
return err;
+ }
compile_items.push_back(output_file);
}
@@ -958,10 +973,12 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
cs_icalls_content.append(m_icall.im_sig + ");\n"); \
}
- for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next())
+ for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) {
ADD_INTERNAL_CALL(E->get());
- for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
+ }
+ for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) {
ADD_INTERNAL_CALL(E->get());
+ }
#undef ADD_INTERNAL_CALL
@@ -970,8 +987,9 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
- if (err != OK)
+ if (err != OK) {
return err;
+ }
compile_items.push_back(internal_methods_file);
@@ -990,14 +1008,14 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
err = _save_file(includes_props_file, includes_props_content);
- if (err != OK)
+ if (err != OK) {
return err;
+ }
return OK;
}
Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
-
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -1020,17 +1038,20 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
const TypeInterface &itype = E.get();
- if (itype.api_type != ClassDB::API_EDITOR)
+ if (itype.api_type != ClassDB::API_EDITOR) {
continue;
+ }
String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
- if (err == ERR_SKIP)
+ if (err == ERR_SKIP) {
continue;
+ }
- if (err != OK)
+ if (err != OK) {
return err;
+ }
compile_items.push_back(output_file);
}
@@ -1060,10 +1081,12 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
cs_icalls_content.append(m_icall.im_sig + ");\n"); \
}
- for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next())
+ for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) {
ADD_INTERNAL_CALL(E->get());
- for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next())
+ }
+ for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) {
ADD_INTERNAL_CALL(E->get());
+ }
#undef ADD_INTERNAL_CALL
@@ -1072,8 +1095,9 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
- if (err != OK)
+ if (err != OK) {
return err;
+ }
compile_items.push_back(internal_methods_file);
@@ -1092,14 +1116,14 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
err = _save_file(includes_props_file, includes_props_content);
- if (err != OK)
+ if (err != OK) {
return err;
+ }
return OK;
}
Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
-
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
String output_dir = path::abspath(path::realpath(p_output_dir));
@@ -1147,7 +1171,6 @@ Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
// - Csc warning e.g.:
// ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
-
CRASH_COND(!itype.is_object_type);
bool is_derived_type = itype.base_name != StringName();
@@ -1222,93 +1245,89 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
output.append(INDENT1 "{");
- if (class_doc) {
-
- // Add constants
+ // Add constants
- for (const List<ConstantInterface>::Element *E = itype.constants.front(); E; E = E->next()) {
- const ConstantInterface &iconstant = E->get();
-
- if (iconstant.const_doc && iconstant.const_doc->description.size()) {
- String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
- Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
+ for (const List<ConstantInterface>::Element *E = itype.constants.front(); E; E = E->next()) {
+ const ConstantInterface &iconstant = E->get();
- if (summary_lines.size()) {
- output.append(MEMBER_BEGIN "/// <summary>\n");
+ if (iconstant.const_doc && iconstant.const_doc->description.size()) {
+ String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
+ Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
- for (int i = 0; i < summary_lines.size(); i++) {
- output.append(INDENT2 "/// ");
- output.append(summary_lines[i]);
- output.append("\n");
- }
+ if (summary_lines.size()) {
+ output.append(MEMBER_BEGIN "/// <summary>\n");
- output.append(INDENT2 "/// </summary>");
+ for (int i = 0; i < summary_lines.size(); i++) {
+ output.append(INDENT2 "/// ");
+ output.append(summary_lines[i]);
+ output.append("\n");
}
- }
- output.append(MEMBER_BEGIN "public const int ");
- output.append(iconstant.proxy_name);
- output.append(" = ");
- output.append(itos(iconstant.value));
- output.append(";");
+ output.append(INDENT2 "/// </summary>");
+ }
}
- if (itype.constants.size())
- output.append("\n");
+ output.append(MEMBER_BEGIN "public const int ");
+ output.append(iconstant.proxy_name);
+ output.append(" = ");
+ output.append(itos(iconstant.value));
+ output.append(";");
+ }
- // Add enums
+ if (itype.constants.size()) {
+ output.append("\n");
+ }
- for (const List<EnumInterface>::Element *E = itype.enums.front(); E; E = E->next()) {
- const EnumInterface &ienum = E->get();
+ // Add enums
- ERR_FAIL_COND_V(ienum.constants.empty(), ERR_BUG);
+ for (const List<EnumInterface>::Element *E = itype.enums.front(); E; E = E->next()) {
+ const EnumInterface &ienum = E->get();
- output.append(MEMBER_BEGIN "public enum ");
- output.append(ienum.cname.operator String());
- output.append(MEMBER_BEGIN OPEN_BLOCK);
+ ERR_FAIL_COND_V(ienum.constants.is_empty(), ERR_BUG);
- for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) {
- const ConstantInterface &iconstant = F->get();
+ output.append(MEMBER_BEGIN "public enum ");
+ output.append(ienum.cname.operator String());
+ output.append(MEMBER_BEGIN OPEN_BLOCK);
- if (iconstant.const_doc && iconstant.const_doc->description.size()) {
- String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
- Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
+ for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) {
+ const ConstantInterface &iconstant = F->get();
- if (summary_lines.size()) {
- output.append(INDENT3 "/// <summary>\n");
+ if (iconstant.const_doc && iconstant.const_doc->description.size()) {
+ String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
+ Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
- for (int i = 0; i < summary_lines.size(); i++) {
- output.append(INDENT3 "/// ");
- output.append(summary_lines[i]);
- output.append("\n");
- }
+ if (summary_lines.size()) {
+ output.append(INDENT3 "/// <summary>\n");
- output.append(INDENT3 "/// </summary>\n");
+ for (int i = 0; i < summary_lines.size(); i++) {
+ output.append(INDENT3 "/// ");
+ output.append(summary_lines[i]);
+ output.append("\n");
}
- }
- output.append(INDENT3);
- output.append(iconstant.proxy_name);
- output.append(" = ");
- output.append(itos(iconstant.value));
- output.append(F != ienum.constants.back() ? ",\n" : "\n");
+ output.append(INDENT3 "/// </summary>\n");
+ }
}
- output.append(INDENT2 CLOSE_BLOCK);
+ output.append(INDENT3);
+ output.append(iconstant.proxy_name);
+ output.append(" = ");
+ output.append(itos(iconstant.value));
+ output.append(F != ienum.constants.back() ? ",\n" : "\n");
}
- // Add properties
-
- for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) {
- const PropertyInterface &iprop = E->get();
- Error prop_err = _generate_cs_property(itype, iprop, output);
- ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
- "Failed to generate property '" + iprop.cname.operator String() +
- "' for class '" + itype.name + "'.");
- }
+ output.append(INDENT2 CLOSE_BLOCK);
}
- // TODO: BINDINGS_NATIVE_NAME_FIELD should be StringName, once we support it in C#
+ // Add properties
+
+ for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) {
+ const PropertyInterface &iprop = E->get();
+ Error prop_err = _generate_cs_property(itype, iprop, output);
+ ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
+ "Failed to generate property '" + iprop.cname.operator String() +
+ "' for class '" + itype.name + "'.");
+ }
if (itype.is_singleton) {
// Add the type name and the singleton pointer as static fields
@@ -1349,7 +1368,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
output.append(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = ");
output.append(itype.api_type == ClassDB::API_EDITOR ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS);
output.append("." + ctor_method);
- output.append("(this);\n" CLOSE_BLOCK_L2);
+ output.append("(this);\n" INDENT3 "_InitializeGodotScriptInstanceInternals();\n" CLOSE_BLOCK_L2);
} else {
// Hide the constructor
output.append(MEMBER_BEGIN "internal ");
@@ -1381,15 +1400,17 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
if (itype.is_singleton) {
InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr");
- if (!find_icall_by_name(singleton_icall.name, custom_icalls))
+ if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
custom_icalls.push_back(singleton_icall);
+ }
}
if (is_derived_type && itype.is_instantiable) {
InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
- if (!find_icall_by_name(ctor_icall.name, custom_icalls))
+ if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
custom_icalls.push_back(ctor_icall);
+ }
}
output.append(INDENT1 CLOSE_BLOCK /* class */
@@ -1403,7 +1424,6 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
}
Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) {
-
const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
// Search it in base types too
@@ -1456,6 +1476,9 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
const TypeInterface *prop_itype = _get_type_or_null(proptype_name);
ERR_FAIL_NULL_V(prop_itype, ERR_BUG); // Property type not found
+ ERR_FAIL_COND_V_MSG(prop_itype->is_singleton, ERR_BUG,
+ "Property type is a singleton: '" + p_itype.name + "." + String(p_iprop.cname) + "'.");
+
if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
@@ -1475,8 +1498,9 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
p_output.append(MEMBER_BEGIN "public ");
- if (p_itype.is_singleton)
+ if (p_itype.is_singleton) {
p_output.append("static ");
+ }
p_output.append(prop_itype->cs_type);
p_output.append(" ");
@@ -1546,9 +1570,11 @@ Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInte
}
Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) {
-
const TypeInterface *return_type = _get_type_or_placeholder(p_imethod.return_type);
+ ERR_FAIL_COND_V_MSG(return_type->is_singleton, ERR_BUG,
+ "Method return type is a singleton: '" + p_itype.name + "." + p_imethod.name + "'.");
+
String method_bind_field = "__method_bind_" + itos(p_method_bind_count);
String arguments_sig;
@@ -1564,29 +1590,41 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
const ArgumentInterface &iarg = F->get();
const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
+ ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
+ "Argument type is a singleton: '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
+
+ if (iarg.default_argument.size()) {
+ CRASH_COND_MSG(!_arg_default_value_is_assignable_to_type(iarg.def_param_value, *arg_type),
+ "Invalid default value for parameter '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
+ }
+
// Add the current arguments to the signature
// If the argument has a default value which is not a constant, we will make it Nullable
{
- if (F != p_imethod.arguments.front())
+ if (F != p_imethod.arguments.front()) {
arguments_sig += ", ";
+ }
- if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
+ if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
arguments_sig += "Nullable<";
+ }
arguments_sig += arg_type->cs_type;
- if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
+ if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
arguments_sig += "> ";
- else
+ } else {
arguments_sig += " ";
+ }
arguments_sig += iarg.name;
if (iarg.default_argument.size()) {
- if (iarg.def_param_mode != ArgumentInterface::CONSTANT)
+ if (iarg.def_param_mode != ArgumentInterface::CONSTANT) {
arguments_sig += " = null";
- else
+ } else {
arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
+ }
}
}
@@ -1604,31 +1642,33 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
cs_in_statements += " = ";
cs_in_statements += iarg.name;
- if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
+ if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
cs_in_statements += ".HasValue ? ";
- else
+ } else {
cs_in_statements += " != null ? ";
+ }
cs_in_statements += iarg.name;
- if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL)
+ if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
cs_in_statements += ".Value : ";
- else
+ } else {
cs_in_statements += " : ";
+ }
String def_arg = sformat(iarg.default_argument, arg_type->cs_type);
cs_in_statements += def_arg;
cs_in_statements += ";\n" INDENT3;
- icall_params += arg_type->cs_in.empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
+ icall_params += arg_type->cs_in.is_empty() ? arg_in : sformat(arg_type->cs_in, arg_in);
// Apparently the name attribute must not include the @
String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name;
default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + def_arg + "</param>");
} else {
- icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
+ icall_params += arg_type->cs_in.is_empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name);
}
}
@@ -1664,14 +1704,19 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
}
if (!p_imethod.is_internal) {
+ // TODO: This alone adds ~0.2 MB of bloat to the core API assembly. It would be
+ // better to generate a table in the C++ glue instead. That way the strings wouldn't
+ // add that much extra bloat as they're already used in engine code. Also, it would
+ // probably be much faster than looking up the attributes when fetching methods.
p_output.append(MEMBER_BEGIN "[GodotMethod(\"");
p_output.append(p_imethod.name);
p_output.append("\")]");
}
if (p_imethod.is_deprecated) {
- if (p_imethod.deprecation_message.empty())
+ if (p_imethod.deprecation_message.is_empty()) {
WARN_PRINT("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'.");
+ }
p_output.append(MEMBER_BEGIN "[Obsolete(\"");
p_output.append(p_imethod.deprecation_message);
@@ -1731,12 +1776,13 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf
im_call += ".";
im_call += im_icall->name;
- if (p_imethod.arguments.size())
+ if (p_imethod.arguments.size()) {
p_output.append(cs_in_statements);
+ }
if (return_type->cname == name_cache.type_void) {
p_output.append(im_call + "(" + icall_params + ");\n");
- } else if (return_type->cs_out.empty()) {
+ } else if (return_type->cs_out.is_empty()) {
p_output.append("return " + im_call + "(" + icall_params + ");\n");
} else {
p_output.append(sformat(return_type->cs_out, im_call, icall_params, return_type->cs_type, return_type->im_type_out));
@@ -1759,10 +1805,14 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
const ArgumentInterface &iarg = F->get();
const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type);
+ ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
+ "Argument type is a singleton: '" + iarg.name + "' of signal" + p_itype.name + "." + p_isignal.name + "'.");
+
// Add the current arguments to the signature
- if (F != p_isignal.arguments.front())
+ if (F != p_isignal.arguments.front()) {
arguments_sig += ", ";
+ }
arguments_sig += arg_type->cs_type;
arguments_sig += " ";
@@ -1789,8 +1839,9 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
}
if (p_isignal.is_deprecated) {
- if (p_isignal.deprecation_message.empty())
+ if (p_isignal.deprecation_message.is_empty()) {
WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'.");
+ }
p_output.append(MEMBER_BEGIN "[Obsolete(\"");
p_output.append(p_isignal.deprecation_message);
@@ -1821,8 +1872,9 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
// Generate event
p_output.append(MEMBER_BEGIN "[Signal]" MEMBER_BEGIN "public ");
- if (p_itype.is_singleton)
+ if (p_itype.is_singleton) {
p_output.append("static ");
+ }
p_output.append("event ");
p_output.append(delegate_name);
@@ -1830,18 +1882,20 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
p_output.append(p_isignal.proxy_name);
p_output.append("\n" OPEN_BLOCK_L2);
- if (p_itype.is_singleton)
+ if (p_itype.is_singleton) {
p_output.append("add => Singleton.Connect(__signal_name_");
- else
+ } else {
p_output.append("add => Connect(__signal_name_");
+ }
p_output.append(p_isignal.name);
p_output.append(", new Callable(value));\n");
- if (p_itype.is_singleton)
+ if (p_itype.is_singleton) {
p_output.append(INDENT3 "remove => Singleton.Disconnect(__signal_name_");
- else
+ } else {
p_output.append(INDENT3 "remove => Disconnect(__signal_name_");
+ }
p_output.append(p_isignal.name);
p_output.append(", new Callable(value));\n");
@@ -1852,7 +1906,6 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf
}
Error BindingsGenerator::generate_glue(const String &p_output_dir) {
-
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
bool dir_exists = DirAccess::exists(p_output_dir);
@@ -1876,7 +1929,6 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) {
CRASH_COND(itype.cname != name_cache.type_Object);
CRASH_COND(!itype.is_instantiable);
CRASH_COND(itype.api_type != ClassDB::API_CORE);
- CRASH_COND(itype.is_reference);
CRASH_COND(itype.is_singleton);
}
@@ -1897,8 +1949,9 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) {
String singleton_icall_name = ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX;
InternalCall singleton_icall = InternalCall(itype.api_type, singleton_icall_name, "IntPtr");
- if (!find_icall_by_name(singleton_icall.name, custom_icalls))
+ if (!find_icall_by_name(singleton_icall.name, custom_icalls)) {
custom_icalls.push_back(singleton_icall);
+ }
output.append("Object* ");
output.append(singleton_icall_name);
@@ -1910,8 +1963,9 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) {
if (is_derived_type && itype.is_instantiable) {
InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj");
- if (!find_icall_by_name(ctor_icall.name, custom_icalls))
+ if (!find_icall_by_name(ctor_icall.name, custom_icalls)) {
custom_icalls.push_back(ctor_icall);
+ }
output.append("Object* ");
output.append(ctor_method);
@@ -1945,19 +1999,18 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) {
#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \
{ \
- output.append("\tmono_add_internal_call("); \
+ output.append("\tGDMonoUtils::add_internal_call("); \
output.append("\"" BINDINGS_NAMESPACE "."); \
output.append(m_icall.editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS); \
output.append("::"); \
output.append(m_icall.name); \
- output.append("\", (void*)"); \
+ output.append("\", "); \
output.append(m_icall.name); \
output.append(");\n"); \
}
bool tools_sequence = false;
for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) {
-
if (tools_sequence) {
if (!E->get().editor_only) {
tools_sequence = false;
@@ -2011,8 +2064,9 @@ 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);
- if (save_err != OK)
+ if (save_err != OK) {
return save_err;
+ }
OS::get_singleton()->print("Mono glue generated successfully\n");
@@ -2024,7 +2078,6 @@ uint32_t BindingsGenerator::get_version() {
}
Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
-
FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(!file, ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
@@ -2036,9 +2089,9 @@ Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p
}
Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, StringBuilder &p_output) {
-
- if (p_imethod.is_virtual)
+ if (p_imethod.is_virtual) {
return OK; // Ignore
+ }
bool ret_void = p_imethod.return_type.cname == name_cache.type_void;
@@ -2066,10 +2119,12 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte
c_in_statements += sformat(", &%s_in);\n", c_param_name);
}
} else {
- if (i > 0)
+ if (i > 0) {
c_args_var_content += ", ";
- if (arg_type->c_in.size())
+ }
+ if (arg_type->c_in.size()) {
c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name);
+ }
c_args_var_content += sformat(arg_type->c_arg_in, c_param_name);
}
@@ -2099,8 +2154,9 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte
if (!generated_icall_funcs.find(im_icall)) {
generated_icall_funcs.push_back(im_icall);
- if (im_icall->editor_only)
+ if (im_icall->editor_only) {
p_output.append("#ifdef TOOLS_ENABLED\n");
+ }
// Generate icall function
@@ -2139,7 +2195,7 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte
if (return_type->ret_as_byref_arg) {
p_output.append("\tif (" CS_PARAM_INSTANCE " == nullptr) { *arg_ret = ");
p_output.append(fail_ret);
- p_output.append("; ERR_FAIL_MSG(\"Parameter ' arg_ret ' is null.\"); }\n");
+ p_output.append("; ERR_FAIL_MSG(\"Parameter ' " CS_PARAM_INSTANCE " ' is null.\"); }\n");
} else {
p_output.append("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE ", ");
p_output.append(fail_ret);
@@ -2207,7 +2263,7 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte
}
if (!ret_void) {
- if (return_type->c_out.empty()) {
+ if (return_type->c_out.is_empty()) {
p_output.append("\treturn " C_LOCAL_RET ";\n");
} else if (return_type->ret_as_byref_arg) {
p_output.append(sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET, return_type->name, "arg_ret"));
@@ -2218,30 +2274,33 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte
p_output.append(CLOSE_BLOCK "\n");
- if (im_icall->editor_only)
+ if (im_icall->editor_only) {
p_output.append("#endif // TOOLS_ENABLED\n");
+ }
}
return OK;
}
const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
-
const Map<StringName, TypeInterface>::Element *builtin_type_match = builtin_types.find(p_typeref.cname);
- if (builtin_type_match)
+ if (builtin_type_match) {
return &builtin_type_match->get();
+ }
const OrderedHashMap<StringName, TypeInterface>::Element obj_type_match = obj_types.find(p_typeref.cname);
- if (obj_type_match)
+ if (obj_type_match) {
return &obj_type_match.get();
+ }
if (p_typeref.is_enum) {
const Map<StringName, TypeInterface>::Element *enum_match = enum_types.find(p_typeref.cname);
- if (enum_match)
+ if (enum_match) {
return &enum_match->get();
+ }
// Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
const Map<StringName, TypeInterface>::Element *int_match = builtin_types.find(name_cache.type_int);
@@ -2253,18 +2312,19 @@ const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(con
}
const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placeholder(const TypeReference &p_typeref) {
-
const TypeInterface *found = _get_type_or_null(p_typeref);
- if (found)
+ if (found) {
return found;
+ }
ERR_PRINT(String() + "Type not found. Creating placeholder: '" + p_typeref.cname.operator String() + "'.");
const Map<StringName, TypeInterface>::Element *match = placeholder_types.find(p_typeref.cname);
- if (match)
+ if (match) {
return &match->get();
+ }
TypeInterface placeholder;
TypeInterface::create_placeholder_type(placeholder, p_typeref.cname);
@@ -2273,7 +2333,6 @@ const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_placehol
}
StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
-
switch (p_meta) {
case GodotTypeInfo::METADATA_INT_IS_INT8:
return "sbyte";
@@ -2306,7 +2365,6 @@ StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metada
}
StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
-
switch (p_meta) {
case GodotTypeInfo::METADATA_REAL_IS_FLOAT:
return "float";
@@ -2324,8 +2382,85 @@ StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Meta
}
}
-bool BindingsGenerator::_populate_object_type_interfaces() {
+bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &p_val, const TypeInterface &p_arg_type) {
+ if (p_arg_type.name == name_cache.type_Variant) {
+ // Variant can take anything
+ return true;
+ }
+
+ switch (p_val.get_type()) {
+ case Variant::NIL:
+ return p_arg_type.is_object_type ||
+ name_cache.is_nullable_type(p_arg_type.name);
+ case Variant::BOOL:
+ return p_arg_type.name == name_cache.type_bool;
+ case Variant::INT:
+ return p_arg_type.name == name_cache.type_sbyte ||
+ p_arg_type.name == name_cache.type_short ||
+ p_arg_type.name == name_cache.type_int ||
+ p_arg_type.name == name_cache.type_byte ||
+ p_arg_type.name == name_cache.type_ushort ||
+ p_arg_type.name == name_cache.type_uint ||
+ p_arg_type.name == name_cache.type_long ||
+ p_arg_type.name == name_cache.type_ulong ||
+ p_arg_type.name == name_cache.type_float ||
+ p_arg_type.name == name_cache.type_double ||
+ p_arg_type.is_enum;
+ case Variant::FLOAT:
+ return p_arg_type.name == name_cache.type_float ||
+ p_arg_type.name == name_cache.type_double;
+ case Variant::STRING:
+ case Variant::STRING_NAME:
+ return p_arg_type.name == name_cache.type_String ||
+ p_arg_type.name == name_cache.type_StringName ||
+ p_arg_type.name == name_cache.type_NodePath;
+ case Variant::NODE_PATH:
+ return p_arg_type.name == name_cache.type_NodePath;
+ case Variant::TRANSFORM:
+ case Variant::TRANSFORM2D:
+ case Variant::BASIS:
+ case Variant::QUAT:
+ case Variant::PLANE:
+ case Variant::AABB:
+ case Variant::COLOR:
+ case Variant::VECTOR2:
+ case Variant::RECT2:
+ case Variant::VECTOR3:
+ case Variant::RID:
+ case Variant::ARRAY:
+ case Variant::DICTIONARY:
+ case Variant::PACKED_BYTE_ARRAY:
+ case Variant::PACKED_INT32_ARRAY:
+ case Variant::PACKED_INT64_ARRAY:
+ case Variant::PACKED_FLOAT32_ARRAY:
+ case Variant::PACKED_FLOAT64_ARRAY:
+ case Variant::PACKED_STRING_ARRAY:
+ case Variant::PACKED_VECTOR2_ARRAY:
+ case Variant::PACKED_VECTOR3_ARRAY:
+ case Variant::PACKED_COLOR_ARRAY:
+ case Variant::CALLABLE:
+ case Variant::SIGNAL:
+ return p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::OBJECT:
+ return p_arg_type.is_object_type;
+ case Variant::VECTOR2I:
+ return p_arg_type.name == name_cache.type_Vector2 ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::RECT2I:
+ return p_arg_type.name == name_cache.type_Rect2 ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::VECTOR3I:
+ return p_arg_type.name == name_cache.type_Vector3 ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ default:
+ CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
+ break;
+ }
+
+ return false;
+}
+bool BindingsGenerator::_populate_object_type_interfaces() {
obj_types.clear();
List<StringName> class_list;
@@ -2387,22 +2522,30 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
const PropertyInfo &property = E->get();
- if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY)
+ if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY) {
+ continue;
+ }
+
+ if (property.name.find("/") >= 0) {
+ // Ignore properties with '/' (slash) in the name. These are only meant for use in the inspector.
continue;
+ }
PropertyInterface iprop;
iprop.cname = property.name;
iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
- if (iprop.setter != StringName())
+ if (iprop.setter != StringName()) {
accessor_methods[iprop.setter] = iprop.cname;
- if (iprop.getter != StringName())
+ }
+ if (iprop.getter != StringName()) {
accessor_methods[iprop.getter] = iprop.cname;
+ }
bool valid = false;
iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
- ERR_FAIL_COND_V(!valid, false);
+ ERR_FAIL_COND_V_MSG(!valid, false, "Invalid property: '" + itype.name + "." + String(iprop.cname) + "'.");
iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
@@ -2414,8 +2557,6 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
iprop.proxy_name += "_";
}
- iprop.proxy_name = iprop.proxy_name.replace("/", "__"); // Some members have a slash...
-
iprop.prop_doc = nullptr;
for (int i = 0; i < itype.class_doc->properties.size(); i++) {
@@ -2444,20 +2585,23 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
int argc = method_info.arguments.size();
- if (method_info.name.empty())
+ if (method_info.name.is_empty()) {
continue;
+ }
String cname = method_info.name;
- if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname))
+ if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname)) {
continue;
+ }
MethodInterface imethod;
imethod.name = method_info.name;
imethod.cname = cname;
- if (method_info.flags & METHOD_FLAG_VIRTUAL)
+ if (method_info.flags & METHOD_FLAG_VIRTUAL) {
imethod.is_virtual = true;
+ }
PropertyInfo return_info = method_info.return_val;
@@ -2479,9 +2623,8 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
// We assume the return type is void.
imethod.return_type.cname = name_cache.type_void;
- // Actually, more methods like this may be added in the future,
- // which could actually will return something different.
- // Let's put this to notify us if that ever happens.
+ // Actually, more methods like this may be added in the future, which could return
+ // something different. Let's put this check to notify us if that ever happens.
if (itype.cname != name_cache.type_Object || imethod.name != "free") {
WARN_PRINT("Notification: New unexpected virtual non-overridable method found."
" We only expected Object.free, but found '" +
@@ -2492,13 +2635,12 @@ bool 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_PRINT("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_V(false);
- }
+
+ bool bad_reference_hint = !imethod.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
+ ClassDB::is_parent_class(return_info.class_name, name_cache.type_Reference);
+ ERR_FAIL_COND_V_MSG(bad_reference_hint, false,
+ String() + "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 + "'.");
} 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) {
@@ -2589,6 +2731,10 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
}
}
+ ERR_FAIL_COND_V_MSG(itype.find_property_by_name(imethod.cname), false,
+ "Method name conflicts with property: '" + itype.name + "." + imethod.name + "'.");
+
+ // Classes starting with an underscore are ignored unless they're used as a property setter or getter
if (!imethod.is_virtual && imethod.name[0] == '_') {
for (const List<PropertyInterface>::Element *F = itype.properties.front(); F; F = F->next()) {
const PropertyInterface &iprop = F->get();
@@ -2768,8 +2914,8 @@ bool BindingsGenerator::_populate_object_type_interfaces() {
}
bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
-
- r_iarg.default_argument = p_val;
+ r_iarg.def_param_value = p_val;
+ r_iarg.default_argument = p_val.operator String();
switch (p_val.get_type()) {
case Variant::NIL:
@@ -2802,8 +2948,9 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
}
break;
case Variant::TRANSFORM:
- if (p_val.operator Transform() == Transform())
+ if (p_val.operator Transform() == Transform()) {
r_iarg.default_argument.clear();
+ }
r_iarg.default_argument = "new %s(" + r_iarg.default_argument + ")";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
break;
@@ -2832,7 +2979,7 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
r_iarg.default_argument = "new %s()";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
break;
- case Variant::_RID:
+ case Variant::RID:
ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false,
"Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_RID) + "'.");
@@ -2869,14 +3016,14 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar
break;
}
- if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null")
+ if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "null") {
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
+ }
return true;
}
void BindingsGenerator::_populate_builtin_type_interfaces() {
-
builtin_types.clear();
TypeInterface itype;
@@ -2953,44 +3100,11 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
INSERT_INT_TYPE("sbyte", int8_t, int64_t);
INSERT_INT_TYPE("short", int16_t, int64_t);
INSERT_INT_TYPE("int", int32_t, int64_t);
+ INSERT_INT_TYPE("long", int64_t, int64_t);
INSERT_INT_TYPE("byte", uint8_t, int64_t);
INSERT_INT_TYPE("ushort", uint16_t, int64_t);
INSERT_INT_TYPE("uint", uint32_t, int64_t);
-
- itype = TypeInterface::create_value_type(String("long"));
- {
- itype.c_out = "\treturn (%0)%1;\n";
- itype.c_in = "\t%0 %1_in = (%0)*%1;\n";
- itype.c_out = "\t*%3 = (%0)%1;\n";
- itype.c_type = "int64_t";
- itype.c_arg_in = "&%s_in";
- }
- itype.c_type_in = "int64_t*";
- itype.c_type_out = "int64_t";
- itype.im_type_in = "ref " + itype.name;
- itype.im_type_out = "out " + itype.name;
- itype.cs_in = "ref %0";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
- itype.ret_as_byref_arg = true;
- builtin_types.insert(itype.cname, itype);
-
- itype = TypeInterface::create_value_type(String("ulong"));
- {
- itype.c_in = "\t%0 %1_in = (%0)*%1;\n";
- itype.c_out = "\t*%3 = (%0)%1;\n";
- itype.c_type = "int64_t";
- itype.c_arg_in = "&%s_in";
- }
- itype.c_type_in = "uint64_t*";
- itype.c_type_out = "uint64_t";
- itype.im_type_in = "ref " + itype.name;
- itype.im_type_out = "out " + itype.name;
- itype.cs_in = "ref %0";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
- itype.ret_as_byref_arg = true;
- builtin_types.insert(itype.cname, itype);
+ INSERT_INT_TYPE("ulong", uint64_t, int64_t);
}
// Floating point types
@@ -3002,20 +3116,16 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.proxy_name = "float";
{
// The expected type for 'float' in ptrcall is 'double'
- itype.c_in = "\t%0 %1_in = (%0)*%1;\n";
- itype.c_out = "\t*%3 = (%0)%1;\n";
+ itype.c_in = "\t%0 %1_in = (%0)%1;\n";
+ itype.c_out = "\treturn (%0)%1;\n";
itype.c_type = "double";
- itype.c_type_in = "float*";
+ itype.c_type_in = "float";
itype.c_type_out = "float";
itype.c_arg_in = "&%s_in";
}
itype.cs_type = itype.proxy_name;
- itype.im_type_in = "ref " + itype.proxy_name;
- itype.im_type_out = "out " + itype.proxy_name;
- itype.cs_in = "ref %0";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
- itype.ret_as_byref_arg = true;
+ itype.im_type_in = itype.proxy_name;
+ itype.im_type_out = itype.proxy_name;
builtin_types.insert(itype.cname, itype);
// double
@@ -3024,20 +3134,14 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
itype.cname = itype.name;
itype.proxy_name = "double";
{
- itype.c_in = "\t%0 %1_in = (%0)*%1;\n";
- itype.c_out = "\t*%3 = (%0)%1;\n";
itype.c_type = "double";
- itype.c_type_in = "double*";
+ itype.c_type_in = "double";
itype.c_type_out = "double";
- itype.c_arg_in = "&%s_in";
+ itype.c_arg_in = "&%s";
}
itype.cs_type = itype.proxy_name;
- itype.im_type_in = "ref " + itype.proxy_name;
- itype.im_type_out = "out " + itype.proxy_name;
- itype.cs_in = "ref %0";
- /* in cs_out, im_type_out (%3) includes the 'out ' part */
- itype.cs_out = "%0(%1, %3 argRet); return argRet;";
- itype.ret_as_byref_arg = true;
+ itype.im_type_in = itype.proxy_name;
+ itype.im_type_out = itype.proxy_name;
builtin_types.insert(itype.cname, itype);
}
@@ -3252,8 +3356,7 @@ void BindingsGenerator::_populate_builtin_type_interfaces() {
}
void BindingsGenerator::_populate_global_constants() {
-
- int global_constants_count = GlobalConstants::get_global_constant_count();
+ int global_constants_count = CoreConstants::get_global_constant_count();
if (global_constants_count > 0) {
Map<String, DocData::ClassDoc>::Element *match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
@@ -3263,8 +3366,7 @@ void BindingsGenerator::_populate_global_constants() {
const DocData::ClassDoc &global_scope_doc = match->value();
for (int i = 0; i < global_constants_count; i++) {
-
- String constant_name = GlobalConstants::get_global_constant_name(i);
+ String constant_name = CoreConstants::get_global_constant_name(i);
const DocData::ConstantDoc *const_doc = nullptr;
for (int j = 0; j < global_scope_doc.constants.size(); j++) {
@@ -3276,8 +3378,8 @@ void BindingsGenerator::_populate_global_constants() {
}
}
- int constant_value = GlobalConstants::get_global_constant_value(i);
- StringName enum_name = GlobalConstants::get_global_constant_enum(i);
+ int constant_value = CoreConstants::get_global_constant_value(i);
+ StringName enum_name = CoreConstants::get_global_constant_enum(i);
ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
iconstant.const_doc = const_doc;
@@ -3342,14 +3444,12 @@ void BindingsGenerator::_populate_global_constants() {
}
void BindingsGenerator::_initialize_blacklisted_methods() {
-
blacklisted_methods["Object"].push_back("to_string"); // there is already ToString
blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead
blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it)
}
void BindingsGenerator::_log(const char *p_format, ...) {
-
if (log_print_enabled) {
va_list list;
@@ -3360,7 +3460,6 @@ void BindingsGenerator::_log(const char *p_format, ...) {
}
void BindingsGenerator::_initialize() {
-
initialized = false;
EditorHelp::generate_doc();
@@ -3381,14 +3480,14 @@ void BindingsGenerator::_initialize() {
core_custom_icalls.clear();
editor_custom_icalls.clear();
- for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next())
+ for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
_generate_method_icalls(E.get());
+ }
initialized = true;
}
void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
-
const int NUM_OPTIONS = 2;
String generate_all_glue_option = "--generate-mono-glue";
String generate_cs_glue_option = "--generate-mono-cs-glue";
@@ -3451,21 +3550,25 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args)
}
if (glue_dir_path.length()) {
- if (bindings_generator.generate_glue(glue_dir_path) != OK)
+ if (bindings_generator.generate_glue(glue_dir_path) != OK) {
ERR_PRINT(generate_all_glue_option + ": Failed to generate the C++ glue.");
+ }
- if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK)
+ if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK) {
ERR_PRINT(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)
+ if (bindings_generator.generate_cs_api(cs_dir_path) != OK) {
ERR_PRINT(generate_cs_glue_option + ": Failed to generate the C# API.");
+ }
}
if (cpp_dir_path.length()) {
- if (bindings_generator.generate_glue(cpp_dir_path) != OK)
+ if (bindings_generator.generate_glue(cpp_dir_path) != OK) {
ERR_PRINT(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 7c87c688db..b18dfb0ec4 100644
--- a/modules/mono/editor/bindings_generator.h
+++ b/modules/mono/editor/bindings_generator.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,21 +31,21 @@
#ifndef BINDINGS_GENERATOR_H
#define BINDINGS_GENERATOR_H
-#include "core/class_db.h"
-#include "core/string_builder.h"
-#include "editor/doc_data.h"
+#include "core/doc_data.h"
+#include "core/object/class_db.h"
+#include "core/string/string_builder.h"
+#include "editor/doc_tools.h"
#include "editor/editor_help.h"
#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
-#include "core/ustring.h"
+#include "core/string/ustring.h"
class BindingsGenerator {
-
struct ConstantInterface {
String name;
String proxy_name;
- int value;
+ int value = 0;
const DocData::ConstantDoc *const_doc;
ConstantInterface() {}
@@ -75,7 +75,7 @@ class BindingsGenerator {
struct PropertyInterface {
StringName cname;
String proxy_name;
- int index;
+ int index = 0;
StringName setter;
StringName getter;
@@ -85,16 +85,12 @@ class BindingsGenerator {
struct TypeReference {
StringName cname;
- bool is_enum;
+ bool is_enum = false;
- TypeReference() :
- is_enum(false) {
- }
+ TypeReference() {}
TypeReference(const StringName &p_cname) :
- cname(p_cname),
- is_enum(false) {
- }
+ cname(p_cname) {}
};
struct ArgumentInterface {
@@ -107,7 +103,9 @@ class BindingsGenerator {
TypeReference type;
String name;
- DefaultParamMode def_param_mode;
+
+ Variant def_param_value;
+ DefaultParamMode def_param_mode = CONSTANT;
/**
* Determines the expression for the parameter default value.
@@ -116,9 +114,7 @@ class BindingsGenerator {
*/
String default_argument;
- ArgumentInterface() {
- def_param_mode = CONSTANT;
- }
+ ArgumentInterface() {}
};
struct MethodInterface {
@@ -138,19 +134,19 @@ class BindingsGenerator {
/**
* Determines if the method has a variable number of arguments (VarArg)
*/
- bool is_vararg;
+ bool is_vararg = false;
/**
* Virtual methods ("virtual" as defined by the Godot API) are methods that by default do nothing,
* but can be overridden by the user to add custom functionality.
* e.g.: _ready, _process, etc.
*/
- bool is_virtual;
+ bool is_virtual = false;
/**
* Determines if the call should fallback to Godot's object.Call(string, params) in C#.
*/
- bool requires_object_call;
+ bool requires_object_call = false;
/**
* Determines if the method visibility is 'internal' (visible only to files in the same assembly).
@@ -158,27 +154,20 @@ class BindingsGenerator {
* but are required by properties as getters or setters.
* Methods that are not meant to be exposed are those that begin with underscore and are not virtual.
*/
- bool is_internal;
+ bool is_internal = false;
List<ArgumentInterface> arguments;
- const DocData::MethodDoc *method_doc;
+ const DocData::MethodDoc *method_doc = nullptr;
- bool is_deprecated;
+ bool is_deprecated = false;
String deprecation_message;
void add_argument(const ArgumentInterface &argument) {
arguments.push_back(argument);
}
- MethodInterface() {
- is_vararg = false;
- is_virtual = false;
- requires_object_call = false;
- is_internal = false;
- method_doc = nullptr;
- is_deprecated = false;
- }
+ MethodInterface() {}
};
struct SignalInterface {
@@ -192,19 +181,16 @@ class BindingsGenerator {
List<ArgumentInterface> arguments;
- const DocData::MethodDoc *method_doc;
+ const DocData::MethodDoc *method_doc = nullptr;
- bool is_deprecated;
+ bool is_deprecated = false;
String deprecation_message;
void add_argument(const ArgumentInterface &argument) {
arguments.push_back(argument);
}
- SignalInterface() {
- method_doc = nullptr;
- is_deprecated = false;
- }
+ SignalInterface() {}
};
struct TypeInterface {
@@ -225,26 +211,26 @@ class BindingsGenerator {
*/
String proxy_name;
- ClassDB::APIType api_type;
+ ClassDB::APIType api_type = ClassDB::API_NONE;
- bool is_enum;
- bool is_object_type;
- bool is_singleton;
- bool is_reference;
+ bool is_enum = false;
+ bool is_object_type = false;
+ bool is_singleton = false;
+ bool is_reference = false;
/**
* Used only by Object-derived types.
* Determines if this type is not abstract (incomplete).
* e.g.: CanvasItem cannot be instantiated.
*/
- bool is_instantiable;
+ bool is_instantiable = false;
/**
* Used only by Object-derived types.
* Determines if the C# class owns the native handle and must free it somehow when disposed.
* e.g.: Reference types must notify when the C# instance is disposed, for proper refcounting.
*/
- bool memory_own;
+ bool memory_own = false;
/**
* This must be set to true for any struct bigger than 32-bits. Those cannot be passed/returned by value
@@ -252,7 +238,7 @@ class BindingsGenerator {
* In this case, [c_out] and [cs_out] must have a different format, explained below.
* The Mono IL interpreter icall trampolines don't support passing structs bigger than 32-bits by value (at least not on WASM).
*/
- bool ret_as_byref_arg;
+ bool ret_as_byref_arg = false;
// !! The comments of the following fields make reference to other fields via square brackets, e.g.: [field_name]
// !! When renaming those fields, make sure to rename their references in the comments
@@ -279,7 +265,7 @@ class BindingsGenerator {
* Formatting elements:
* %0 or %s: name of the parameter
*/
- String c_arg_in;
+ String c_arg_in = "%s";
/**
* One or more statements that determine how a variable of this type is returned from a function.
@@ -362,7 +348,7 @@ class BindingsGenerator {
*/
String im_type_out;
- const DocData::ClassDoc *class_doc;
+ const DocData::ClassDoc *class_doc = nullptr;
List<ConstantInterface> constants;
List<EnumInterface> enums;
@@ -372,8 +358,9 @@ class BindingsGenerator {
const MethodInterface *find_method_by_name(const StringName &p_cname) const {
for (const List<MethodInterface>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().cname == p_cname)
+ if (E->get().cname == p_cname) {
return &E->get();
+ }
}
return nullptr;
@@ -381,8 +368,9 @@ class BindingsGenerator {
const PropertyInterface *find_property_by_name(const StringName &p_cname) const {
for (const List<PropertyInterface>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().cname == p_cname)
+ if (E->get().cname == p_cname) {
return &E->get();
+ }
}
return nullptr;
@@ -390,8 +378,9 @@ class BindingsGenerator {
const PropertyInterface *find_property_by_proxy_name(const String &p_proxy_name) const {
for (const List<PropertyInterface>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().proxy_name == p_proxy_name)
+ if (E->get().proxy_name == p_proxy_name) {
return &E->get();
+ }
}
return nullptr;
@@ -399,8 +388,9 @@ class BindingsGenerator {
const MethodInterface *find_method_by_proxy_name(const String &p_proxy_name) const {
for (const List<MethodInterface>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().proxy_name == p_proxy_name)
+ if (E->get().proxy_name == p_proxy_name) {
return &E->get();
+ }
}
return nullptr;
@@ -482,24 +472,7 @@ class BindingsGenerator {
r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name];
}
- TypeInterface() {
-
- api_type = ClassDB::API_NONE;
-
- is_enum = false;
- is_object_type = false;
- is_singleton = false;
- is_reference = false;
- is_instantiable = false;
-
- memory_own = false;
-
- ret_as_byref_arg = false;
-
- c_arg_in = "%s";
-
- class_doc = nullptr;
- }
+ TypeInterface() {}
};
struct InternalCall {
@@ -507,7 +480,7 @@ class BindingsGenerator {
String im_type_out; // Return type for the C# method declaration. Also used as companion of [unique_siq]
String im_sig; // Signature for the C# method declaration
String unique_sig; // Unique signature to avoid duplicates in containers
- bool editor_only;
+ bool editor_only = false;
InternalCall() {}
@@ -532,8 +505,8 @@ class BindingsGenerator {
}
};
- bool log_print_enabled;
- bool initialized;
+ bool log_print_enabled = true;
+ bool initialized = false;
OrderedHashMap<StringName, TypeInterface> obj_types;
@@ -557,58 +530,70 @@ class BindingsGenerator {
void _initialize_blacklisted_methods();
struct NameCache {
- StringName type_void;
- StringName type_Array;
- StringName type_Dictionary;
- StringName type_Variant;
- StringName type_VarArg;
- StringName type_Object;
- StringName type_Reference;
- StringName type_RID;
- StringName type_String;
- StringName type_StringName;
- StringName type_NodePath;
- StringName type_at_GlobalScope;
- StringName enum_Error;
-
- StringName type_sbyte;
- StringName type_short;
- StringName type_int;
- StringName type_long;
- StringName type_byte;
- StringName type_ushort;
- StringName type_uint;
- StringName type_ulong;
- StringName type_float;
- StringName type_double;
-
- NameCache() {
- type_void = StaticCString::create("void");
- type_Array = StaticCString::create("Array");
- type_Dictionary = StaticCString::create("Dictionary");
- type_Variant = StaticCString::create("Variant");
- type_VarArg = StaticCString::create("VarArg");
- type_Object = StaticCString::create("Object");
- type_Reference = StaticCString::create("Reference");
- type_RID = StaticCString::create("RID");
- type_String = StaticCString::create("String");
- type_StringName = StaticCString::create("StringName");
- type_NodePath = StaticCString::create("NodePath");
- type_at_GlobalScope = StaticCString::create("@GlobalScope");
- enum_Error = StaticCString::create("Error");
-
- type_sbyte = StaticCString::create("sbyte");
- type_short = StaticCString::create("short");
- type_int = StaticCString::create("int");
- type_long = StaticCString::create("long");
- type_byte = StaticCString::create("byte");
- type_ushort = StaticCString::create("ushort");
- type_uint = StaticCString::create("uint");
- type_ulong = StaticCString::create("ulong");
- type_float = StaticCString::create("float");
- type_double = StaticCString::create("double");
+ StringName type_void = StaticCString::create("void");
+ StringName type_Variant = StaticCString::create("Variant");
+ StringName type_VarArg = StaticCString::create("VarArg");
+ StringName type_Object = StaticCString::create("Object");
+ StringName type_Reference = StaticCString::create("Reference");
+ StringName type_RID = StaticCString::create("RID");
+ StringName type_String = StaticCString::create("String");
+ StringName type_StringName = StaticCString::create("StringName");
+ StringName type_NodePath = StaticCString::create("NodePath");
+ StringName type_at_GlobalScope = StaticCString::create("@GlobalScope");
+ StringName enum_Error = StaticCString::create("Error");
+
+ StringName type_sbyte = StaticCString::create("sbyte");
+ StringName type_short = StaticCString::create("short");
+ StringName type_int = StaticCString::create("int");
+ StringName type_byte = StaticCString::create("byte");
+ StringName type_ushort = StaticCString::create("ushort");
+ StringName type_uint = StaticCString::create("uint");
+ StringName type_long = StaticCString::create("long");
+ StringName type_ulong = StaticCString::create("ulong");
+
+ StringName type_bool = StaticCString::create("bool");
+ StringName type_float = StaticCString::create("float");
+ StringName type_double = StaticCString::create("double");
+
+ StringName type_Vector2 = StaticCString::create("Vector2");
+ StringName type_Rect2 = StaticCString::create("Rect2");
+ StringName type_Vector3 = StaticCString::create("Vector3");
+
+ // Object not included as it must be checked for all derived classes
+ static constexpr int nullable_types_count = 17;
+ StringName nullable_types[nullable_types_count] = {
+ type_String,
+ type_StringName,
+ type_NodePath,
+
+ StaticCString::create(_STR(Array)),
+ StaticCString::create(_STR(Dictionary)),
+ StaticCString::create(_STR(Callable)),
+ StaticCString::create(_STR(Signal)),
+
+ StaticCString::create(_STR(PackedByteArray)),
+ StaticCString::create(_STR(PackedInt32Array)),
+ StaticCString::create(_STR(PackedInt64rray)),
+ StaticCString::create(_STR(PackedFloat32Array)),
+ StaticCString::create(_STR(PackedFloat64Array)),
+ StaticCString::create(_STR(PackedStringArray)),
+ StaticCString::create(_STR(PackedVector2Array)),
+ StaticCString::create(_STR(PackedVector3Array)),
+ StaticCString::create(_STR(PackedColorArray)),
+ };
+
+ bool is_nullable_type(const StringName &p_type) const {
+ for (int i = 0; i < nullable_types_count; i++) {
+ if (p_type == nullable_types[i]) {
+ return true;
+ }
+ }
+
+ return false;
}
+ NameCache() {}
+
private:
NameCache(const NameCache &);
NameCache &operator=(const NameCache &);
@@ -619,7 +604,9 @@ class BindingsGenerator {
const List<InternalCall>::Element *find_icall_by_name(const String &p_name, const List<InternalCall> &p_list) {
const List<InternalCall>::Element *it = p_list.front();
while (it) {
- if (it->get().name == p_name) return it;
+ if (it->get().name == p_name) {
+ return it;
+ }
it = it->next();
}
return nullptr;
@@ -627,20 +614,22 @@ class BindingsGenerator {
const ConstantInterface *find_constant_by_name(const String &p_name, const List<ConstantInterface> &p_constants) const {
for (const List<ConstantInterface>::Element *E = p_constants.front(); E; E = E->next()) {
- if (E->get().name == p_name)
+ if (E->get().name == p_name) {
return &E->get();
+ }
}
return nullptr;
}
inline String get_unique_sig(const TypeInterface &p_type) {
- if (p_type.is_reference)
+ if (p_type.is_reference) {
return "Ref";
- else if (p_type.is_object_type)
+ } else if (p_type.is_object_type) {
return "Obj";
- else if (p_type.is_enum)
+ } else if (p_type.is_enum) {
return "int";
+ }
return p_type.name;
}
@@ -659,6 +648,7 @@ class BindingsGenerator {
StringName _get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta);
bool _arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg);
+ bool _arg_default_value_is_assignable_to_type(const Variant &p_val, const TypeInterface &p_arg_type);
bool _populate_object_type_interfaces();
void _populate_builtin_type_interfaces();
@@ -696,9 +686,7 @@ public:
static void handle_cmdline_args(const List<String> &p_cmdline_args);
- BindingsGenerator() :
- log_print_enabled(true),
- initialized(false) {
+ BindingsGenerator() {
_initialize();
}
};
diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp
new file mode 100644
index 0000000000..bbfba83e6f
--- /dev/null
+++ b/modules/mono/editor/code_completion.cpp
@@ -0,0 +1,261 @@
+/*************************************************************************/
+/* code_completion.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "code_completion.h"
+
+#include "core/config/project_settings.h"
+#include "editor/editor_file_system.h"
+#include "editor/editor_settings.h"
+#include "scene/gui/control.h"
+#include "scene/main/node.h"
+
+namespace gdmono {
+
+// Almost everything here is taken from functions used by GDScript for code completion, adapted for C#.
+
+_FORCE_INLINE_ String quoted(const String &p_str) {
+ return "\"" + p_str + "\"";
+}
+
+void _add_nodes_suggestions(const Node *p_base, const Node *p_node, PackedStringArray &r_suggestions) {
+ if (p_node != p_base && !p_node->get_owner()) {
+ return;
+ }
+
+ String path_relative_to_orig = p_base->get_path_to(p_node);
+
+ r_suggestions.push_back(quoted(path_relative_to_orig));
+
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ _add_nodes_suggestions(p_base, p_node->get_child(i), r_suggestions);
+ }
+}
+
+Node *_find_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
+ if (p_current->get_owner() != p_base && p_base != p_current) {
+ return nullptr;
+ }
+
+ Ref<Script> c = p_current->get_script();
+
+ if (c == p_script) {
+ return p_current;
+ }
+
+ for (int i = 0; i < p_current->get_child_count(); i++) {
+ Node *found = _find_node_for_script(p_base, p_current->get_child(i), p_script);
+ if (found) {
+ return found;
+ }
+ }
+
+ return nullptr;
+}
+
+void _get_directory_contents(EditorFileSystemDirectory *p_dir, PackedStringArray &r_suggestions) {
+ for (int i = 0; i < p_dir->get_file_count(); i++) {
+ r_suggestions.push_back(quoted(p_dir->get_file_path(i)));
+ }
+
+ for (int i = 0; i < p_dir->get_subdir_count(); i++) {
+ _get_directory_contents(p_dir->get_subdir(i), r_suggestions);
+ }
+}
+
+Node *_try_find_owner_node_in_tree(const Ref<Script> p_script) {
+ SceneTree *tree = SceneTree::get_singleton();
+ if (!tree) {
+ return nullptr;
+ }
+ Node *base = tree->get_edited_scene_root();
+ if (base) {
+ base = _find_node_for_script(base, base, p_script);
+ }
+ return base;
+}
+
+PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_script_file) {
+ PackedStringArray suggestions;
+
+ switch (p_kind) {
+ case CompletionKind::INPUT_ACTIONS: {
+ List<PropertyInfo> project_props;
+ ProjectSettings::get_singleton()->get_property_list(&project_props);
+
+ for (List<PropertyInfo>::Element *E = project_props.front(); E; E = E->next()) {
+ const PropertyInfo &prop = E->get();
+
+ if (!prop.name.begins_with("input/")) {
+ continue;
+ }
+
+ String name = prop.name.substr(prop.name.find("/") + 1, prop.name.length());
+ suggestions.push_back(quoted(name));
+ }
+ } break;
+ case CompletionKind::NODE_PATHS: {
+ {
+ // AutoLoads
+ Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
+
+ for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
+ const ProjectSettings::AutoloadInfo &info = E->value();
+ suggestions.push_back(quoted("/root/" + String(info.name)));
+ }
+ }
+
+ {
+ // Current edited scene tree
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base) {
+ _add_nodes_suggestions(base, base, suggestions);
+ }
+ }
+ } break;
+ case CompletionKind::RESOURCE_PATHS: {
+ if (bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) {
+ _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), suggestions);
+ }
+ } break;
+ case CompletionKind::SCENE_PATHS: {
+ DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES);
+ List<String> directories;
+ directories.push_back(dir_access->get_current_dir());
+
+ while (!directories.is_empty()) {
+ dir_access->change_dir(directories.back()->get());
+ directories.pop_back();
+
+ dir_access->list_dir_begin();
+ String filename = dir_access->get_next();
+
+ while (filename != "") {
+ if (filename == "." || filename == "..") {
+ filename = dir_access->get_next();
+ continue;
+ }
+
+ if (dir_access->dir_exists(filename)) {
+ directories.push_back(dir_access->get_current_dir().plus_file(filename));
+ } else if (filename.ends_with(".tscn") || filename.ends_with(".scn")) {
+ suggestions.push_back(quoted(dir_access->get_current_dir().plus_file(filename)));
+ }
+
+ filename = dir_access->get_next();
+ }
+ }
+ } break;
+ case CompletionKind::SHADER_PARAMS: {
+ print_verbose("Shared params completion for C# not implemented.");
+ } break;
+ case CompletionKind::SIGNALS: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+
+ List<MethodInfo> signals;
+ script->get_script_signal_list(&signals);
+
+ StringName native = script->get_instance_base_type();
+ if (native != StringName()) {
+ ClassDB::get_signal_list(native, &signals, /* p_no_inheritance: */ false);
+ }
+
+ for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
+ const String &signal = E->get().name;
+ suggestions.push_back(quoted(signal));
+ }
+ } break;
+ case CompletionKind::THEME_COLORS: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base && Object::cast_to<Control>(base)) {
+ List<StringName> sn;
+ Theme::get_default()->get_color_list(base->get_class(), &sn);
+
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ suggestions.push_back(quoted(E->get()));
+ }
+ }
+ } break;
+ case CompletionKind::THEME_CONSTANTS: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base && Object::cast_to<Control>(base)) {
+ List<StringName> sn;
+ Theme::get_default()->get_constant_list(base->get_class(), &sn);
+
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ suggestions.push_back(quoted(E->get()));
+ }
+ }
+ } break;
+ case CompletionKind::THEME_FONTS: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base && Object::cast_to<Control>(base)) {
+ List<StringName> sn;
+ Theme::get_default()->get_font_list(base->get_class(), &sn);
+
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ suggestions.push_back(quoted(E->get()));
+ }
+ }
+ } break;
+ case CompletionKind::THEME_FONT_SIZES: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base && Object::cast_to<Control>(base)) {
+ List<StringName> sn;
+ Theme::get_default()->get_font_size_list(base->get_class(), &sn);
+
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ suggestions.push_back(quoted(E->get()));
+ }
+ }
+ } break;
+ case CompletionKind::THEME_STYLES: {
+ Ref<Script> script = ResourceLoader::load(p_script_file.simplify_path());
+ Node *base = _try_find_owner_node_in_tree(script);
+ if (base && Object::cast_to<Control>(base)) {
+ List<StringName> sn;
+ Theme::get_default()->get_stylebox_list(base->get_class(), &sn);
+
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ suggestions.push_back(quoted(E->get()));
+ }
+ }
+ } break;
+ default:
+ ERR_FAIL_V_MSG(suggestions, "Invalid completion kind.");
+ }
+
+ return suggestions;
+}
+} // namespace gdmono
diff --git a/modules/mono/editor/code_completion.h b/modules/mono/editor/code_completion.h
new file mode 100644
index 0000000000..7f7521672b
--- /dev/null
+++ b/modules/mono/editor/code_completion.h
@@ -0,0 +1,56 @@
+/*************************************************************************/
+/* code_completion.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 CODE_COMPLETION_H
+#define CODE_COMPLETION_H
+
+#include "core/string/ustring.h"
+#include "core/variant/variant.h"
+
+namespace gdmono {
+
+enum class CompletionKind {
+ INPUT_ACTIONS = 0,
+ NODE_PATHS,
+ RESOURCE_PATHS,
+ SCENE_PATHS,
+ SHADER_PARAMS,
+ SIGNALS,
+ THEME_COLORS,
+ THEME_CONSTANTS,
+ THEME_FONTS,
+ THEME_FONT_SIZES,
+ THEME_STYLES
+};
+
+PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_script_file);
+} // namespace gdmono
+
+#endif // CODE_COMPLETION_H
diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp
index c3e7e67ae9..667e4a3879 100644
--- a/modules/mono/editor/editor_internal_calls.cpp
+++ b/modules/mono/editor/editor_internal_calls.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -47,7 +47,7 @@
#include "../godotsharp_dirs.h"
#include "../mono_gd/gd_mono_marshal.h"
#include "../utils/osx_utils.h"
-#include "bindings_generator.h"
+#include "code_completion.h"
#include "godotsharp_export.h"
#include "script_class_parser.h"
@@ -172,35 +172,6 @@ MonoBoolean godot_icall_EditorProgress_Step(MonoString *p_task, MonoString *p_st
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, MonoString **r_error_str) {
*r_error_str = nullptr;
@@ -224,7 +195,7 @@ int32_t godot_icall_ScriptClassParser_ParseFile(MonoString *p_filepath, MonoObje
}
} else {
String error_str = scp.get_error();
- if (!error_str.empty()) {
+ if (!error_str.is_empty()) {
*r_error_str = GDMonoMarshal::mono_string_from_godot(error_str);
}
}
@@ -323,7 +294,7 @@ MonoObject *godot_icall_Internal_GetScriptsMetadataOrNothing(MonoReflectionType
MonoType *dict_type = mono_reflection_type_get_type(p_dict_reftype);
- uint32_t type_encoding = mono_type_get_type(dict_type);
+ int 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);
@@ -354,6 +325,12 @@ void godot_icall_Internal_ScriptEditorDebugger_ReloadScripts() {
}
}
+MonoArray *godot_icall_Internal_CodeCompletionRequest(int32_t p_kind, MonoString *p_script_file) {
+ String script_file = GDMonoMarshal::mono_string_to_godot(p_script_file);
+ PackedStringArray suggestions = gdmono::get_code_completion((gdmono::CompletionKind)p_kind, script_file);
+ return GDMonoMarshal::PackedStringArray_to_mono_array(suggestions);
+}
+
float godot_icall_Globals_EditorScale() {
return EDSCALE;
}
@@ -392,76 +369,67 @@ MonoBoolean godot_icall_Utils_OS_UnixFileHasExecutableAccess(MonoString *p_file_
}
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);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResDataDir", godot_icall_GodotSharpDirs_ResDataDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResMetadataDir", godot_icall_GodotSharpDirs_ResMetadataDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesBaseDir", godot_icall_GodotSharpDirs_ResAssembliesBaseDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesDir", godot_icall_GodotSharpDirs_ResAssembliesDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResConfigDir", godot_icall_GodotSharpDirs_ResConfigDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempDir", godot_icall_GodotSharpDirs_ResTempDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesBaseDir", godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesDir", godot_icall_GodotSharpDirs_ResTempAssembliesDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoUserDir", godot_icall_GodotSharpDirs_MonoUserDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoLogsDir", godot_icall_GodotSharpDirs_MonoLogsDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoSolutionsDir", godot_icall_GodotSharpDirs_MonoSolutionsDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_BuildLogsDirs", godot_icall_GodotSharpDirs_BuildLogsDirs);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectSlnPath", godot_icall_GodotSharpDirs_ProjectSlnPath);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectCsProjPath", godot_icall_GodotSharpDirs_ProjectCsProjPath);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorToolsDir", godot_icall_GodotSharpDirs_DataEditorToolsDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorPrebuiltApiDir", godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoEtcDir", godot_icall_GodotSharpDirs_DataMonoEtcDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoLibDir", godot_icall_GodotSharpDirs_DataMonoLibDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoBinDir", 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);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Create", godot_icall_EditorProgress_Create);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Dispose", godot_icall_EditorProgress_Dispose);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.EditorProgress::internal_Step", godot_icall_EditorProgress_Step);
// ScriptClassParser
- mono_add_internal_call("GodotTools.Internals.ScriptClassParser::internal_ParseFile", (void *)godot_icall_ScriptClassParser_ParseFile);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.ScriptClassParser::internal_ParseFile", godot_icall_ScriptClassParser_ParseFile);
// ExportPlugin
- mono_add_internal_call("GodotTools.Export.ExportPlugin::internal_GetExportedAssemblyDependencies", (void *)godot_icall_ExportPlugin_GetExportedAssemblyDependencies);
+ GDMonoUtils::add_internal_call("GodotTools.Export.ExportPlugin::internal_GetExportedAssemblyDependencies", godot_icall_ExportPlugin_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_EditorDebuggerNodeReloadScripts", (void *)godot_icall_Internal_EditorDebuggerNodeReloadScripts);
- 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);
- mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorRunPlay", (void *)godot_icall_Internal_EditorRunPlay);
- mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorRunStop", (void *)godot_icall_Internal_EditorRunStop);
- mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebugger_ReloadScripts", (void *)godot_icall_Internal_ScriptEditorDebugger_ReloadScripts);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_UpdateApiAssembliesFromPrebuilt", godot_icall_Internal_UpdateApiAssembliesFromPrebuilt);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_FullTemplatesDir", godot_icall_Internal_FullTemplatesDir);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_SimplifyGodotPath", godot_icall_Internal_SimplifyGodotPath);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_IsOsxAppBundleInstalled", godot_icall_Internal_IsOsxAppBundleInstalled);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotIs32Bits", godot_icall_Internal_GodotIs32Bits);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotIsRealTDouble", godot_icall_Internal_GodotIsRealTDouble);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GodotMainIteration", godot_icall_Internal_GodotMainIteration);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GetCoreApiHash", godot_icall_Internal_GetCoreApiHash);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GetEditorApiHash", godot_icall_Internal_GetEditorApiHash);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_IsAssembliesReloadingNeeded", godot_icall_Internal_IsAssembliesReloadingNeeded);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ReloadAssemblies", godot_icall_Internal_ReloadAssemblies);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorDebuggerNodeReloadScripts", godot_icall_Internal_EditorDebuggerNodeReloadScripts);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorEdit", godot_icall_Internal_ScriptEditorEdit);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorNodeShowScriptScreen", godot_icall_Internal_EditorNodeShowScriptScreen);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_GetScriptsMetadataOrNothing", godot_icall_Internal_GetScriptsMetadataOrNothing);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_MonoWindowsInstallRoot", godot_icall_Internal_MonoWindowsInstallRoot);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorRunPlay", godot_icall_Internal_EditorRunPlay);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_EditorRunStop", godot_icall_Internal_EditorRunStop);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebugger_ReloadScripts", godot_icall_Internal_ScriptEditorDebugger_ReloadScripts);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Internal::internal_CodeCompletionRequest", godot_icall_Internal_CodeCompletionRequest);
// 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);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorScale", godot_icall_Globals_EditorScale);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_GlobalDef", godot_icall_Globals_GlobalDef);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_EditorDef", godot_icall_Globals_EditorDef);
+ GDMonoUtils::add_internal_call("GodotTools.Internals.Globals::internal_TTR", godot_icall_Globals_TTR);
// Utils.OS
- mono_add_internal_call("GodotTools.Utils.OS::GetPlatformName", (void *)godot_icall_Utils_OS_GetPlatformName);
- mono_add_internal_call("GodotTools.Utils.OS::UnixFileHasExecutableAccess", (void *)godot_icall_Utils_OS_UnixFileHasExecutableAccess);
+ GDMonoUtils::add_internal_call("GodotTools.Utils.OS::GetPlatformName", godot_icall_Utils_OS_GetPlatformName);
+ GDMonoUtils::add_internal_call("GodotTools.Utils.OS::UnixFileHasExecutableAccess", godot_icall_Utils_OS_UnixFileHasExecutableAccess);
}
diff --git a/modules/mono/editor/editor_internal_calls.h b/modules/mono/editor/editor_internal_calls.h
index ef4e639161..24080cd867 100644
--- a/modules/mono/editor/editor_internal_calls.h
+++ b/modules/mono/editor/editor_internal_calls.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp
index 4126da16be..4b858c0e82 100644
--- a/modules/mono/editor/godotsharp_export.cpp
+++ b/modules/mono/editor/godotsharp_export.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,70 +32,73 @@
#include <mono/metadata/image.h>
+#include "core/config/project_settings.h"
+#include "core/io/file_access_pack.h"
#include "core/os/os.h"
#include "../mono_gd/gd_mono.h"
#include "../mono_gd/gd_mono_assembly.h"
#include "../mono_gd/gd_mono_cache.h"
+#include "../utils/macros.h"
namespace GodotSharpExport {
-String get_assemblyref_name(MonoImage *p_image, int index) {
+MonoAssemblyName *new_mono_assembly_name() {
+ // Mono has no public API to create an empty MonoAssemblyName and the struct is private.
+ // As such the only way to create it is with a stub name and then clear it.
+
+ MonoAssemblyName *aname = mono_assembly_name_new("stub");
+ CRASH_COND(aname == nullptr);
+ mono_assembly_name_free(aname); // Frees the string fields, not the struct
+ return aname;
+}
+
+struct AssemblyRefInfo {
+ String name;
+ uint16_t major = 0;
+ uint16_t minor = 0;
+ uint16_t build = 0;
+ uint16_t revision = 0;
+};
+
+AssemblyRefInfo get_assemblyref_name(MonoImage *p_image, int index) {
const MonoTableInfo *table_info = mono_image_get_table_info(p_image, MONO_TABLE_ASSEMBLYREF);
uint32_t cols[MONO_ASSEMBLYREF_SIZE];
mono_metadata_decode_row(table_info, index, cols, MONO_ASSEMBLYREF_SIZE);
- return String::utf8(mono_metadata_string_heap(p_image, cols[MONO_ASSEMBLYREF_NAME]));
+ return {
+ String::utf8(mono_metadata_string_heap(p_image, cols[MONO_ASSEMBLYREF_NAME])),
+ (uint16_t)cols[MONO_ASSEMBLYREF_MAJOR_VERSION],
+ (uint16_t)cols[MONO_ASSEMBLYREF_MINOR_VERSION],
+ (uint16_t)cols[MONO_ASSEMBLYREF_BUILD_NUMBER],
+ (uint16_t)cols[MONO_ASSEMBLYREF_REV_NUMBER]
+ };
}
-Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_assembly_dependencies) {
+Error get_assembly_dependencies(GDMonoAssembly *p_assembly, MonoAssemblyName *reusable_aname, const Vector<String> &p_search_dirs, Dictionary &r_assembly_dependencies) {
MonoImage *image = p_assembly->get_image();
for (int i = 0; i < mono_image_get_table_rows(image, MONO_TABLE_ASSEMBLYREF); i++) {
- String ref_name = get_assemblyref_name(image, i);
+ AssemblyRefInfo ref_info = get_assemblyref_name(image, i);
- if (r_assembly_dependencies.has(ref_name))
- continue;
+ const String &ref_name = ref_info.name;
- GDMonoAssembly *ref_assembly = nullptr;
- String path;
- bool has_extension = ref_name.ends_with(".dll") || ref_name.ends_with(".exe");
-
- for (int j = 0; j < p_search_dirs.size(); j++) {
- const String &search_dir = p_search_dirs[j];
-
- if (has_extension) {
- path = search_dir.plus_file(ref_name);
- if (FileAccess::exists(path)) {
- GDMono::get_singleton()->load_assembly_from(ref_name.get_basename(), path, &ref_assembly, true);
- if (ref_assembly != nullptr)
- break;
- }
- } else {
- path = search_dir.plus_file(ref_name + ".dll");
- if (FileAccess::exists(path)) {
- GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true);
- if (ref_assembly != nullptr)
- break;
- }
-
- path = search_dir.plus_file(ref_name + ".exe");
- if (FileAccess::exists(path)) {
- GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true);
- if (ref_assembly != nullptr)
- break;
- }
- }
+ if (r_assembly_dependencies.has(ref_name)) {
+ continue;
}
- ERR_FAIL_COND_V_MSG(!ref_assembly, ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + ref_name + "'.");
+ mono_assembly_get_assemblyref(image, i, reusable_aname);
- // Use the path we got from the search. Don't try to get the path from the loaded assembly as we can't trust it will be from the selected BCL dir.
- r_assembly_dependencies[ref_name] = path;
+ GDMonoAssembly *ref_assembly = NULL;
+ if (!GDMono::get_singleton()->load_assembly(ref_name, reusable_aname, &ref_assembly, /* refonly: */ true, p_search_dirs)) {
+ ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + ref_name + "'.");
+ }
- Error err = get_assembly_dependencies(ref_assembly, p_search_dirs, r_assembly_dependencies);
+ r_assembly_dependencies[ref_name] = ref_assembly->get_path();
+
+ Error err = get_assembly_dependencies(ref_assembly, reusable_aname, p_search_dirs, r_assembly_dependencies);
ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot load one of the dependencies for the assembly: '" + ref_name + "'.");
}
@@ -113,6 +116,11 @@ Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies,
Vector<String> search_dirs;
GDMonoAssembly::fill_search_dirs(search_dirs, p_build_config, p_custom_bcl_dir);
+ if (p_custom_bcl_dir.length()) {
+ // Only one mscorlib can be loaded. We need this workaround to make sure we get it from the right BCL directory.
+ r_assembly_dependencies["mscorlib"] = p_custom_bcl_dir.plus_file("mscorlib.dll").simplify_path();
+ }
+
for (const Variant *key = p_initial_assemblies.next(); key; key = p_initial_assemblies.next(key)) {
String assembly_name = *key;
String assembly_path = p_initial_assemblies[*key];
@@ -122,12 +130,15 @@ Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies,
ERR_FAIL_COND_V_MSG(!load_success, ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + assembly_name + "'.");
- Error err = get_assembly_dependencies(assembly, search_dirs, r_assembly_dependencies);
- if (err != OK)
+ MonoAssemblyName *reusable_aname = new_mono_assembly_name();
+ SCOPE_EXIT { mono_free(reusable_aname); };
+
+ Error err = get_assembly_dependencies(assembly, reusable_aname, search_dirs, r_assembly_dependencies);
+ if (err != OK) {
return err;
+ }
}
return OK;
}
-
} // namespace GodotSharpExport
diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h
index 9ab57755de..0e9d689618 100644
--- a/modules/mono/editor/godotsharp_export.h
+++ b/modules/mono/editor/godotsharp_export.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,9 +31,9 @@
#ifndef GODOTSHARP_EXPORT_H
#define GODOTSHARP_EXPORT_H
-#include "core/dictionary.h"
-#include "core/error_list.h"
-#include "core/ustring.h"
+#include "core/error/error_list.h"
+#include "core/string/ustring.h"
+#include "core/variant/dictionary.h"
#include "../mono_gd/gd_mono_header.h"
@@ -43,7 +43,6 @@ Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String>
Error get_exported_assembly_dependencies(const Dictionary &p_initial_assemblies,
const String &p_build_config, const String &p_custom_lib_dir, Dictionary &r_assembly_dependencies);
-
} // namespace GodotSharpExport
#endif // GODOTSHARP_EXPORT_H
diff --git a/modules/mono/editor/script_class_parser.cpp b/modules/mono/editor/script_class_parser.cpp
index bece23c9a6..e81cbe4ebd 100644
--- a/modules/mono/editor/script_class_parser.cpp
+++ b/modules/mono/editor/script_class_parser.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,8 +30,8 @@
#include "script_class_parser.h"
-#include "core/map.h"
#include "core/os/os.h"
+#include "core/templates/map.h"
#include "../utils/string_utils.h"
@@ -54,13 +54,11 @@ const char *ScriptClassParser::token_names[ScriptClassParser::TK_MAX] = {
};
String ScriptClassParser::get_token_name(ScriptClassParser::Token p_token) {
-
ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>");
return token_names[p_token];
}
ScriptClassParser::Token ScriptClassParser::get_token() {
-
while (true) {
switch (code[idx]) {
case '\n': {
@@ -153,7 +151,7 @@ ScriptClassParser::Token ScriptClassParser::get_token() {
case '"': {
bool verbatim = idx != 0 && code[idx - 1] == '@';
- CharType begin_str = code[idx];
+ char32_t begin_str = code[idx];
idx++;
String tk_string = String();
while (true) {
@@ -172,23 +170,33 @@ ScriptClassParser::Token ScriptClassParser::get_token() {
} else if (code[idx] == '\\' && !verbatim) {
//escaped characters...
idx++;
- CharType next = code[idx];
+ char32_t next = code[idx];
if (next == 0) {
error_str = "Unterminated String";
error = true;
return TK_ERROR;
}
- CharType res = 0;
+ char32_t res = 0;
switch (next) {
- case 'b': res = 8; break;
- case 't': res = 9; break;
- case 'n': res = 10; break;
- case 'f': res = 12; break;
+ case 'b':
+ res = 8;
+ break;
+ case 't':
+ res = 9;
+ break;
+ case 'n':
+ res = 10;
+ break;
+ case 'f':
+ res = 12;
+ break;
case 'r':
res = 13;
break;
- case '\"': res = '\"'; break;
+ case '\"':
+ res = '\"';
+ break;
case '\\':
res = '\\';
break;
@@ -200,8 +208,9 @@ ScriptClassParser::Token ScriptClassParser::get_token() {
tk_string += res;
} else {
- if (code[idx] == '\n')
+ if (code[idx] == '\n') {
line++;
+ }
tk_string += code[idx];
}
idx++;
@@ -225,8 +234,8 @@ ScriptClassParser::Token ScriptClassParser::get_token() {
if (code[idx] == '-' || (code[idx] >= '0' && code[idx] <= '9')) {
//a number
- const CharType *rptr;
- double number = String::to_double(&code[idx], &rptr);
+ const char32_t *rptr;
+ double number = String::to_float(&code[idx], &rptr);
idx += (rptr - &code[idx]);
value = number;
return TK_NUMBER;
@@ -258,7 +267,6 @@ ScriptClassParser::Token ScriptClassParser::get_token() {
}
Error ScriptClassParser::_skip_generic_type_params() {
-
Token tk;
while (true) {
@@ -293,15 +301,17 @@ Error ScriptClassParser::_skip_generic_type_params() {
tk = get_token();
- if (tk != TK_PERIOD)
+ if (tk != TK_PERIOD) {
break;
+ }
}
}
if (tk == TK_OP_LESS) {
Error err = _skip_generic_type_params();
- if (err)
+ if (err) {
return err;
+ }
tk = get_token();
}
@@ -327,7 +337,6 @@ Error ScriptClassParser::_skip_generic_type_params() {
}
Error ScriptClassParser::_parse_type_full_name(String &r_full_name) {
-
Token tk = get_token();
if (tk != TK_IDENTIFIER) {
@@ -343,12 +352,14 @@ Error ScriptClassParser::_parse_type_full_name(String &r_full_name) {
// We don't mind if the base is generic, but we skip it any ways since this information is not needed
Error err = _skip_generic_type_params();
- if (err)
+ if (err) {
return err;
+ }
}
- if (code[idx] != '.') // We only want to take the next token if it's a period
+ if (code[idx] != '.') { // We only want to take the next token if it's a period
return OK;
+ }
tk = get_token();
@@ -360,19 +371,20 @@ Error ScriptClassParser::_parse_type_full_name(String &r_full_name) {
}
Error ScriptClassParser::_parse_class_base(Vector<String> &r_base) {
-
String name;
Error err = _parse_type_full_name(name);
- if (err)
+ if (err) {
return err;
+ }
Token tk = get_token();
if (tk == TK_COMMA) {
err = _parse_class_base(r_base);
- if (err)
+ if (err) {
return err;
+ }
} else if (tk == TK_IDENTIFIER && String(value) == "where") {
err = _parse_type_constraints();
if (err) {
@@ -428,8 +440,9 @@ Error ScriptClassParser::_parse_type_constraints() {
tk = get_token();
- if (tk != TK_PERIOD)
+ if (tk != TK_PERIOD) {
break;
+ }
}
}
}
@@ -447,8 +460,9 @@ Error ScriptClassParser::_parse_type_constraints() {
}
} else if (tk == TK_OP_LESS) {
Error err = _skip_generic_type_params();
- if (err)
+ if (err) {
return err;
+ }
} else if (tk == TK_CURLY_BRACKET_OPEN) {
return OK;
} else {
@@ -460,7 +474,6 @@ Error ScriptClassParser::_parse_type_constraints() {
}
Error ScriptClassParser::_parse_namespace_name(String &r_name, int &r_curly_stack) {
-
Token tk = get_token();
if (tk == TK_IDENTIFIER) {
@@ -487,7 +500,6 @@ Error ScriptClassParser::_parse_namespace_name(String &r_name, int &r_curly_stac
}
Error ScriptClassParser::parse(const String &p_code) {
-
code = p_code;
idx = 0;
line = 0;
@@ -519,8 +531,9 @@ Error ScriptClassParser::parse(const String &p_code) {
const NameDecl &name_decl = E->value();
if (name_decl.type == NameDecl::NAMESPACE_DECL) {
- if (E != name_stack.front())
+ if (E != name_stack.front()) {
class_decl.namespace_ += ".";
+ }
class_decl.namespace_ += name_decl.name;
} else {
class_decl.name += name_decl.name + ".";
@@ -537,8 +550,9 @@ Error ScriptClassParser::parse(const String &p_code) {
if (tk == TK_COLON) {
Error err = _parse_class_base(class_decl.base);
- if (err)
+ if (err) {
return err;
+ }
curly_stack++;
type_curly_stack++;
@@ -552,8 +566,9 @@ Error ScriptClassParser::parse(const String &p_code) {
generic = true;
Error err = _skip_generic_type_params();
- if (err)
+ if (err) {
return err;
+ }
} else if (tk == TK_IDENTIFIER && String(value) == "where") {
Error err = _parse_type_constraints();
if (err) {
@@ -581,8 +596,9 @@ Error ScriptClassParser::parse(const String &p_code) {
classes.push_back(class_decl);
} else if (OS::get_singleton()->is_stdout_verbose()) {
String full_name = class_decl.namespace_;
- if (full_name.length())
+ if (full_name.length()) {
full_name += ".";
+ }
full_name += class_decl.name;
OS::get_singleton()->print("Ignoring generic class declaration: %s\n", full_name.utf8().get_data());
}
@@ -599,8 +615,9 @@ Error ScriptClassParser::parse(const String &p_code) {
int at_level = curly_stack;
Error err = _parse_namespace_name(name, curly_stack);
- if (err)
+ if (err) {
return err;
+ }
NameDecl name_decl;
name_decl.name = name;
@@ -611,8 +628,9 @@ Error ScriptClassParser::parse(const String &p_code) {
} else if (tk == TK_CURLY_BRACKET_CLOSE) {
curly_stack--;
if (name_stack.has(curly_stack)) {
- if (name_stack[curly_stack].type != NameDecl::NAMESPACE_DECL)
+ if (name_stack[curly_stack].type != NameDecl::NAMESPACE_DECL) {
type_curly_stack--;
+ }
name_stack.erase(curly_stack);
}
}
@@ -625,8 +643,9 @@ Error ScriptClassParser::parse(const String &p_code) {
error = true;
}
- if (error)
+ if (error) {
return ERR_PARSE_ERROR;
+ }
return OK;
}
@@ -643,7 +662,6 @@ static String get_preprocessor_directive(const String &p_line, int p_from) {
}
static void run_dummy_preprocessor(String &r_source, const String &p_filepath) {
-
Vector<String> lines = r_source.split("\n", /* p_allow_empty: */ true);
bool *include_lines = memnew_arr(bool, lines.size());
@@ -700,8 +718,9 @@ static void run_dummy_preprocessor(String &r_source, const String &p_filepath) {
// Custom join ignoring lines removed by the preprocessor
for (int i = 0; i < lines.size(); i++) {
- if (i > 0 && include_lines[i - 1])
+ if (i > 0 && include_lines[i - 1]) {
r_source += '\n';
+ }
if (include_lines[i]) {
r_source += lines[i];
@@ -710,16 +729,15 @@ static void run_dummy_preprocessor(String &r_source, const String &p_filepath) {
}
Error ScriptClassParser::parse_file(const String &p_filepath) {
-
String source;
Error ferr = read_all_file_utf8(p_filepath, source);
ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
ferr == ERR_INVALID_DATA ?
- "File '" + p_filepath + "' contains invalid unicode (UTF-8), so it was not loaded."
+ "File '" + p_filepath + "' contains invalid unicode (UTF-8), so it was not loaded."
" Please ensure that scripts are saved in valid UTF-8 unicode." :
- "Failed to read file: '" + p_filepath + "'.");
+ "Failed to read file: '" + p_filepath + "'.");
run_dummy_preprocessor(source, p_filepath);
diff --git a/modules/mono/editor/script_class_parser.h b/modules/mono/editor/script_class_parser.h
index a76a3a50a9..75a46bb4e5 100644
--- a/modules/mono/editor/script_class_parser.h
+++ b/modules/mono/editor/script_class_parser.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,11 @@
#ifndef SCRIPT_CLASS_PARSER_H
#define SCRIPT_CLASS_PARSER_H
-#include "core/ustring.h"
-#include "core/variant.h"
-#include "core/vector.h"
+#include "core/string/ustring.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
class ScriptClassParser {
-
public:
struct NameDecl {
enum Type {
@@ -46,23 +45,22 @@ public:
};
String name;
- Type type;
+ Type type = NAMESPACE_DECL;
};
struct ClassDecl {
String name;
String namespace_;
Vector<String> base;
- bool nested;
- bool has_script_attr;
+ bool nested = false;
};
private:
String code;
- int idx;
- int line;
+ int idx = 0;
+ int line = 0;
String error_str;
- bool error;
+ bool error = false;
Variant value;
Vector<ClassDecl> classes;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
index 6a4f785551..3aecce50f5 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs
@@ -14,6 +14,10 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// Axis-Aligned Bounding Box. AABB consists of a position, a size, and
+ /// several utility functions. It is typically used for fast overlap tests.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct AABB : IEquatable<AABB>
@@ -21,24 +25,55 @@ namespace Godot
private Vector3 _position;
private Vector3 _size;
+ /// <summary>
+ /// Beginning corner. Typically has values lower than End.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector3 Position
{
get { return _position; }
set { _position = value; }
}
+ /// <summary>
+ /// Size from Position to End. Typically all components are positive.
+ /// If the size is negative, you can use <see cref="Abs"/> to fix it.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector3 Size
{
get { return _size; }
set { _size = value; }
}
+ /// <summary>
+ /// Ending corner. This is calculated as <see cref="Position"/> plus
+ /// <see cref="Size"/>. Setting this value will change the size.
+ /// </summary>
+ /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value>
public Vector3 End
{
get { return _position + _size; }
set { _size = value - _position; }
}
+ /// <summary>
+ /// Returns an AABB with equivalent position and size, modified so that
+ /// the most-negative corner is the origin and the size is positive.
+ /// </summary>
+ /// <returns>The modified AABB.</returns>
+ public AABB Abs()
+ {
+ Vector3 end = End;
+ Vector3 topLeft = new Vector3(Mathf.Min(_position.x, end.x), Mathf.Min(_position.y, end.y), Mathf.Min(_position.z, end.z));
+ return new AABB(topLeft, _size.Abs());
+ }
+
+ /// <summary>
+ /// Returns true if this AABB completely encloses another one.
+ /// </summary>
+ /// <param name="with">The other AABB that may be enclosed.</param>
+ /// <returns>A bool for whether or not this AABB encloses `b`.</returns>
public bool Encloses(AABB with)
{
Vector3 src_min = _position;
@@ -54,33 +89,59 @@ namespace Godot
src_max.z > dst_max.z;
}
+ /// <summary>
+ /// Returns this AABB expanded to include a given point.
+ /// </summary>
+ /// <param name="point">The point to include.</param>
+ /// <returns>The expanded AABB.</returns>
public AABB Expand(Vector3 point)
{
Vector3 begin = _position;
Vector3 end = _position + _size;
if (point.x < begin.x)
+ {
begin.x = point.x;
+ }
if (point.y < begin.y)
+ {
begin.y = point.y;
+ }
if (point.z < begin.z)
+ {
begin.z = point.z;
+ }
if (point.x > end.x)
+ {
end.x = point.x;
+ }
if (point.y > end.y)
+ {
end.y = point.y;
+ }
if (point.z > end.z)
+ {
end.z = point.z;
+ }
return new AABB(begin, end - begin);
}
+ /// <summary>
+ /// Returns the area of the AABB.
+ /// </summary>
+ /// <returns>The area.</returns>
public real_t GetArea()
{
return _size.x * _size.y * _size.z;
}
+ /// <summary>
+ /// Gets the position of one of the 8 endpoints of the AABB.
+ /// </summary>
+ /// <param name="idx">Which endpoint to get.</param>
+ /// <returns>An endpoint of the AABB.</returns>
public Vector3 GetEndpoint(int idx)
{
switch (idx)
@@ -106,6 +167,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns the normalized longest axis of the AABB.
+ /// </summary>
+ /// <returns>A vector representing the normalized longest axis of the AABB.</returns>
public Vector3 GetLongestAxis()
{
var axis = new Vector3(1f, 0f, 0f);
@@ -125,6 +190,10 @@ namespace Godot
return axis;
}
+ /// <summary>
+ /// Returns the <see cref="Vector3.Axis"/> index of the longest axis of the AABB.
+ /// </summary>
+ /// <returns>A <see cref="Vector3.Axis"/> index for which axis is longest.</returns>
public Vector3.Axis GetLongestAxisIndex()
{
var axis = Vector3.Axis.X;
@@ -144,6 +213,10 @@ namespace Godot
return axis;
}
+ /// <summary>
+ /// Returns the scalar length of the longest axis of the AABB.
+ /// </summary>
+ /// <returns>The scalar length of the longest axis of the AABB.</returns>
public real_t GetLongestAxisSize()
{
real_t max_size = _size.x;
@@ -157,6 +230,10 @@ namespace Godot
return max_size;
}
+ /// <summary>
+ /// Returns the normalized shortest axis of the AABB.
+ /// </summary>
+ /// <returns>A vector representing the normalized shortest axis of the AABB.</returns>
public Vector3 GetShortestAxis()
{
var axis = new Vector3(1f, 0f, 0f);
@@ -176,6 +253,10 @@ namespace Godot
return axis;
}
+ /// <summary>
+ /// Returns the <see cref="Vector3.Axis"/> index of the shortest axis of the AABB.
+ /// </summary>
+ /// <returns>A <see cref="Vector3.Axis"/> index for which axis is shortest.</returns>
public Vector3.Axis GetShortestAxisIndex()
{
var axis = Vector3.Axis.X;
@@ -195,6 +276,10 @@ namespace Godot
return axis;
}
+ /// <summary>
+ /// Returns the scalar length of the shortest axis of the AABB.
+ /// </summary>
+ /// <returns>The scalar length of the shortest axis of the AABB.</returns>
public real_t GetShortestAxisSize()
{
real_t max_size = _size.x;
@@ -208,6 +293,12 @@ namespace Godot
return max_size;
}
+ /// <summary>
+ /// Returns the support point in a given direction.
+ /// This is useful for collision detection algorithms.
+ /// </summary>
+ /// <param name="dir">The direction to find support for.</param>
+ /// <returns>A vector representing the support.</returns>
public Vector3 GetSupport(Vector3 dir)
{
Vector3 half_extents = _size * 0.5f;
@@ -219,6 +310,11 @@ namespace Godot
dir.z > 0f ? -half_extents.z : half_extents.z);
}
+ /// <summary>
+ /// Returns a copy of the AABB grown a given amount of units towards all the sides.
+ /// </summary>
+ /// <param name="by">The amount to grow by.</param>
+ /// <returns>The grown AABB.</returns>
public AABB Grow(real_t by)
{
var res = this;
@@ -233,16 +329,29 @@ namespace Godot
return res;
}
+ /// <summary>
+ /// Returns true if the AABB is flat or empty, or false otherwise.
+ /// </summary>
+ /// <returns>A bool for whether or not the AABB has area.</returns>
public bool HasNoArea()
{
return _size.x <= 0f || _size.y <= 0f || _size.z <= 0f;
}
+ /// <summary>
+ /// Returns true if the AABB has no surface (no size), or false otherwise.
+ /// </summary>
+ /// <returns>A bool for whether or not the AABB has area.</returns>
public bool HasNoSurface()
{
return _size.x <= 0f && _size.y <= 0f && _size.z <= 0f;
}
+ /// <summary>
+ /// Returns true if the AABB contains a point, or false otherwise.
+ /// </summary>
+ /// <param name="point">The point to check.</param>
+ /// <returns>A bool for whether or not the AABB contains `point`.</returns>
public bool HasPoint(Vector3 point)
{
if (point.x < _position.x)
@@ -261,6 +370,11 @@ namespace Godot
return true;
}
+ /// <summary>
+ /// Returns the intersection of this AABB and `b`.
+ /// </summary>
+ /// <param name="with">The other AABB.</param>
+ /// <returns>The clipped AABB.</returns>
public AABB Intersection(AABB with)
{
Vector3 src_min = _position;
@@ -297,24 +411,57 @@ namespace Godot
return new AABB(min, max - min);
}
- public bool Intersects(AABB with)
+ /// <summary>
+ /// Returns true if the AABB overlaps with `b`
+ /// (i.e. they have at least one point in common).
+ ///
+ /// If `includeBorders` is true, they will also be considered overlapping
+ /// if their borders touch, even without intersection.
+ /// </summary>
+ /// <param name="with">The other AABB to check for intersections with.</param>
+ /// <param name="includeBorders">Whether or not to consider borders.</param>
+ /// <returns>A bool for whether or not they are intersecting.</returns>
+ public bool Intersects(AABB with, bool includeBorders = false)
{
- if (_position.x >= with._position.x + with._size.x)
- return false;
- if (_position.x + _size.x <= with._position.x)
- return false;
- if (_position.y >= with._position.y + with._size.y)
- return false;
- if (_position.y + _size.y <= with._position.y)
- return false;
- if (_position.z >= with._position.z + with._size.z)
- return false;
- if (_position.z + _size.z <= with._position.z)
- return false;
+ if (includeBorders)
+ {
+ if (_position.x > with._position.x + with._size.x)
+ return false;
+ if (_position.x + _size.x < with._position.x)
+ return false;
+ if (_position.y > with._position.y + with._size.y)
+ return false;
+ if (_position.y + _size.y < with._position.y)
+ return false;
+ if (_position.z > with._position.z + with._size.z)
+ return false;
+ if (_position.z + _size.z < with._position.z)
+ return false;
+ }
+ else
+ {
+ if (_position.x >= with._position.x + with._size.x)
+ return false;
+ if (_position.x + _size.x <= with._position.x)
+ return false;
+ if (_position.y >= with._position.y + with._size.y)
+ return false;
+ if (_position.y + _size.y <= with._position.y)
+ return false;
+ if (_position.z >= with._position.z + with._size.z)
+ return false;
+ if (_position.z + _size.z <= with._position.z)
+ return false;
+ }
return true;
}
+ /// <summary>
+ /// Returns true if the AABB is on both sides of `plane`.
+ /// </summary>
+ /// <param name="plane">The plane to check for intersection.</param>
+ /// <returns>A bool for whether or not the AABB intersects the plane.</returns>
public bool IntersectsPlane(Plane plane)
{
Vector3[] points =
@@ -335,14 +482,24 @@ namespace Godot
for (int i = 0; i < 8; i++)
{
if (plane.DistanceTo(points[i]) > 0)
+ {
over = true;
+ }
else
+ {
under = true;
+ }
}
return under && over;
}
+ /// <summary>
+ /// Returns true if the AABB intersects the line segment between `from` and `to`.
+ /// </summary>
+ /// <param name="from">The start of the line segment.</param>
+ /// <param name="to">The end of the line segment.</param>
+ /// <returns>A bool for whether or not the AABB intersects the line segment.</returns>
public bool IntersectsSegment(Vector3 from, Vector3 to)
{
real_t min = 0f;
@@ -359,7 +516,9 @@ namespace Godot
if (segFrom < segTo)
{
if (segFrom > boxEnd || segTo < boxBegin)
+ {
return false;
+ }
real_t length = segTo - segFrom;
cmin = segFrom < boxBegin ? (boxBegin - segFrom) / length : 0f;
@@ -368,7 +527,9 @@ namespace Godot
else
{
if (segTo > boxEnd || segFrom < boxBegin)
+ {
return false;
+ }
real_t length = segTo - segFrom;
cmin = segFrom > boxEnd ? (boxEnd - segFrom) / length : 0f;
@@ -381,14 +542,23 @@ namespace Godot
}
if (cmax < max)
+ {
max = cmax;
+ }
if (max < min)
+ {
return false;
+ }
}
return true;
}
+ /// <summary>
+ /// Returns a larger AABB that contains this AABB and `b`.
+ /// </summary>
+ /// <param name="with">The other AABB.</param>
+ /// <returns>The merged AABB.</returns>
public AABB Merge(AABB with)
{
Vector3 beg1 = _position;
@@ -411,22 +581,52 @@ namespace Godot
return new AABB(min, max - min);
}
- // Constructors
+ /// <summary>
+ /// Constructs an AABB from a position and size.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="size">The size, typically positive.</param>
public AABB(Vector3 position, Vector3 size)
{
_position = position;
_size = size;
}
+
+ /// <summary>
+ /// Constructs an AABB from a position, width, height, and depth.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="width">The width, typically positive.</param>
+ /// <param name="height">The height, typically positive.</param>
+ /// <param name="depth">The depth, typically positive.</param>
public AABB(Vector3 position, real_t width, real_t height, real_t depth)
{
_position = position;
_size = new Vector3(width, height, depth);
}
+
+ /// <summary>
+ /// Constructs an AABB from x, y, z, and size.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="z">The position's Z coordinate.</param>
+ /// <param name="size">The size, typically positive.</param>
public AABB(real_t x, real_t y, real_t z, Vector3 size)
{
_position = new Vector3(x, y, z);
_size = size;
}
+
+ /// <summary>
+ /// Constructs an AABB from x, y, z, width, height, and depth.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="z">The position's Z coordinate.</param>
+ /// <param name="width">The width, typically positive.</param>
+ /// <param name="height">The height, typically positive.</param>
+ /// <param name="depth">The depth, typically positive.</param>
public AABB(real_t x, real_t y, real_t z, real_t width, real_t height, real_t depth)
{
_position = new Vector3(x, y, z);
@@ -458,6 +658,12 @@ namespace Godot
return _position == other._position && _size == other._size;
}
+ /// <summary>
+ /// Returns true if this AABB and `other` are approximately equal, by running
+ /// <see cref="Vector3.IsEqualApprox(Vector3)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other AABB to compare.</param>
+ /// <returns>Whether or not the AABBs are approximately equal.</returns>
public bool IsEqualApprox(AABB other)
{
return _position.IsEqualApprox(other._position) && _size.IsEqualApprox(other._size);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
index a963810d63..ce613f7ef9 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs
@@ -44,6 +44,15 @@ namespace Godot.Collections
Add(element);
}
+ public Array(params object[] array) : this()
+ {
+ if (array == null)
+ {
+ throw new NullReferenceException($"Parameter '{nameof(array)} cannot be null.'");
+ }
+ safeHandle = new ArraySafeHandle(godot_icall_Array_Ctor_MonoArray(array));
+ }
+
internal Array(ArraySafeHandle handle)
{
safeHandle = handle;
@@ -72,6 +81,16 @@ namespace Godot.Collections
return godot_icall_Array_Resize(GetPtr(), newSize);
}
+ public void Shuffle()
+ {
+ godot_icall_Array_Shuffle(GetPtr());
+ }
+
+ public static Array operator +(Array left, Array right)
+ {
+ return new Array(godot_icall_Array_Concatenate(left.GetPtr(), right.GetPtr()));
+ }
+
// IDisposable
public void Dispose()
@@ -155,6 +174,9 @@ namespace Godot.Collections
internal extern static IntPtr godot_icall_Array_Ctor();
[MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern static IntPtr godot_icall_Array_Ctor_MonoArray(System.Array array);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
internal extern static void godot_icall_Array_Dtor(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
@@ -176,6 +198,9 @@ namespace Godot.Collections
internal extern static void godot_icall_Array_Clear(IntPtr ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern static IntPtr godot_icall_Array_Concatenate(IntPtr left, IntPtr right);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
internal extern static bool godot_icall_Array_Contains(IntPtr ptr, object item);
[MethodImpl(MethodImplOptions.InternalCall)]
@@ -200,6 +225,9 @@ namespace Godot.Collections
internal extern static Error godot_icall_Array_Resize(IntPtr ptr, int newSize);
[MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern static Error godot_icall_Array_Shuffle(IntPtr ptr);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
internal extern static void godot_icall_Array_Generic_GetElementTypeInfo(Type elemType, out int elemTypeEncoding, out IntPtr elemTypeClass);
[MethodImpl(MethodImplOptions.InternalCall)]
@@ -231,6 +259,15 @@ namespace Godot.Collections
objectArray = new Array(collection);
}
+ public Array(params T[] array) : this()
+ {
+ if (array == null)
+ {
+ throw new NullReferenceException($"Parameter '{nameof(array)} cannot be null.'");
+ }
+ objectArray = new Array(array);
+ }
+
public Array(Array array)
{
objectArray = array;
@@ -266,6 +303,16 @@ namespace Godot.Collections
return objectArray.Resize(newSize);
}
+ public void Shuffle()
+ {
+ objectArray.Shuffle();
+ }
+
+ public static Array<T> operator +(Array<T> left, Array<T> right)
+ {
+ return new Array<T>(left.objectArray + right.objectArray);
+ }
+
// IList<T>
public T this[int index]
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
index baf470a0cc..3f1120575f 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs
@@ -8,6 +8,20 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 3×3 matrix used for 3D rotation and scale.
+ /// Almost always used as an orthogonal basis for a Transform.
+ ///
+ /// Contains 3 vector fields X, Y and Z as its columns, which are typically
+ /// interpreted as the local basis vectors of a 3D transformation. For such use,
+ /// it is composed of a scaling and a rotation matrix, in that order (M = R.S).
+ ///
+ /// Can also be accessed as array of 3D vectors. These vectors are normally
+ /// orthogonal to each other, but are not necessarily normalized (due to scaling).
+ ///
+ /// For more information, read this documentation article:
+ /// https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Basis : IEquatable<Basis>
@@ -15,9 +29,9 @@ namespace Godot
// NOTE: x, y and z are public-only. Use Column0, Column1 and Column2 internally.
/// <summary>
- /// Returns the basis matrix’s x vector.
- /// This is equivalent to <see cref="Column0"/>.
+ /// The basis matrix's X vector (column 0).
/// </summary>
+ /// <value>Equivalent to <see cref="Column0"/> and array index `[0]`.</value>
public Vector3 x
{
get => Column0;
@@ -25,9 +39,9 @@ namespace Godot
}
/// <summary>
- /// Returns the basis matrix’s y vector.
- /// This is equivalent to <see cref="Column1"/>.
+ /// The basis matrix's Y vector (column 1).
/// </summary>
+ /// <value>Equivalent to <see cref="Column1"/> and array index `[1]`.</value>
public Vector3 y
{
get => Column1;
@@ -35,19 +49,40 @@ namespace Godot
}
/// <summary>
- /// Returns the basis matrix’s z vector.
- /// This is equivalent to <see cref="Column2"/>.
+ /// The basis matrix's Z vector (column 2).
/// </summary>
+ /// <value>Equivalent to <see cref="Column2"/> and array index `[2]`.</value>
public Vector3 z
{
get => Column2;
set => Column2 = value;
}
+ /// <summary>
+ /// Row 0 of the basis matrix. Shows which vectors contribute
+ /// to the X direction. Rows are not very useful for user code,
+ /// but are more efficient for some internal calculations.
+ /// </summary>
public Vector3 Row0;
+
+ /// <summary>
+ /// Row 1 of the basis matrix. Shows which vectors contribute
+ /// to the Y direction. Rows are not very useful for user code,
+ /// but are more efficient for some internal calculations.
+ /// </summary>
public Vector3 Row1;
+
+ /// <summary>
+ /// Row 2 of the basis matrix. Shows which vectors contribute
+ /// to the Z direction. Rows are not very useful for user code,
+ /// but are more efficient for some internal calculations.
+ /// </summary>
public Vector3 Row2;
+ /// <summary>
+ /// Column 0 of the basis matrix (the X vector).
+ /// </summary>
+ /// <value>Equivalent to <see cref="x"/> and array index `[0]`.</value>
public Vector3 Column0
{
get => new Vector3(Row0.x, Row1.x, Row2.x);
@@ -58,6 +93,11 @@ namespace Godot
this.Row2.x = value.z;
}
}
+
+ /// <summary>
+ /// Column 1 of the basis matrix (the Y vector).
+ /// </summary>
+ /// <value>Equivalent to <see cref="y"/> and array index `[1]`.</value>
public Vector3 Column1
{
get => new Vector3(Row0.y, Row1.y, Row2.y);
@@ -68,6 +108,11 @@ namespace Godot
this.Row2.y = value.z;
}
}
+
+ /// <summary>
+ /// Column 2 of the basis matrix (the Z vector).
+ /// </summary>
+ /// <value>Equivalent to <see cref="z"/> and array index `[2]`.</value>
public Vector3 Column2
{
get => new Vector3(Row0.z, Row1.z, Row2.z);
@@ -79,6 +124,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The scale of this basis.
+ /// </summary>
+ /// <value>Equivalent to the lengths of each column vector, but negative if the determinant is negative.</value>
public Vector3 Scale
{
get
@@ -86,11 +135,18 @@ namespace Godot
real_t detSign = Mathf.Sign(Determinant());
return detSign * new Vector3
(
- new Vector3(this.Row0[0], this.Row1[0], this.Row2[0]).Length(),
- new Vector3(this.Row0[1], this.Row1[1], this.Row2[1]).Length(),
- new Vector3(this.Row0[2], this.Row1[2], this.Row2[2]).Length()
+ Column0.Length(),
+ Column1.Length(),
+ Column2.Length()
);
}
+ set
+ {
+ value /= Scale; // Value becomes what's called "delta_scale" in core.
+ Column0 *= value.x;
+ Column1 *= value.y;
+ Column2 *= value.z;
+ }
}
/// <summary>
@@ -151,14 +207,15 @@ namespace Godot
}
}
- internal Quat RotationQuat()
+ public Quat RotationQuat()
{
Basis orthonormalizedBasis = Orthonormalized();
real_t det = orthonormalizedBasis.Determinant();
if (det < 0)
{
- // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
- orthonormalizedBasis = orthonormalizedBasis.Scaled(Vector3.NegOne);
+ // Ensure that the determinant is 1, such that result is a proper
+ // rotation matrix which can be represented by Euler angles.
+ orthonormalizedBasis = orthonormalizedBasis.Scaled(-Vector3.One);
}
return orthonormalizedBasis.Quat();
@@ -182,6 +239,15 @@ namespace Godot
Row2 = new Vector3(0, 0, diagonal.z);
}
+ /// <summary>
+ /// Returns the determinant of the basis matrix. If the basis is
+ /// uniformly scaled, its determinant is the square of the scale.
+ ///
+ /// A negative determinant means the basis has a negative scale.
+ /// A zero determinant means the basis isn't invertible,
+ /// and is usually considered invalid.
+ /// </summary>
+ /// <returns>The determinant of the basis matrix.</returns>
public real_t Determinant()
{
real_t cofac00 = Row1[1] * Row2[2] - Row1[2] * Row2[1];
@@ -191,6 +257,16 @@ namespace Godot
return Row0[0] * cofac00 + Row0[1] * cofac10 + Row0[2] * cofac20;
}
+ /// <summary>
+ /// Returns the basis's rotation in the form of Euler angles
+ /// (in the YXZ convention: when *decomposing*, first Z, then X, and Y last).
+ /// The returned vector contains the rotation angles in
+ /// the format (X angle, Y angle, Z angle).
+ ///
+ /// Consider using the <see cref="Basis.Quat()"/> method instead, which
+ /// returns a <see cref="Godot.Quat"/> quaternion instead of Euler angles.
+ /// </summary>
+ /// <returns>A Vector3 representing the basis rotation in Euler angles.</returns>
public Vector3 GetEuler()
{
Basis m = Orthonormalized();
@@ -223,6 +299,12 @@ namespace Godot
return euler;
}
+ /// <summary>
+ /// Get rows by index. Rows are not very useful for user code,
+ /// but are more efficient for some internal calculations.
+ /// </summary>
+ /// <param name="index">Which row.</param>
+ /// <returns>One of `Row0`, `Row1`, or `Row2`.</returns>
public Vector3 GetRow(int index)
{
switch (index)
@@ -238,6 +320,12 @@ namespace Godot
}
}
+ /// <summary>
+ /// Sets rows by index. Rows are not very useful for user code,
+ /// but are more efficient for some internal calculations.
+ /// </summary>
+ /// <param name="index">Which row.</param>
+ /// <param name="value">The vector to set the row to.</param>
public void SetRow(int index, Vector3 value)
{
switch (index)
@@ -256,16 +344,16 @@ namespace Godot
}
}
- public Vector3 GetColumn(int index)
- {
- return this[index];
- }
-
- public void SetColumn(int index, Vector3 value)
- {
- this[index] = value;
- }
-
+ /// <summary>
+ /// This function considers a discretization of rotations into
+ /// 24 points on unit sphere, lying along the vectors (x, y, z) with
+ /// each component being either -1, 0, or 1, and returns the index
+ /// of the point best representing the orientation of the object.
+ /// It is mainly used by the <see cref="GridMap"/> editor.
+ ///
+ /// For further details, refer to the Godot source code.
+ /// </summary>
+ /// <returns>The orthogonal index.</returns>
public int GetOrthogonalIndex()
{
var orth = this;
@@ -279,11 +367,17 @@ namespace Godot
real_t v = row[j];
if (v > 0.5f)
+ {
v = 1.0f;
+ }
else if (v < -0.5f)
+ {
v = -1.0f;
+ }
else
+ {
v = 0f;
+ }
row[j] = v;
@@ -294,12 +388,18 @@ namespace Godot
for (int i = 0; i < 24; i++)
{
if (orth == _orthoBases[i])
+ {
return i;
+ }
}
return 0;
}
+ /// <summary>
+ /// Returns the inverse of the matrix.
+ /// </summary>
+ /// <returns>The inverse matrix.</returns>
public Basis Inverse()
{
real_t cofac00 = Row1[1] * Row2[2] - Row1[2] * Row2[1];
@@ -309,7 +409,9 @@ namespace Godot
real_t det = Row0[0] * cofac00 + Row0[1] * cofac10 + Row0[2] * cofac20;
if (det == 0)
+ {
throw new InvalidOperationException("Matrix determinant is zero and cannot be inverted.");
+ }
real_t detInv = 1.0f / det;
@@ -328,11 +430,17 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the orthonormalized version of the basis matrix (useful to
+ /// call occasionally to avoid rounding errors for orthogonal matrices).
+ /// This performs a Gram-Schmidt orthonormalization on the basis of the matrix.
+ /// </summary>
+ /// <returns>An orthonormalized basis matrix.</returns>
public Basis Orthonormalized()
{
- Vector3 column0 = GetColumn(0);
- Vector3 column1 = GetColumn(1);
- Vector3 column2 = GetColumn(2);
+ Vector3 column0 = this[0];
+ Vector3 column1 = this[1];
+ Vector3 column2 = this[2];
column0.Normalize();
column1 = column1 - column0 * column0.Dot(column1);
@@ -343,48 +451,86 @@ namespace Godot
return new Basis(column0, column1, column2);
}
+ /// <summary>
+ /// Introduce an additional rotation around the given `axis`
+ /// by `phi` (in radians). The axis must be a normalized vector.
+ /// </summary>
+ /// <param name="axis">The axis to rotate around. Must be normalized.</param>
+ /// <param name="phi">The angle to rotate, in radians.</param>
+ /// <returns>The rotated basis matrix.</returns>
public Basis Rotated(Vector3 axis, real_t phi)
{
return new Basis(axis, phi) * this;
}
+ /// <summary>
+ /// Introduce an additional scaling specified by the given 3D scaling factor.
+ /// </summary>
+ /// <param name="scale">The scale to introduce.</param>
+ /// <returns>The scaled basis matrix.</returns>
public Basis Scaled(Vector3 scale)
{
- var b = this;
+ Basis b = this;
b.Row0 *= scale.x;
b.Row1 *= scale.y;
b.Row2 *= scale.z;
return b;
}
- public Basis Slerp(Basis target, real_t t)
+ /// <summary>
+ /// Assuming that the matrix is a proper rotation matrix, slerp performs
+ /// a spherical-linear interpolation with another rotation matrix.
+ /// </summary>
+ /// <param name="target">The destination basis for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting basis matrix of the interpolation.</returns>
+ public Basis Slerp(Basis target, real_t weight)
{
- var from = new Quat(this);
- var to = new Quat(target);
+ Quat from = new Quat(this);
+ Quat to = new Quat(target);
- var b = new Basis(from.Slerp(to, t));
- b.Row0 *= Mathf.Lerp(Row0.Length(), target.Row0.Length(), t);
- b.Row1 *= Mathf.Lerp(Row1.Length(), target.Row1.Length(), t);
- b.Row2 *= Mathf.Lerp(Row2.Length(), target.Row2.Length(), t);
+ Basis b = new Basis(from.Slerp(to, weight));
+ b.Row0 *= Mathf.Lerp(Row0.Length(), target.Row0.Length(), weight);
+ b.Row1 *= Mathf.Lerp(Row1.Length(), target.Row1.Length(), weight);
+ b.Row2 *= Mathf.Lerp(Row2.Length(), target.Row2.Length(), weight);
return b;
}
+ /// <summary>
+ /// Transposed dot product with the X axis of the matrix.
+ /// </summary>
+ /// <param name="with">A vector to calculate the dot product with.</param>
+ /// <returns>The resulting dot product.</returns>
public real_t Tdotx(Vector3 with)
{
return this.Row0[0] * with[0] + this.Row1[0] * with[1] + this.Row2[0] * with[2];
}
+ /// <summary>
+ /// Transposed dot product with the Y axis of the matrix.
+ /// </summary>
+ /// <param name="with">A vector to calculate the dot product with.</param>
+ /// <returns>The resulting dot product.</returns>
public real_t Tdoty(Vector3 with)
{
return this.Row0[1] * with[0] + this.Row1[1] * with[1] + this.Row2[1] * with[2];
}
+ /// <summary>
+ /// Transposed dot product with the Z axis of the matrix.
+ /// </summary>
+ /// <param name="with">A vector to calculate the dot product with.</param>
+ /// <returns>The resulting dot product.</returns>
public real_t Tdotz(Vector3 with)
{
return this.Row0[2] * with[0] + this.Row1[2] * with[1] + this.Row2[2] * with[2];
}
+ /// <summary>
+ /// Returns the transposed version of the basis matrix.
+ /// </summary>
+ /// <returns>The transposed basis matrix.</returns>
public Basis Transposed()
{
var tr = this;
@@ -404,6 +550,11 @@ namespace Godot
return tr;
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the basis matrix.
+ /// </summary>
+ /// <param name="v">A vector to transform.</param>
+ /// <returns>The transformed vector.</returns>
public Vector3 Xform(Vector3 v)
{
return new Vector3
@@ -414,6 +565,14 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the transposed basis matrix.
+ ///
+ /// Note: This results in a multiplication by the inverse of the
+ /// basis matrix only if it represents a rotation-reflection.
+ /// </summary>
+ /// <param name="v">A vector to inversely transform.</param>
+ /// <returns>The inversely transformed vector.</returns>
public Vector3 XformInv(Vector3 v)
{
return new Vector3
@@ -424,6 +583,12 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the basis's rotation in the form of a quaternion.
+ /// See <see cref="GetEuler()"/> if you need Euler angles, but keep in
+ /// mind that quaternions should generally be preferred to Euler angles.
+ /// </summary>
+ /// <returns>A <see cref="Godot.Quat"/> representing the basis's rotation.</returns>
public Quat Quat()
{
real_t trace = Row0[0] + Row1[1] + Row2[2];
@@ -508,11 +673,33 @@ namespace Godot
private static readonly Basis _flipY = new Basis(1, 0, 0, 0, -1, 0, 0, 0, 1);
private static readonly Basis _flipZ = new Basis(1, 0, 0, 0, 1, 0, 0, 0, -1);
+ /// <summary>
+ /// The identity basis, with no rotation or scaling applied.
+ /// This is used as a replacement for `Basis()` in GDScript.
+ /// Do not use `new Basis()` with no arguments in C#, because it sets all values to zero.
+ /// </summary>
+ /// <value>Equivalent to `new Basis(Vector3.Right, Vector3.Up, Vector3.Back)`.</value>
public static Basis Identity { get { return _identity; } }
+ /// <summary>
+ /// The basis that will flip something along the X axis when used in a transformation.
+ /// </summary>
+ /// <value>Equivalent to `new Basis(Vector3.Left, Vector3.Up, Vector3.Back)`.</value>
public static Basis FlipX { get { return _flipX; } }
+ /// <summary>
+ /// The basis that will flip something along the Y axis when used in a transformation.
+ /// </summary>
+ /// <value>Equivalent to `new Basis(Vector3.Right, Vector3.Down, Vector3.Back)`.</value>
public static Basis FlipY { get { return _flipY; } }
+ /// <summary>
+ /// The basis that will flip something along the Z axis when used in a transformation.
+ /// </summary>
+ /// <value>Equivalent to `new Basis(Vector3.Right, Vector3.Up, Vector3.Forward)`.</value>
public static Basis FlipZ { get { return _flipZ; } }
+ /// <summary>
+ /// Constructs a pure rotation basis matrix from the given quaternion.
+ /// </summary>
+ /// <param name="quat">The quaternion to create the basis from.</param>
public Basis(Quat quat)
{
real_t s = 2.0f / quat.LengthSquared;
@@ -535,26 +722,41 @@ namespace Godot
Row2 = new Vector3(xz - wy, yz + wx, 1.0f - (xx + yy));
}
- public Basis(Vector3 euler)
+ /// <summary>
+ /// Constructs a pure rotation basis matrix from the given Euler angles
+ /// (in the YXZ convention: when *composing*, first Y, then X, and Z last),
+ /// given in the vector format as (X angle, Y angle, Z angle).
+ ///
+ /// Consider using the <see cref="Basis(Quat)"/> constructor instead, which
+ /// uses a <see cref="Godot.Quat"/> quaternion instead of Euler angles.
+ /// </summary>
+ /// <param name="eulerYXZ">The Euler angles to create the basis from.</param>
+ public Basis(Vector3 eulerYXZ)
{
real_t c;
real_t s;
- c = Mathf.Cos(euler.x);
- s = Mathf.Sin(euler.x);
+ c = Mathf.Cos(eulerYXZ.x);
+ s = Mathf.Sin(eulerYXZ.x);
var xmat = new Basis(1, 0, 0, 0, c, -s, 0, s, c);
- c = Mathf.Cos(euler.y);
- s = Mathf.Sin(euler.y);
+ c = Mathf.Cos(eulerYXZ.y);
+ s = Mathf.Sin(eulerYXZ.y);
var ymat = new Basis(c, 0, s, 0, 1, 0, -s, 0, c);
- c = Mathf.Cos(euler.z);
- s = Mathf.Sin(euler.z);
+ c = Mathf.Cos(eulerYXZ.z);
+ s = Mathf.Sin(eulerYXZ.z);
var zmat = new Basis(c, -s, 0, s, c, 0, 0, 0, 1);
this = ymat * xmat * zmat;
}
+ /// <summary>
+ /// Constructs a pure rotation basis matrix, rotated around the given `axis`
+ /// by `phi` (in radians). The axis must be a normalized vector.
+ /// </summary>
+ /// <param name="axis">The axis to rotate around. Must be normalized.</param>
+ /// <param name="phi">The angle to rotate, in radians.</param>
public Basis(Vector3 axis, real_t phi)
{
Vector3 axisSq = new Vector3(axis.x * axis.x, axis.y * axis.y, axis.z * axis.z);
@@ -582,6 +784,12 @@ namespace Godot
Row2.y = xyzt + zyxs;
}
+ /// <summary>
+ /// Constructs a basis matrix from 3 axis vectors (matrix columns).
+ /// </summary>
+ /// <param name="column0">The X vector, or Column0.</param>
+ /// <param name="column1">The Y vector, or Column1.</param>
+ /// <param name="column2">The Z vector, or Column2.</param>
public Basis(Vector3 column0, Vector3 column1, Vector3 column2)
{
Row0 = new Vector3(column0.x, column1.x, column2.x);
@@ -637,6 +845,12 @@ namespace Godot
return Row0.Equals(other.Row0) && Row1.Equals(other.Row1) && Row2.Equals(other.Row2);
}
+ /// <summary>
+ /// Returns true if this basis and `other` are approximately equal, by running
+ /// <see cref="Vector3.IsEqualApprox(Vector3)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other basis to compare.</param>
+ /// <returns>Whether or not the matrices are approximately equal.</returns>
public bool IsEqualApprox(Basis other)
{
return Row0.IsEqualApprox(other.Row0) && Row1.IsEqualApprox(other.Row1) && Row2.IsEqualApprox(other.Row2);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
index 6030b72a44..90141928ca 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs
@@ -3,15 +3,44 @@ using System.Runtime.InteropServices;
namespace Godot
{
+ /// <summary>
+ /// A color represented by red, green, blue, and alpha (RGBA) components.
+ /// The alpha component is often used for transparency.
+ /// Values are in floating-point and usually range from 0 to 1.
+ /// Some properties (such as CanvasItem.modulate) may accept values
+ /// greater than 1 (overbright or HDR colors).
+ ///
+ /// If you want to supply values in a range of 0 to 255, you should use
+ /// <see cref="Color8"/> and the `r8`/`g8`/`b8`/`a8` properties.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Color : IEquatable<Color>
{
+ /// <summary>
+ /// The color's red component, typically on the range of 0 to 1.
+ /// </summary>
public float r;
+
+ /// <summary>
+ /// The color's green component, typically on the range of 0 to 1.
+ /// </summary>
public float g;
+
+ /// <summary>
+ /// The color's blue component, typically on the range of 0 to 1.
+ /// </summary>
public float b;
+
+ /// <summary>
+ /// The color's alpha (transparency) component, typically on the range of 0 to 1.
+ /// </summary>
public float a;
+ /// <summary>
+ /// Wrapper for <see cref="r"/> that uses the range 0 to 255 instead of 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value>
public int r8
{
get
@@ -24,6 +53,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// Wrapper for <see cref="g"/> that uses the range 0 to 255 instead of 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value>
public int g8
{
get
@@ -36,6 +69,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// Wrapper for <see cref="b"/> that uses the range 0 to 255 instead of 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value>
public int b8
{
get
@@ -48,6 +85,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// Wrapper for <see cref="a"/> that uses the range 0 to 255 instead of 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to multiplying by 255 and rounding. Setting is equivalent to dividing by 255.</value>
public int a8
{
get
@@ -60,6 +101,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The HSV hue of this color, on the range 0 to 1.
+ /// </summary>
+ /// <value>Getting is a long process, refer to the source code for details. Setting uses <see cref="FromHsv"/>.</value>
public float h
{
get
@@ -70,21 +115,31 @@ namespace Godot
float delta = max - min;
if (delta == 0)
+ {
return 0;
+ }
float h;
if (r == max)
+ {
h = (g - b) / delta; // Between yellow & magenta
+ }
else if (g == max)
+ {
h = 2 + (b - r) / delta; // Between cyan & yellow
+ }
else
+ {
h = 4 + (r - g) / delta; // Between magenta & cyan
+ }
h /= 6.0f;
if (h < 0)
+ {
h += 1.0f;
+ }
return h;
}
@@ -94,6 +149,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The HSV saturation of this color, on the range 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to the ratio between the min and max RGB value. Setting uses <see cref="FromHsv"/>.</value>
public float s
{
get
@@ -103,7 +162,7 @@ namespace Godot
float delta = max - min;
- return max != 0 ? delta / max : 0;
+ return max == 0 ? 0 : delta / max;
}
set
{
@@ -111,6 +170,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The HSV value (brightness) of this color, on the range 0 to 1.
+ /// </summary>
+ /// <value>Getting is equivalent to using `Max()` on the RGB components. Setting uses <see cref="FromHsv"/>.</value>
public float v
{
get
@@ -123,25 +186,10 @@ namespace Godot
}
}
- public static Color ColorN(string name, float alpha = 1f)
- {
- name = name.Replace(" ", String.Empty);
- name = name.Replace("-", String.Empty);
- name = name.Replace("_", String.Empty);
- name = name.Replace("'", String.Empty);
- name = name.Replace(".", String.Empty);
- name = name.ToLower();
-
- if (!Colors.namedColors.ContainsKey(name))
- {
- throw new ArgumentOutOfRangeException($"Invalid Color Name: {name}");
- }
-
- Color color = Colors.namedColors[name];
- color.a = alpha;
- return color;
- }
-
+ /// <summary>
+ /// Access color components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.r`, `[1]` is equivalent to `.g`, `[2]` is equivalent to `.b`, `[3]` is equivalent to `.a`.</value>
public float this[int index]
{
get
@@ -182,73 +230,13 @@ namespace Godot
}
}
- public void ToHsv(out float hue, out float saturation, out float value)
- {
- float max = (float)Mathf.Max(r, Mathf.Max(g, b));
- float min = (float)Mathf.Min(r, Mathf.Min(g, b));
-
- float delta = max - min;
-
- if (delta == 0)
- {
- hue = 0;
- }
- else
- {
- if (r == max)
- hue = (g - b) / delta; // Between yellow & magenta
- else if (g == max)
- hue = 2 + (b - r) / delta; // Between cyan & yellow
- else
- hue = 4 + (r - g) / delta; // Between magenta & cyan
-
- hue /= 6.0f;
-
- if (hue < 0)
- hue += 1.0f;
- }
-
- saturation = max == 0 ? 0 : 1f - 1f * min / max;
- value = max;
- }
-
- public static Color FromHsv(float hue, float saturation, float value, float alpha = 1.0f)
- {
- if (saturation == 0)
- {
- // acp_hromatic (grey)
- return new Color(value, value, value, alpha);
- }
-
- int i;
- float f, p, q, t;
-
- hue *= 6.0f;
- hue %= 6f;
- i = (int)hue;
-
- f = hue - i;
- p = value * (1 - saturation);
- q = value * (1 - saturation * f);
- t = value * (1 - saturation * (1 - f));
-
- switch (i)
- {
- case 0: // Red is the dominant color
- return new Color(value, t, p, alpha);
- case 1: // Green is the dominant color
- return new Color(q, value, p, alpha);
- case 2:
- return new Color(p, value, t, alpha);
- case 3: // Blue is the dominant color
- return new Color(p, q, value, alpha);
- case 4:
- return new Color(t, p, value, alpha);
- default: // (5) Red is the dominant color
- return new Color(value, p, q, alpha);
- }
- }
-
+ /// <summary>
+ /// Returns a new color resulting from blending this color over another.
+ /// If the color is opaque, the result is also opaque.
+ /// The second color may have a range of alpha values.
+ /// </summary>
+ /// <param name="over">The color to blend over.</param>
+ /// <returns>This color blended over `over`.</returns>
public Color Blend(Color over)
{
Color res;
@@ -268,16 +256,12 @@ namespace Godot
return res;
}
- public Color Contrasted()
- {
- return new Color(
- (r + 0.5f) % 1.0f,
- (g + 0.5f) % 1.0f,
- (b + 0.5f) % 1.0f,
- a
- );
- }
-
+ /// <summary>
+ /// Returns a new color resulting from making this color darker
+ /// by the specified ratio (on the range of 0 to 1).
+ /// </summary>
+ /// <param name="amount">The ratio to darken by.</param>
+ /// <returns>The darkened color.</returns>
public Color Darkened(float amount)
{
Color res = this;
@@ -287,6 +271,10 @@ namespace Godot
return res;
}
+ /// <summary>
+ /// Returns the inverted color: `(1 - r, 1 - g, 1 - b, a)`.
+ /// </summary>
+ /// <returns>The inverted color.</returns>
public Color Inverted()
{
return new Color(
@@ -297,6 +285,12 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns a new color resulting from making this color lighter
+ /// by the specified ratio (on the range of 0 to 1).
+ /// </summary>
+ /// <param name="amount">The ratio to lighten by.</param>
+ /// <returns>The darkened color.</returns>
public Color Lightened(float amount)
{
Color res = this;
@@ -306,6 +300,13 @@ namespace Godot
return res;
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this color and `to` by amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination color for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting color of the interpolation.</returns>
public Color Lerp(Color to, float weight)
{
return new Color
@@ -317,6 +318,13 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this color and `to` by color amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination color for interpolation.</param>
+ /// <param name="weight">A color with components on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting color of the interpolation.</returns>
public Color Lerp(Color to, Color weight)
{
return new Color
@@ -328,6 +336,12 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 32-bit integer in ABGR
+ /// format (each byte represents a color channel).
+ /// ABGR is the reversed version of the default format.
+ /// </summary>
+ /// <returns>A uint representing this color in ABGR32 format.</returns>
public uint ToAbgr32()
{
uint c = (byte)Math.Round(a * 255);
@@ -341,6 +355,12 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 64-bit integer in ABGR
+ /// format (each word represents a color channel).
+ /// ABGR is the reversed version of the default format.
+ /// </summary>
+ /// <returns>A ulong representing this color in ABGR64 format.</returns>
public ulong ToAbgr64()
{
ulong c = (ushort)Math.Round(a * 65535);
@@ -354,6 +374,12 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 32-bit integer in ARGB
+ /// format (each byte represents a color channel).
+ /// ARGB is more compatible with DirectX, but not used much in Godot.
+ /// </summary>
+ /// <returns>A uint representing this color in ARGB32 format.</returns>
public uint ToArgb32()
{
uint c = (byte)Math.Round(a * 255);
@@ -367,6 +393,12 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 64-bit integer in ARGB
+ /// format (each word represents a color channel).
+ /// ARGB is more compatible with DirectX, but not used much in Godot.
+ /// </summary>
+ /// <returns>A ulong representing this color in ARGB64 format.</returns>
public ulong ToArgb64()
{
ulong c = (ushort)Math.Round(a * 65535);
@@ -380,6 +412,12 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 32-bit integer in RGBA
+ /// format (each byte represents a color channel).
+ /// RGBA is Godot's default and recommended format.
+ /// </summary>
+ /// <returns>A uint representing this color in RGBA32 format.</returns>
public uint ToRgba32()
{
uint c = (byte)Math.Round(r * 255);
@@ -393,6 +431,12 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color converted to an unsigned 64-bit integer in RGBA
+ /// format (each word represents a color channel).
+ /// RGBA is Godot's default and recommended format.
+ /// </summary>
+ /// <returns>A ulong representing this color in RGBA64 format.</returns>
public ulong ToRgba64()
{
ulong c = (ushort)Math.Round(r * 65535);
@@ -406,6 +450,11 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the color's HTML hexadecimal color string in RGBA format.
+ /// </summary>
+ /// <param name="includeAlpha">Whether or not to include alpha. If false, the color is RGB instead of RGBA.</param>
+ /// <returns>A string for the HTML hexadecimal representation of this color.</returns>
public string ToHtml(bool includeAlpha = true)
{
var txt = string.Empty;
@@ -415,12 +464,20 @@ namespace Godot
txt += ToHex32(b);
if (includeAlpha)
- txt = ToHex32(a) + txt;
+ {
+ txt += ToHex32(a);
+ }
return txt;
}
- // Constructors
+ /// <summary>
+ /// Constructs a color from RGBA values, typically on the range of 0 to 1.
+ /// </summary>
+ /// <param name="r">The color's red component, typically on the range of 0 to 1.</param>
+ /// <param name="g">The color's green component, typically on the range of 0 to 1.</param>
+ /// <param name="b">The color's blue component, typically on the range of 0 to 1.</param>
+ /// <param name="a">The color's alpha (transparency) value, typically on the range of 0 to 1. Default: 1.</param>
public Color(float r, float g, float b, float a = 1.0f)
{
this.r = r;
@@ -429,6 +486,11 @@ namespace Godot
this.a = a;
}
+ /// <summary>
+ /// Constructs a color from an existing color and an alpha value.
+ /// </summary>
+ /// <param name="c">The color to construct from. Only its RGB values are used.</param>
+ /// <param name="a">The color's alpha (transparency) value, typically on the range of 0 to 1. Default: 1.</param>
public Color(Color c, float a = 1.0f)
{
r = c.r;
@@ -437,6 +499,11 @@ namespace Godot
this.a = a;
}
+ /// <summary>
+ /// Constructs a color from an unsigned 32-bit integer in RGBA format
+ /// (each byte represents a color channel).
+ /// </summary>
+ /// <param name="rgba">The uint representing the color.</param>
public Color(uint rgba)
{
a = (rgba & 0xFF) / 255.0f;
@@ -448,6 +515,11 @@ namespace Godot
r = (rgba & 0xFF) / 255.0f;
}
+ /// <summary>
+ /// Constructs a color from an unsigned 64-bit integer in RGBA format
+ /// (each word represents a color channel).
+ /// </summary>
+ /// <param name="rgba">The ulong representing the color.</param>
public Color(ulong rgba)
{
a = (rgba & 0xFFFF) / 65535.0f;
@@ -459,168 +531,286 @@ namespace Godot
r = (rgba & 0xFFFF) / 65535.0f;
}
- private static int ParseCol8(string str, int ofs)
+ /// <summary>
+ /// Constructs a color from the HTML hexadecimal color string in RGBA format.
+ /// </summary>
+ /// <param name="rgba">A string for the HTML hexadecimal representation of this color.</param>
+ public Color(string rgba)
{
- int ig = 0;
+ if (rgba.Length == 0)
+ {
+ r = 0f;
+ g = 0f;
+ b = 0f;
+ a = 1.0f;
+ return;
+ }
+
+ if (rgba[0] == '#')
+ {
+ rgba = rgba.Substring(1);
+ }
- for (int i = 0; i < 2; i++)
+ // If enabled, use 1 hex digit per channel instead of 2.
+ // Other sizes aren't in the HTML/CSS spec but we could add them if desired.
+ bool isShorthand = rgba.Length < 5;
+ bool alpha;
+
+ if (rgba.Length == 8)
+ {
+ alpha = true;
+ }
+ else if (rgba.Length == 6)
+ {
+ alpha = false;
+ }
+ else if (rgba.Length == 4)
+ {
+ alpha = true;
+ }
+ else if (rgba.Length == 3)
{
- int c = str[i + ofs];
- int v;
+ alpha = false;
+ }
+ else
+ {
+ throw new ArgumentOutOfRangeException("Invalid color code. Length is " + rgba.Length + " but a length of 6 or 8 is expected: " + rgba);
+ }
- if (c >= '0' && c <= '9')
- {
- v = c - '0';
- }
- else if (c >= 'a' && c <= 'f')
- {
- v = c - 'a';
- v += 10;
- }
- else if (c >= 'A' && c <= 'F')
+ a = 1.0f;
+ if (isShorthand)
+ {
+ r = ParseCol4(rgba, 0) / 15f;
+ g = ParseCol4(rgba, 1) / 15f;
+ b = ParseCol4(rgba, 2) / 15f;
+ if (alpha)
{
- v = c - 'A';
- v += 10;
+ a = ParseCol4(rgba, 3) / 15f;
}
- else
+ }
+ else
+ {
+ r = ParseCol8(rgba, 0) / 255f;
+ g = ParseCol8(rgba, 2) / 255f;
+ b = ParseCol8(rgba, 4) / 255f;
+ if (alpha)
{
- return -1;
+ a = ParseCol8(rgba, 6) / 255f;
}
+ }
- if (i == 0)
- ig += v * 16;
- else
- ig += v;
+ if (r < 0)
+ {
+ throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba);
+ }
+
+ if (g < 0)
+ {
+ throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba);
}
- return ig;
+ if (b < 0)
+ {
+ throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba);
+ }
+
+ if (a < 0)
+ {
+ throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba);
+ }
}
- private String ToHex32(float val)
+ /// <summary>
+ /// Returns a color constructed from integer red, green, blue, and alpha channels.
+ /// Each channel should have 8 bits of information ranging from 0 to 255.
+ /// </summary>
+ /// <param name="r8">The red component represented on the range of 0 to 255.</param>
+ /// <param name="g8">The green component represented on the range of 0 to 255.</param>
+ /// <param name="b8">The blue component represented on the range of 0 to 255.</param>
+ /// <param name="a8">The alpha (transparency) component represented on the range of 0 to 255.</param>
+ /// <returns>The constructed color.</returns>
+ public static Color Color8(byte r8, byte g8, byte b8, byte a8 = 255)
{
- int v = Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255));
+ return new Color(r8 / 255f, g8 / 255f, b8 / 255f, a8 / 255f);
+ }
- var ret = string.Empty;
+ /// <summary>
+ /// Returns a color according to the standardized name, with the
+ /// specified alpha value. Supported color names are the same as
+ /// the constants defined in <see cref="Colors"/>.
+ /// </summary>
+ /// <param name="name">The name of the color.</param>
+ /// <param name="alpha">The alpha (transparency) component represented on the range of 0 to 1. Default: 1.</param>
+ /// <returns>The constructed color.</returns>
+ public static Color ColorN(string name, float alpha = 1f)
+ {
+ name = name.Replace(" ", String.Empty);
+ name = name.Replace("-", String.Empty);
+ name = name.Replace("_", String.Empty);
+ name = name.Replace("'", String.Empty);
+ name = name.Replace(".", String.Empty);
+ name = name.ToLower();
- for (int i = 0; i < 2; i++)
+ if (!Colors.namedColors.ContainsKey(name))
{
- char c;
- int lv = v & 0xF;
-
- if (lv < 10)
- c = (char)('0' + lv);
- else
- c = (char)('a' + lv - 10);
-
- v >>= 4;
- ret = c + ret;
+ throw new ArgumentOutOfRangeException($"Invalid Color Name: {name}");
}
- return ret;
+ Color color = Colors.namedColors[name];
+ color.a = alpha;
+ return color;
}
- internal static bool HtmlIsValid(string color)
+ /// <summary>
+ /// Constructs a color from an HSV profile, with values on the
+ /// range of 0 to 1. This is equivalent to using each of
+ /// the `h`/`s`/`v` properties, but much more efficient.
+ /// </summary>
+ /// <param name="hue">The HSV hue, typically on the range of 0 to 1.</param>
+ /// <param name="saturation">The HSV saturation, typically on the range of 0 to 1.</param>
+ /// <param name="value">The HSV value (brightness), typically on the range of 0 to 1.</param>
+ /// <param name="alpha">The alpha (transparency) value, typically on the range of 0 to 1.</param>
+ /// <returns>The constructed color.</returns>
+ public static Color FromHsv(float hue, float saturation, float value, float alpha = 1.0f)
{
- if (color.Length == 0)
- return false;
+ if (saturation == 0)
+ {
+ // acp_hromatic (grey)
+ return new Color(value, value, value, alpha);
+ }
- if (color[0] == '#')
- color = color.Substring(1, color.Length - 1);
+ int i;
+ float f, p, q, t;
- bool alpha;
+ hue *= 6.0f;
+ hue %= 6f;
+ i = (int)hue;
+
+ f = hue - i;
+ p = value * (1 - saturation);
+ q = value * (1 - saturation * f);
+ t = value * (1 - saturation * (1 - f));
- switch (color.Length)
+ switch (i)
{
- case 8:
- alpha = true;
- break;
- case 6:
- alpha = false;
- break;
- default:
- return false;
+ case 0: // Red is the dominant color
+ return new Color(value, t, p, alpha);
+ case 1: // Green is the dominant color
+ return new Color(q, value, p, alpha);
+ case 2:
+ return new Color(p, value, t, alpha);
+ case 3: // Blue is the dominant color
+ return new Color(p, q, value, alpha);
+ case 4:
+ return new Color(t, p, value, alpha);
+ default: // (5) Red is the dominant color
+ return new Color(value, p, q, alpha);
}
+ }
+
+ /// <summary>
+ /// Converts a color to HSV values. This is equivalent to using each of
+ /// the `h`/`s`/`v` properties, but much more efficient.
+ /// </summary>
+ /// <param name="hue">Output parameter for the HSV hue.</param>
+ /// <param name="saturation">Output parameter for the HSV saturation.</param>
+ /// <param name="value">Output parameter for the HSV value.</param>
+ public void ToHsv(out float hue, out float saturation, out float value)
+ {
+ float max = (float)Mathf.Max(r, Mathf.Max(g, b));
+ float min = (float)Mathf.Min(r, Mathf.Min(g, b));
- if (alpha)
+ float delta = max - min;
+
+ if (delta == 0)
{
- if (ParseCol8(color, 0) < 0)
- return false;
+ hue = 0;
}
+ else
+ {
+ if (r == max)
+ {
+ hue = (g - b) / delta; // Between yellow & magenta
+ }
+ else if (g == max)
+ {
+ hue = 2 + (b - r) / delta; // Between cyan & yellow
+ }
+ else
+ {
+ hue = 4 + (r - g) / delta; // Between magenta & cyan
+ }
- int from = alpha ? 2 : 0;
+ hue /= 6.0f;
- if (ParseCol8(color, from + 0) < 0)
- return false;
- if (ParseCol8(color, from + 2) < 0)
- return false;
- if (ParseCol8(color, from + 4) < 0)
- return false;
+ if (hue < 0)
+ {
+ hue += 1.0f;
+ }
+ }
- return true;
+ saturation = max == 0 ? 0 : 1f - 1f * min / max;
+ value = max;
}
- public static Color Color8(byte r8, byte g8, byte b8, byte a8 = 255)
+ private static int ParseCol4(string str, int ofs)
{
- return new Color(r8 / 255f, g8 / 255f, b8 / 255f, a8 / 255f);
- }
+ char character = str[ofs];
- public Color(string rgba)
- {
- if (rgba.Length == 0)
+ if (character >= '0' && character <= '9')
{
- r = 0f;
- g = 0f;
- b = 0f;
- a = 1.0f;
- return;
+ return character - '0';
}
-
- if (rgba[0] == '#')
- rgba = rgba.Substring(1);
-
- bool alpha;
-
- if (rgba.Length == 8)
+ else if (character >= 'a' && character <= 'f')
{
- alpha = true;
+ return character + (10 - 'a');
}
- else if (rgba.Length == 6)
+ else if (character >= 'A' && character <= 'F')
{
- alpha = false;
+ return character + (10 - 'A');
}
- else
+ return -1;
+ }
+
+ private static int ParseCol8(string str, int ofs)
+ {
+ return ParseCol4(str, ofs) * 16 + ParseCol4(str, ofs + 1);
+ }
+
+ private string ToHex32(float val)
+ {
+ byte b = (byte)Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255));
+ return b.HexEncode();
+ }
+
+ internal static bool HtmlIsValid(string color)
+ {
+ if (color.Length == 0)
{
- throw new ArgumentOutOfRangeException("Invalid color code. Length is " + rgba.Length + " but a length of 6 or 8 is expected: " + rgba);
+ return false;
}
- if (alpha)
+ if (color[0] == '#')
{
- a = ParseCol8(rgba, 0) / 255f;
-
- if (a < 0)
- throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba);
+ color = color.Substring(1);
}
- else
+
+ // Check if the amount of hex digits is valid.
+ int len = color.Length;
+ if (!(len == 3 || len == 4 || len == 6 || len == 8))
{
- a = 1.0f;
+ return false;
}
- int from = alpha ? 2 : 0;
-
- r = ParseCol8(rgba, from + 0) / 255f;
-
- if (r < 0)
- throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba);
-
- g = ParseCol8(rgba, from + 2) / 255f;
-
- if (g < 0)
- throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba);
-
- b = ParseCol8(rgba, from + 4) / 255f;
+ // Check if each hex digit is valid.
+ for (int i = 0; i < len; i++) {
+ if (ParseCol4(color, i) == -1)
+ {
+ return false;
+ }
+ }
- if (b < 0)
- throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba);
+ return true;
}
public static Color operator +(Color left, Color right)
@@ -708,13 +898,13 @@ namespace Godot
if (Mathf.IsEqualApprox(left.g, right.g))
{
if (Mathf.IsEqualApprox(left.b, right.b))
+ {
return left.a < right.a;
+ }
return left.b < right.b;
}
-
return left.g < right.g;
}
-
return left.r < right.r;
}
@@ -725,13 +915,13 @@ namespace Godot
if (Mathf.IsEqualApprox(left.g, right.g))
{
if (Mathf.IsEqualApprox(left.b, right.b))
+ {
return left.a > right.a;
+ }
return left.b > right.b;
}
-
return left.g > right.g;
}
-
return left.r > right.r;
}
@@ -750,6 +940,12 @@ namespace Godot
return r == other.r && g == other.g && b == other.b && a == other.a;
}
+ /// <summary>
+ /// Returns true if this color and `other` are approximately equal, by running
+ /// <see cref="Godot.Mathf.IsEqualApprox(float, float)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other color to compare.</param>
+ /// <returns>Whether or not the colors are approximately equal.</returns>
public bool IsEqualApprox(Color other)
{
return Mathf.IsEqualApprox(r, other.r) && Mathf.IsEqualApprox(g, other.g) && Mathf.IsEqualApprox(b, other.b) && Mathf.IsEqualApprox(a, other.a);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
index f41f5e9fc8..d05a0414aa 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs
@@ -3,6 +3,10 @@ using System.Collections.Generic;
namespace Godot
{
+ /// <summary>
+ /// This class contains color constants created from standardized color names.
+ /// The standardized color set is based on the X11 and .NET color names.
+ /// </summary>
public static class Colors
{
// Color names and values are derived from core/color_names.inc
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs
new file mode 100644
index 0000000000..20b11a48dd
--- /dev/null
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/SceneTreeExtensions.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Runtime.CompilerServices;
+using Godot.Collections;
+
+namespace Godot
+{
+ public partial class SceneTree
+ {
+ public Array<T> GetNodesInGroup<T>(StringName group) where T : class
+ {
+ return new Array<T>(godot_icall_SceneTree_get_nodes_in_group_Generic(Object.GetPtr(this), StringName.GetPtr(group), typeof(T)));
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern static IntPtr godot_icall_SceneTree_get_nodes_in_group_Generic(IntPtr obj, IntPtr group, Type elemType);
+ }
+}
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
index 9384da0e48..6699c5992c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs
@@ -39,14 +39,6 @@ namespace Godot
return val * sgn;
}
- public static FuncRef FuncRef(Object instance, StringName funcName)
- {
- var ret = new FuncRef();
- ret.SetInstance(instance);
- ret.SetFunction(funcName);
- return ret;
- }
-
public static int Hash(object var)
{
return godot_icall_GD_hash(var);
@@ -84,7 +76,7 @@ namespace Godot
public static void Print(params object[] what)
{
- godot_icall_GD_print(Array.ConvertAll(what, x => x?.ToString()));
+ godot_icall_GD_print(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null"));
}
public static void PrintStack()
@@ -94,22 +86,22 @@ namespace Godot
public static void PrintErr(params object[] what)
{
- godot_icall_GD_printerr(Array.ConvertAll(what, x => x?.ToString()));
+ godot_icall_GD_printerr(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null"));
}
public static void PrintRaw(params object[] what)
{
- godot_icall_GD_printraw(Array.ConvertAll(what, x => x?.ToString()));
+ godot_icall_GD_printraw(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null"));
}
public static void PrintS(params object[] what)
{
- godot_icall_GD_prints(Array.ConvertAll(what, x => x?.ToString()));
+ godot_icall_GD_prints(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null"));
}
public static void PrintT(params object[] what)
{
- godot_icall_GD_printt(Array.ConvertAll(what, x => x?.ToString()));
+ godot_icall_GD_printt(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null"));
}
public static float Randf()
@@ -129,7 +121,12 @@ namespace Godot
public static double RandRange(double from, double to)
{
- return godot_icall_GD_rand_range(from, to);
+ return godot_icall_GD_randf_range(from, to);
+ }
+
+ public static int RandRange(int from, int to)
+ {
+ return godot_icall_GD_randi_range(from, to);
}
public static uint RandSeed(ulong seed, out ulong newSeed)
@@ -238,9 +235,11 @@ namespace Godot
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static void godot_icall_GD_randomize();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern static double godot_icall_GD_randf_range(double from, double to);
[MethodImpl(MethodImplOptions.InternalCall)]
- internal extern static double godot_icall_GD_rand_range(double from, double to);
+ internal extern static int godot_icall_GD_randi_range(int from, int to);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static uint godot_icall_GD_rand_seed(ulong seed, out ulong newSeed);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
index 4f7aa99df8..c3f372d415 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs
@@ -11,79 +11,185 @@ namespace Godot
{
// Define constants with Decimal precision and cast down to double or float.
+ /// <summary>
+ /// The circle constant, the circumference of the unit circle in radians.
+ /// </summary>
public const real_t Tau = (real_t) 6.2831853071795864769252867666M; // 6.2831855f and 6.28318530717959
+
+ /// <summary>
+ /// Constant that represents how many times the diameter of a circle
+ /// fits around its perimeter. This is equivalent to `Mathf.Tau / 2`.
+ /// </summary>
public const real_t Pi = (real_t) 3.1415926535897932384626433833M; // 3.1415927f and 3.14159265358979
+
+ /// <summary>
+ /// Positive infinity. For negative infinity, use `-Mathf.Inf`.
+ /// </summary>
public const real_t Inf = real_t.PositiveInfinity;
+
+ /// <summary>
+ /// "Not a Number", an invalid value. `NaN` has special properties, including
+ /// that it is not equal to itself. It is output by some invalid operations,
+ /// such as dividing zero by zero.
+ /// </summary>
public const real_t NaN = real_t.NaN;
private const real_t Deg2RadConst = (real_t) 0.0174532925199432957692369077M; // 0.0174532924f and 0.0174532925199433
private const real_t Rad2DegConst = (real_t) 57.295779513082320876798154814M; // 57.29578f and 57.2957795130823
+ /// <summary>
+ /// Returns the absolute value of `s` (i.e. positive value).
+ /// </summary>
+ /// <param name="s">The input number.</param>
+ /// <returns>The absolute value of `s`.</returns>
public static int Abs(int s)
{
return Math.Abs(s);
}
+ /// <summary>
+ /// Returns the absolute value of `s` (i.e. positive value).
+ /// </summary>
+ /// <param name="s">The input number.</param>
+ /// <returns>The absolute value of `s`.</returns>
public static real_t Abs(real_t s)
{
return Math.Abs(s);
}
+ /// <summary>
+ /// Returns the arc cosine of `s` in radians. Use to get the angle of cosine s.
+ /// </summary>
+ /// <param name="s">The input cosine value. Must be on the range of -1.0 to 1.0.</param>
+ /// <returns>An angle that would result in the given cosine value. On the range `0` to `Tau/2`.</returns>
public static real_t Acos(real_t s)
{
return (real_t)Math.Acos(s);
}
+ /// <summary>
+ /// Returns the arc sine of `s` in radians. Use to get the angle of sine s.
+ /// </summary>
+ /// <param name="s">The input sine value. Must be on the range of -1.0 to 1.0.</param>
+ /// <returns>An angle that would result in the given sine value. On the range `-Tau/4` to `Tau/4`.</returns>
public static real_t Asin(real_t s)
{
return (real_t)Math.Asin(s);
}
+ /// <summary>
+ /// Returns the arc tangent of `s` in radians. Use to get the angle of tangent s.
+ ///
+ /// The method cannot know in which quadrant the angle should fall.
+ /// See <see cref="Atan2(real_t, real_t)"/> if you have both `y` and `x`.
+ /// </summary>
+ /// <param name="s">The input tangent value.</param>
+ /// <returns>An angle that would result in the given tangent value. On the range `-Tau/4` to `Tau/4`.</returns>
public static real_t Atan(real_t s)
{
return (real_t)Math.Atan(s);
}
+ /// <summary>
+ /// Returns the arc tangent of `y` and `x` in radians. Use to get the angle
+ /// of the tangent of `y/x`. To compute the value, the method takes into
+ /// account the sign of both arguments in order to determine the quadrant.
+ ///
+ /// Important note: The Y coordinate comes first, by convention.
+ /// </summary>
+ /// <param name="y">The Y coordinate of the point to find the angle to.</param>
+ /// <param name="x">The X coordinate of the point to find the angle to.</param>
+ /// <returns>An angle that would result in the given tangent value. On the range `-Tau/2` to `Tau/2`.</returns>
public static real_t Atan2(real_t y, real_t x)
{
return (real_t)Math.Atan2(y, x);
}
+ /// <summary>
+ /// 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).
+ /// </summary>
+ /// <param name="x">The input X coordinate.</param>
+ /// <param name="y">The input Y coordinate.</param>
+ /// <returns>A <see cref="Vector2"/> with X representing the distance and Y representing the angle.</returns>
public static Vector2 Cartesian2Polar(real_t x, real_t y)
{
return new Vector2(Sqrt(x * x + y * y), Atan2(y, x));
}
+ /// <summary>
+ /// Rounds `s` upward (towards positive infinity).
+ /// </summary>
+ /// <param name="s">The number to ceil.</param>
+ /// <returns>The smallest whole number that is not less than `s`.</returns>
public static real_t Ceil(real_t s)
{
return (real_t)Math.Ceiling(s);
}
+ /// <summary>
+ /// Clamps a `value` so that it is not less than `min` and not more than `max`.
+ /// </summary>
+ /// <param name="value">The value to clamp.</param>
+ /// <param name="min">The minimum allowed value.</param>
+ /// <param name="max">The maximum allowed value.</param>
+ /// <returns>The clamped value.</returns>
public static int Clamp(int value, int min, int max)
{
return value < min ? min : value > max ? max : value;
}
+ /// <summary>
+ /// Clamps a `value` so that it is not less than `min` and not more than `max`.
+ /// </summary>
+ /// <param name="value">The value to clamp.</param>
+ /// <param name="min">The minimum allowed value.</param>
+ /// <param name="max">The maximum allowed value.</param>
+ /// <returns>The clamped value.</returns>
public static real_t Clamp(real_t value, real_t min, real_t max)
{
return value < min ? min : value > max ? max : value;
}
+ /// <summary>
+ /// Returns the cosine of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The cosine of that angle.</returns>
public static real_t Cos(real_t s)
{
return (real_t)Math.Cos(s);
}
+ /// <summary>
+ /// Returns the hyperbolic cosine of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The hyperbolic cosine of that angle.</returns>
public static real_t Cosh(real_t s)
{
return (real_t)Math.Cosh(s);
}
+ /// <summary>
+ /// Converts an angle expressed in degrees to radians.
+ /// </summary>
+ /// <param name="deg">An angle expressed in degrees.</param>
+ /// <returns>The same angle expressed in radians.</returns>
public static real_t Deg2Rad(real_t deg)
{
return deg * Deg2RadConst;
}
+ /// <summary>
+ /// Easing function, based on exponent. The curve values are:
+ /// `0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out.
+ /// Negative values are in-out/out-in.
+ /// </summary>
+ /// <param name="s">The value to ease.</param>
+ /// <param name="curve">`0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out.</param>
+ /// <returns>The eased value.</returns>
public static real_t Ease(real_t s, real_t curve)
{
if (s < 0f)
@@ -118,21 +224,47 @@ namespace Godot
return 0f;
}
+ /// <summary>
+ /// The natural exponential function. It raises the mathematical
+ /// constant `e` to the power of `s` and returns it.
+ /// </summary>
+ /// <param name="s">The exponent to raise `e` to.</param>
+ /// <returns>`e` raised to the power of `s`.</returns>
public static real_t Exp(real_t s)
{
return (real_t)Math.Exp(s);
}
+ /// <summary>
+ /// Rounds `s` downward (towards negative infinity).
+ /// </summary>
+ /// <param name="s">The number to floor.</param>
+ /// <returns>The largest whole number that is not more than `s`.</returns>
public static real_t Floor(real_t s)
{
return (real_t)Math.Floor(s);
}
+ /// <summary>
+ /// Returns a normalized value considering the given range.
+ /// This is the opposite of <see cref="Lerp(real_t, real_t, real_t)"/>.
+ /// </summary>
+ /// <param name="from">The interpolated value.</param>
+ /// <param name="to">The destination value for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting value of the inverse interpolation.</returns>
public static real_t InverseLerp(real_t from, real_t to, real_t weight)
{
return (weight - from) / (to - from);
}
+ /// <summary>
+ /// Returns true if `a` and `b` are approximately equal to each other.
+ /// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <returns>A bool for whether or not the two values are approximately equal.</returns>
public static bool IsEqualApprox(real_t a, real_t b)
{
// Check for exact equality first, required to handle "infinity" values.
@@ -149,26 +281,62 @@ namespace Godot
return Abs(a - b) < tolerance;
}
+ /// <summary>
+ /// Returns whether `s` is an infinity value (either positive infinity or negative infinity).
+ /// </summary>
+ /// <param name="s">The value to check.</param>
+ /// <returns>A bool for whether or not the value is an infinity value.</returns>
public static bool IsInf(real_t s)
{
return real_t.IsInfinity(s);
}
+ /// <summary>
+ /// Returns whether `s` is a `NaN` ("Not a Number" or invalid) value.
+ /// </summary>
+ /// <param name="s">The value to check.</param>
+ /// <returns>A bool for whether or not the value is a `NaN` value.</returns>
public static bool IsNaN(real_t s)
{
return real_t.IsNaN(s);
}
+ /// <summary>
+ /// Returns true if `s` is approximately zero.
+ /// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>.
+ ///
+ /// This method is faster than using <see cref="IsEqualApprox(real_t, real_t)"/> with one value as zero.
+ /// </summary>
+ /// <param name="s">The value to check.</param>
+ /// <returns>A bool for whether or not the value is nearly zero.</returns>
public static bool IsZeroApprox(real_t s)
{
return Abs(s) < Epsilon;
}
+ /// <summary>
+ /// Linearly interpolates between two values by a normalized value.
+ /// This is the opposite <see cref="InverseLerp(real_t, real_t, real_t)"/>.
+ /// </summary>
+ /// <param name="from">The start value for interpolation.</param>
+ /// <param name="to">The destination value for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting value of the interpolation.</returns>
public static real_t Lerp(real_t from, real_t to, real_t weight)
{
return from + (to - from) * weight;
}
+ /// <summary>
+ /// Linearly interpolates between two angles (in radians) by a normalized value.
+ ///
+ /// Similar to <see cref="Lerp(real_t, real_t, real_t)"/>,
+ /// but interpolates correctly when the angles wrap around <see cref="Tau"/>.
+ /// </summary>
+ /// <param name="from">The start angle for interpolation.</param>
+ /// <param name="to">The destination angle for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting angle of the interpolation.</returns>
public static real_t LerpAngle(real_t from, real_t to, real_t weight)
{
real_t difference = (to - from) % Mathf.Tau;
@@ -176,36 +344,81 @@ namespace Godot
return from + distance * weight;
}
+ /// <summary>
+ /// Natural logarithm. The amount of time needed to reach a certain level of continuous growth.
+ ///
+ /// Note: This is not the same as the "log" function on most calculators, which uses a base 10 logarithm.
+ /// </summary>
+ /// <param name="s">The input value.</param>
+ /// <returns>The natural log of `s`.</returns>
public static real_t Log(real_t s)
{
return (real_t)Math.Log(s);
}
+ /// <summary>
+ /// Returns the maximum of two values.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <returns>Whichever of the two values is higher.</returns>
public static int Max(int a, int b)
{
return a > b ? a : b;
}
+ /// <summary>
+ /// Returns the maximum of two values.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <returns>Whichever of the two values is higher.</returns>
public static real_t Max(real_t a, real_t b)
{
return a > b ? a : b;
}
+ /// <summary>
+ /// Returns the minimum of two values.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <returns>Whichever of the two values is lower.</returns>
public static int Min(int a, int b)
{
return a < b ? a : b;
}
+ /// <summary>
+ /// Returns the minimum of two values.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <returns>Whichever of the two values is lower.</returns>
public static real_t Min(real_t a, real_t b)
{
return a < b ? a : b;
}
+ /// <summary>
+ /// Moves `from` toward `to` by the `delta` value.
+ ///
+ /// Use a negative delta value to move away.
+ /// </summary>
+ /// <param name="from">The start value.</param>
+ /// <param name="to">The value to move towards.</param>
+ /// <param name="delta">The amount to move by.</param>
+ /// <returns>The value after moving.</returns>
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;
}
+ /// <summary>
+ /// Returns the nearest larger power of 2 for the integer `value`.
+ /// </summary>
+ /// <param name="value">The input value.</param>
+ /// <returns>The nearest larger power of 2.</returns>
public static int NearestPo2(int value)
{
value--;
@@ -218,14 +431,25 @@ namespace Godot
return value;
}
+ /// <summary>
+ /// Converts a 2D point expressed in the polar coordinate
+ /// system (a distance from the origin `r` and an angle `th`)
+ /// to the cartesian coordinate system (X and Y axis).
+ /// </summary>
+ /// <param name="r">The distance from the origin.</param>
+ /// <param name="th">The angle of the point.</param>
+ /// <returns>A <see cref="Vector2"/> representing the cartesian coordinate.</returns>
public static Vector2 Polar2Cartesian(real_t r, real_t th)
{
return new Vector2(r * Cos(th), r * Sin(th));
}
/// <summary>
- /// Performs a canonical Modulus operation, where the output is on the range [0, b).
+ /// Performs a canonical Modulus operation, where the output is on the range `[0, b)`.
/// </summary>
+ /// <param name="a">The dividend, the primary input.</param>
+ /// <param name="b">The divisor. The output is on the range `[0, b)`.</param>
+ /// <returns>The resulting output.</returns>
public static int PosMod(int a, int b)
{
int c = a % b;
@@ -237,8 +461,11 @@ namespace Godot
}
/// <summary>
- /// Performs a canonical Modulus operation, where the output is on the range [0, b).
+ /// Performs a canonical Modulus operation, where the output is on the range `[0, b)`.
/// </summary>
+ /// <param name="a">The dividend, the primary input.</param>
+ /// <param name="b">The divisor. The output is on the range `[0, b)`.</param>
+ /// <returns>The resulting output.</returns>
public static real_t PosMod(real_t a, real_t b)
{
real_t c = a % b;
@@ -249,43 +476,89 @@ namespace Godot
return c;
}
+ /// <summary>
+ /// Returns the result of `x` raised to the power of `y`.
+ /// </summary>
+ /// <param name="x">The base.</param>
+ /// <param name="y">The exponent.</param>
+ /// <returns>`x` raised to the power of `y`.</returns>
public static real_t Pow(real_t x, real_t y)
{
return (real_t)Math.Pow(x, y);
}
+ /// <summary>
+ /// Converts an angle expressed in radians to degrees.
+ /// </summary>
+ /// <param name="rad">An angle expressed in radians.</param>
+ /// <returns>The same angle expressed in degrees.</returns>
public static real_t Rad2Deg(real_t rad)
{
return rad * Rad2DegConst;
}
+ /// <summary>
+ /// Rounds `s` to the nearest whole number,
+ /// with halfway cases rounded towards the nearest multiple of two.
+ /// </summary>
+ /// <param name="s">The number to round.</param>
+ /// <returns>The rounded number.</returns>
public static real_t Round(real_t s)
{
return (real_t)Math.Round(s);
}
+ /// <summary>
+ /// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`.
+ /// </summary>
+ /// <param name="s">The input number.</param>
+ /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns>
public static int Sign(int s)
{
if (s == 0) return 0;
return s < 0 ? -1 : 1;
}
+ /// <summary>
+ /// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`.
+ /// </summary>
+ /// <param name="s">The input number.</param>
+ /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns>
public static int Sign(real_t s)
{
if (s == 0) return 0;
return s < 0 ? -1 : 1;
}
+ /// <summary>
+ /// Returns the sine of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The sine of that angle.</returns>
public static real_t Sin(real_t s)
{
return (real_t)Math.Sin(s);
}
+ /// <summary>
+ /// Returns the hyperbolic sine of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The hyperbolic sine of that angle.</returns>
public static real_t Sinh(real_t s)
{
return (real_t)Math.Sinh(s);
}
+ /// <summary>
+ /// Returns a number smoothly interpolated between `from` and `to`,
+ /// based on the `weight`. Similar to <see cref="Lerp(real_t, real_t, real_t)"/>,
+ /// but interpolates faster at the beginning and slower at the end.
+ /// </summary>
+ /// <param name="from">The start value for interpolation.</param>
+ /// <param name="to">The destination value for interpolation.</param>
+ /// <param name="weight">A value representing the amount of interpolation.</param>
+ /// <returns>The resulting value of the interpolation.</returns>
public static real_t SmoothStep(real_t from, real_t to, real_t weight)
{
if (IsEqualApprox(from, to))
@@ -296,11 +569,25 @@ namespace Godot
return x * x * (3 - 2 * x);
}
+ /// <summary>
+ /// Returns the square root of `s`, where `s` is a non-negative number.
+ ///
+ /// If you need negative inputs, use `System.Numerics.Complex`.
+ /// </summary>
+ /// <param name="s">The input number. Must not be negative.</param>
+ /// <returns>The square root of `s`.</returns>
public static real_t Sqrt(real_t s)
{
return (real_t)Math.Sqrt(s);
}
+ /// <summary>
+ /// Returns the position of the first non-zero digit, after the
+ /// decimal point. Note that the maximum return value is 10,
+ /// which is a design decision in the implementation.
+ /// </summary>
+ /// <param name="step">The input value.</param>
+ /// <returns>The position of the first non-zero digit.</returns>
public static int StepDecimals(real_t step)
{
double[] sd = new double[] {
@@ -326,32 +613,68 @@ namespace Godot
return 0;
}
- public static real_t Stepify(real_t s, real_t step)
+ /// <summary>
+ /// Snaps float value `s` to a given `step`.
+ /// This can also be used to round a floating point
+ /// number to an arbitrary number of decimals.
+ /// </summary>
+ /// <param name="s">The value to snap.</param>
+ /// <param name="step">The step size to snap to.</param>
+ /// <returns></returns>
+ public static real_t Snapped(real_t s, real_t step)
{
if (step != 0f)
{
- s = Floor(s / step + 0.5f) * step;
+ return Floor(s / step + 0.5f) * step;
}
return s;
}
+ /// <summary>
+ /// Returns the tangent of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The tangent of that angle.</returns>
public static real_t Tan(real_t s)
{
return (real_t)Math.Tan(s);
}
+ /// <summary>
+ /// Returns the hyperbolic tangent of angle `s` in radians.
+ /// </summary>
+ /// <param name="s">The angle in radians.</param>
+ /// <returns>The hyperbolic tangent of that angle.</returns>
public static real_t Tanh(real_t s)
{
return (real_t)Math.Tanh(s);
}
+ /// <summary>
+ /// Wraps `value` between `min` and `max`. Usable for creating loop-alike
+ /// behavior or infinite surfaces. If `min` is `0`, this is equivalent
+ /// to <see cref="PosMod(int, int)"/>, so prefer using that instead.
+ /// </summary>
+ /// <param name="value">The value to wrap.</param>
+ /// <param name="min">The minimum allowed value and lower bound of the range.</param>
+ /// <param name="max">The maximum allowed value and upper bound of the range.</param>
+ /// <returns>The wrapped value.</returns>
public static int Wrap(int value, int min, int max)
{
int range = max - min;
return range == 0 ? min : min + ((value - min) % range + range) % range;
}
+ /// <summary>
+ /// Wraps `value` between `min` and `max`. Usable for creating loop-alike
+ /// behavior or infinite surfaces. If `min` is `0`, this is equivalent
+ /// to <see cref="PosMod(real_t, real_t)"/>, so prefer using that instead.
+ /// </summary>
+ /// <param name="value">The value to wrap.</param>
+ /// <param name="min">The minimum allowed value and lower bound of the range.</param>
+ /// <param name="max">The maximum allowed value and upper bound of the range.</param>
+ /// <returns>The wrapped value.</returns>
public static real_t Wrap(real_t value, real_t min, real_t max)
{
real_t range = max - min;
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
index 1b7fd4906f..c2f4701b5f 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs
@@ -12,40 +12,89 @@ namespace Godot
{
// Define constants with Decimal precision and cast down to double or float.
+ /// <summary>
+ /// The natural number `e`.
+ /// </summary>
public const real_t E = (real_t) 2.7182818284590452353602874714M; // 2.7182817f and 2.718281828459045
+
+ /// <summary>
+ /// The square root of 2.
+ /// </summary>
public const real_t Sqrt2 = (real_t) 1.4142135623730950488016887242M; // 1.4142136f and 1.414213562373095
+ /// <summary>
+ /// A very small number used for float comparison with error tolerance.
+ /// 1e-06 with single-precision floats, but 1e-14 if `REAL_T_IS_DOUBLE`.
+ /// </summary>
#if REAL_T_IS_DOUBLE
public const real_t Epsilon = 1e-14; // Epsilon size should depend on the precision used.
#else
public const real_t Epsilon = 1e-06f;
#endif
+ /// <summary>
+ /// Returns the amount of digits after the decimal place.
+ /// </summary>
+ /// <param name="s">The input value.</param>
+ /// <returns>The amount of digits.</returns>
public static int DecimalCount(real_t s)
{
return DecimalCount((decimal)s);
}
+ /// <summary>
+ /// Returns the amount of digits after the decimal place.
+ /// </summary>
+ /// <param name="s">The input <see cref="System.Decimal"/> value.</param>
+ /// <returns>The amount of digits.</returns>
public static int DecimalCount(decimal s)
{
return BitConverter.GetBytes(decimal.GetBits(s)[3])[2];
}
+ /// <summary>
+ /// Rounds `s` upward (towards positive infinity).
+ ///
+ /// This is the same as <see cref="Ceil(real_t)"/>, but returns an `int`.
+ /// </summary>
+ /// <param name="s">The number to ceil.</param>
+ /// <returns>The smallest whole number that is not less than `s`.</returns>
public static int CeilToInt(real_t s)
{
return (int)Math.Ceiling(s);
}
+ /// <summary>
+ /// Rounds `s` downward (towards negative infinity).
+ ///
+ /// This is the same as <see cref="Floor(real_t)"/>, but returns an `int`.
+ /// </summary>
+ /// <param name="s">The number to floor.</param>
+ /// <returns>The largest whole number that is not more than `s`.</returns>
public static int FloorToInt(real_t s)
{
return (int)Math.Floor(s);
}
+ /// <summary>
+ ///
+ /// </summary>
+ /// <param name="s"></param>
+ /// <returns></returns>
public static int RoundToInt(real_t s)
{
return (int)Math.Round(s);
}
+ /// <summary>
+ /// Returns true if `a` and `b` are approximately equal to each other.
+ /// The comparison is done using the provided tolerance value.
+ /// If you want the tolerance to be calculated for you, use <see cref="IsEqualApprox(real_t, real_t)"/>.
+ /// </summary>
+ /// <param name="a">One of the values.</param>
+ /// <param name="b">The other value.</param>
+ /// <param name="tolerance">The pre-calculated tolerance value.</param>
+ /// <returns>A bool for whether or not the two values are equal.</returns>
public static bool IsEqualApprox(real_t a, real_t b, real_t tolerance)
{
// Check for exact equality first, required to handle "infinity" values.
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
index 42610c5ef7..48582d5ad8 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs
@@ -15,14 +15,13 @@ namespace Godot
public Object() : this(false)
{
if (ptr == IntPtr.Zero)
- {
ptr = godot_icall_Object_Ctor(this);
- }
- else
- {
- // This is called inside godot_icall_Object_Ctor, so we must call it as well in this case.
- godot_icall_Object_ConnectEventSignals(ptr);
- }
+ _InitializeGodotScriptInstanceInternals();
+ }
+
+ internal void _InitializeGodotScriptInstanceInternals()
+ {
+ godot_icall_Object_ConnectEventSignals(ptr);
}
internal Object(bool memoryOwn)
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
index 885845e3a4..2f8b5f297c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs
@@ -8,18 +8,33 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// Plane represents a normalized plane equation.
+ /// "Over" or "Above" the plane is considered the side of
+ /// the plane towards where the normal is pointing.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Plane : IEquatable<Plane>
{
private Vector3 _normal;
+ /// <summary>
+ /// The normal of the plane, which must be normalized.
+ /// In the scalar equation of the plane `ax + by + cz = d`, this is
+ /// the vector `(a, b, c)`, where `d` is the <see cref="D"/> property.
+ /// </summary>
+ /// <value>Equivalent to `x`, `y`, and `z`.</value>
public Vector3 Normal
{
get { return _normal; }
set { _normal = value; }
}
+ /// <summary>
+ /// The X component of the plane's normal vector.
+ /// </summary>
+ /// <value>Equivalent to <see cref="Normal"/>'s X value.</value>
public real_t x
{
get
@@ -32,6 +47,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The Y component of the plane's normal vector.
+ /// </summary>
+ /// <value>Equivalent to <see cref="Normal"/>'s Y value.</value>
public real_t y
{
get
@@ -44,6 +63,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The Z component of the plane's normal vector.
+ /// </summary>
+ /// <value>Equivalent to <see cref="Normal"/>'s Z value.</value>
public real_t z
{
get
@@ -56,38 +79,71 @@ namespace Godot
}
}
+ /// <summary>
+ /// The distance from the origin to the plane (in the direction of
+ /// <see cref="Normal"/>). This value is typically non-negative.
+ /// In the scalar equation of the plane `ax + by + cz = d`,
+ /// this is `d`, while the `(a, b, c)` coordinates are represented
+ /// by the <see cref="Normal"/> property.
+ /// </summary>
+ /// <value>The plane's distance from the origin.</value>
public real_t D { get; set; }
+ /// <summary>
+ /// The center of the plane, the point where the normal line intersects the plane.
+ /// </summary>
+ /// <value>Equivalent to <see cref="Normal"/> multiplied by `D`.</value>
public Vector3 Center
{
get
{
return _normal * D;
}
+ set
+ {
+ _normal = value.Normalized();
+ D = value.Length();
+ }
}
+ /// <summary>
+ /// Returns the shortest distance from this plane to the position `point`.
+ /// </summary>
+ /// <param name="point">The position to use for the calculation.</param>
+ /// <returns>The shortest distance.</returns>
public real_t DistanceTo(Vector3 point)
{
return _normal.Dot(point) - D;
}
- public Vector3 GetAnyPoint()
- {
- return _normal * D;
- }
-
+ /// <summary>
+ /// Returns true if point is inside the plane.
+ /// Comparison uses a custom minimum epsilon threshold.
+ /// </summary>
+ /// <param name="point">The point to check.</param>
+ /// <param name="epsilon">The tolerance threshold.</param>
+ /// <returns>A bool for whether or not the plane has the point.</returns>
public bool HasPoint(Vector3 point, real_t epsilon = Mathf.Epsilon)
{
real_t dist = _normal.Dot(point) - D;
return Mathf.Abs(dist) <= epsilon;
}
+ /// <summary>
+ /// Returns the intersection point of the three planes: `b`, `c`,
+ /// and this plane. If no intersection is found, `null` is returned.
+ /// </summary>
+ /// <param name="b">One of the three planes to use in the calculation.</param>
+ /// <param name="c">One of the three planes to use in the calculation.</param>
+ /// <returns>The intersection, or `null` if none is found.</returns>
public Vector3? Intersect3(Plane b, Plane c)
{
real_t denom = _normal.Cross(b._normal).Dot(c._normal);
if (Mathf.IsZeroApprox(denom))
+ {
return null;
+ }
Vector3 result = b._normal.Cross(c._normal) * D +
c._normal.Cross(_normal) * b.D +
@@ -96,54 +152,94 @@ namespace Godot
return result / denom;
}
+ /// <summary>
+ /// Returns the intersection point of a ray consisting of the
+ /// position `from` and the direction normal `dir` with this plane.
+ /// If no intersection is found, `null` is returned.
+ /// </summary>
+ /// <param name="from">The start of the ray.</param>
+ /// <param name="dir">The direction of the ray, normalized.</param>
+ /// <returns>The intersection, or `null` if none is found.</returns>
public Vector3? IntersectRay(Vector3 from, Vector3 dir)
{
real_t den = _normal.Dot(dir);
if (Mathf.IsZeroApprox(den))
+ {
return null;
+ }
real_t dist = (_normal.Dot(from) - D) / den;
// This is a ray, before the emitting pos (from) does not exist
if (dist > Mathf.Epsilon)
+ {
return null;
+ }
return from + dir * -dist;
}
+ /// <summary>
+ /// Returns the intersection point of a line segment from
+ /// position `begin` to position `end` with this plane.
+ /// If no intersection is found, `null` is returned.
+ /// </summary>
+ /// <param name="begin">The start of the line segment.</param>
+ /// <param name="end">The end of the line segment.</param>
+ /// <returns>The intersection, or `null` if none is found.</returns>
public Vector3? IntersectSegment(Vector3 begin, Vector3 end)
{
Vector3 segment = begin - end;
real_t den = _normal.Dot(segment);
if (Mathf.IsZeroApprox(den))
+ {
return null;
+ }
real_t dist = (_normal.Dot(begin) - D) / den;
// Only allow dist to be in the range of 0 to 1, with tolerance.
if (dist < -Mathf.Epsilon || dist > 1.0f + Mathf.Epsilon)
+ {
return null;
+ }
return begin + segment * -dist;
}
+ /// <summary>
+ /// Returns true if `point` is located above the plane.
+ /// </summary>
+ /// <param name="point">The point to check.</param>
+ /// <returns>A bool for whether or not the point is above the plane.</returns>
public bool IsPointOver(Vector3 point)
{
return _normal.Dot(point) > D;
}
+ /// <summary>
+ /// Returns the plane scaled to unit length.
+ /// </summary>
+ /// <returns>A normalized version of the plane.</returns>
public Plane Normalized()
{
real_t len = _normal.Length();
if (len == 0)
+ {
return new Plane(0, 0, 0, 0);
+ }
return new Plane(_normal / len, D / len);
}
+ /// <summary>
+ /// Returns the orthogonal projection of `point` into the plane.
+ /// </summary>
+ /// <param name="point">The point to project.</param>
+ /// <returns>The projected point.</returns>
public Vector3 Project(Vector3 point)
{
return point - _normal * DistanceTo(point);
@@ -154,22 +250,56 @@ namespace Godot
private static readonly Plane _planeXZ = new Plane(0, 1, 0, 0);
private static readonly Plane _planeXY = new Plane(0, 0, 1, 0);
+ /// <summary>
+ /// A plane that extends in the Y and Z axes (normal vector points +X).
+ /// </summary>
+ /// <value>Equivalent to `new Plane(1, 0, 0, 0)`.</value>
public static Plane PlaneYZ { get { return _planeYZ; } }
+
+ /// <summary>
+ /// A plane that extends in the X and Z axes (normal vector points +Y).
+ /// </summary>
+ /// <value>Equivalent to `new Plane(0, 1, 0, 0)`.</value>
public static Plane PlaneXZ { get { return _planeXZ; } }
+
+ /// <summary>
+ /// A plane that extends in the X and Y axes (normal vector points +Z).
+ /// </summary>
+ /// <value>Equivalent to `new Plane(0, 0, 1, 0)`.</value>
public static Plane PlaneXY { get { return _planeXY; } }
- // Constructors
+ /// <summary>
+ /// Constructs a plane from four values. `a`, `b` and `c` become the
+ /// components of the resulting plane's <see cref="Normal"/> vector.
+ /// `d` becomes the plane's distance from the origin.
+ /// </summary>
+ /// <param name="a">The X component of the plane's normal vector.</param>
+ /// <param name="b">The Y component of the plane's normal vector.</param>
+ /// <param name="c">The Z component of the plane's normal vector.</param>
+ /// <param name="d">The plane's distance from the origin. This value is typically non-negative.</param>
public Plane(real_t a, real_t b, real_t c, real_t d)
{
_normal = new Vector3(a, b, c);
this.D = d;
}
+
+ /// <summary>
+ /// Constructs a plane from a normal vector and the plane's distance to the origin.
+ /// </summary>
+ /// <param name="normal">The normal of the plane, must be normalized.</param>
+ /// <param name="d">The plane's distance from the origin. This value is typically non-negative.</param>
public Plane(Vector3 normal, real_t d)
{
this._normal = normal;
this.D = d;
}
+ /// <summary>
+ /// Constructs a plane from the three points, given in clockwise order.
+ /// </summary>
+ /// <param name="v1">The first point.</param>
+ /// <param name="v2">The second point.</param>
+ /// <param name="v3">The third point.</param>
public Plane(Vector3 v1, Vector3 v2, Vector3 v3)
{
_normal = (v1 - v3).Cross(v1 - v2);
@@ -207,6 +337,12 @@ namespace Godot
return _normal == other._normal && D == other.D;
}
+ /// <summary>
+ /// Returns true if this plane and `other` are approximately equal, by running
+ /// <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other plane to compare.</param>
+ /// <returns>Whether or not the planes are approximately equal.</returns>
public bool IsEqualApprox(Plane other)
{
return _normal.IsEqualApprox(other._normal) && Mathf.IsEqualApprox(D, other.D);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs
index bbc617ea6e..bd3bcb0c58 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs
@@ -8,15 +8,51 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// A unit quaternion used for representing 3D rotations.
+ /// Quaternions need to be normalized to be used for rotation.
+ ///
+ /// It is similar to Basis, which implements matrix representation of
+ /// rotations, and can be parametrized using both an axis-angle pair
+ /// or Euler angles. Basis stores rotation, scale, and shearing,
+ /// while Quat only stores rotation.
+ ///
+ /// Due to its compactness and the way it is stored in memory, certain
+ /// operations (obtaining axis-angle and performing SLERP, in particular)
+ /// are more efficient and robust against floating-point errors.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quat : IEquatable<Quat>
{
+ /// <summary>
+ /// X component of the quaternion (imaginary `i` axis part).
+ /// Quaternion components should usually not be manipulated directly.
+ /// </summary>
public real_t x;
+
+ /// <summary>
+ /// Y component of the quaternion (imaginary `j` axis part).
+ /// Quaternion components should usually not be manipulated directly.
+ /// </summary>
public real_t y;
+
+ /// <summary>
+ /// Z component of the quaternion (imaginary `k` axis part).
+ /// Quaternion components should usually not be manipulated directly.
+ /// </summary>
public real_t z;
+
+ /// <summary>
+ /// W component of the quaternion (real part).
+ /// Quaternion components should usually not be manipulated directly.
+ /// </summary>
public real_t w;
+ /// <summary>
+ /// Access quaternion components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`, `[3]` is equivalent to `.w`.</value>
public real_t this[int index]
{
get
@@ -57,103 +93,168 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns the length (magnitude) of the quaternion.
+ /// </summary>
+ /// <value>Equivalent to `Mathf.Sqrt(LengthSquared)`.</value>
public real_t Length
{
get { return Mathf.Sqrt(LengthSquared); }
}
+ /// <summary>
+ /// Returns the squared length (squared magnitude) of the quaternion.
+ /// This method runs faster than <see cref="Length"/>, so prefer it if
+ /// you need to compare quaternions or need the squared length for some formula.
+ /// </summary>
+ /// <value>Equivalent to `Dot(this)`.</value>
public real_t LengthSquared
{
get { return Dot(this); }
}
- public Quat CubicSlerp(Quat b, Quat preA, Quat postB, real_t t)
- {
- real_t t2 = (1.0f - t) * t * 2f;
- Quat sp = Slerp(b, t);
- Quat sq = preA.Slerpni(postB, t);
+ /// <summary>
+ /// Performs a cubic spherical interpolation between quaternions `preA`,
+ /// this vector, `b`, and `postB`, by the given amount `t`.
+ /// </summary>
+ /// <param name="b">The destination quaternion.</param>
+ /// <param name="preA">A quaternion before this quaternion.</param>
+ /// <param name="postB">A quaternion after `b`.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The interpolated quaternion.</returns>
+ public Quat CubicSlerp(Quat b, Quat preA, Quat postB, real_t weight)
+ {
+ real_t t2 = (1.0f - weight) * weight * 2f;
+ Quat sp = Slerp(b, weight);
+ Quat sq = preA.Slerpni(postB, weight);
return sp.Slerpni(sq, t2);
}
+ /// <summary>
+ /// Returns the dot product of two quaternions.
+ /// </summary>
+ /// <param name="b">The other quaternion.</param>
+ /// <returns>The dot product.</returns>
public real_t Dot(Quat b)
{
return x * b.x + y * b.y + z * b.z + w * b.w;
}
+ /// <summary>
+ /// Returns Euler angles (in the YXZ convention: when decomposing,
+ /// first Z, then X, and Y last) corresponding to the rotation
+ /// represented by the unit quaternion. Returned vector contains
+ /// the rotation angles in the format (X angle, Y angle, Z angle).
+ /// </summary>
+ /// <returns>The Euler angle representation of this quaternion.</returns>
public Vector3 GetEuler()
{
#if DEBUG
if (!IsNormalized())
+ {
throw new InvalidOperationException("Quat is not normalized");
+ }
#endif
var basis = new Basis(this);
return basis.GetEuler();
}
+ /// <summary>
+ /// Returns the inverse of the quaternion.
+ /// </summary>
+ /// <returns>The inverse quaternion.</returns>
public Quat Inverse()
{
#if DEBUG
if (!IsNormalized())
+ {
throw new InvalidOperationException("Quat is not normalized");
+ }
#endif
return new Quat(-x, -y, -z, w);
}
+ /// <summary>
+ /// Returns whether the quaternion is normalized or not.
+ /// </summary>
+ /// <returns>A bool for whether the quaternion is normalized or not.</returns>
+ public bool IsNormalized()
+ {
+ return Mathf.Abs(LengthSquared - 1) <= Mathf.Epsilon;
+ }
+
+ /// <summary>
+ /// Returns a copy of the quaternion, normalized to unit length.
+ /// </summary>
+ /// <returns>The normalized quaternion.</returns>
public Quat Normalized()
{
return this / Length;
}
- public Quat Slerp(Quat b, real_t t)
+ /// <summary>
+ /// Returns the result of the spherical linear interpolation between
+ /// this quaternion and `to` by amount `weight`.
+ ///
+ /// Note: Both quaternions must be normalized.
+ /// </summary>
+ /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting quaternion of the interpolation.</returns>
+ public Quat Slerp(Quat to, real_t weight)
{
#if DEBUG
if (!IsNormalized())
+ {
throw new InvalidOperationException("Quat is not normalized");
- if (!b.IsNormalized())
- throw new ArgumentException("Argument is not normalized", nameof(b));
+ }
+ if (!to.IsNormalized())
+ {
+ throw new ArgumentException("Argument is not normalized", nameof(to));
+ }
#endif
- // Calculate cosine
- real_t cosom = x * b.x + y * b.y + z * b.z + w * b.w;
+ // Calculate cosine.
+ real_t cosom = x * to.x + y * to.y + z * to.z + w * to.w;
var to1 = new Quat();
- // Adjust signs if necessary
+ // Adjust signs if necessary.
if (cosom < 0.0)
{
cosom = -cosom;
- to1.x = -b.x;
- to1.y = -b.y;
- to1.z = -b.z;
- to1.w = -b.w;
+ to1.x = -to.x;
+ to1.y = -to.y;
+ to1.z = -to.z;
+ to1.w = -to.w;
}
else
{
- to1.x = b.x;
- to1.y = b.y;
- to1.z = b.z;
- to1.w = b.w;
+ to1.x = to.x;
+ to1.y = to.y;
+ to1.z = to.z;
+ to1.w = to.w;
}
real_t sinom, scale0, scale1;
- // Calculate coefficients
+ // Calculate coefficients.
if (1.0 - cosom > Mathf.Epsilon)
{
- // Standard case (Slerp)
+ // Standard case (Slerp).
real_t omega = Mathf.Acos(cosom);
sinom = Mathf.Sin(omega);
- scale0 = Mathf.Sin((1.0f - t) * omega) / sinom;
- scale1 = Mathf.Sin(t * omega) / sinom;
+ scale0 = Mathf.Sin((1.0f - weight) * omega) / sinom;
+ scale1 = Mathf.Sin(weight * omega) / sinom;
}
else
{
- // Quaternions are very close so we can do a linear interpolation
- scale0 = 1.0f - t;
- scale1 = t;
+ // Quaternions are very close so we can do a linear interpolation.
+ scale0 = 1.0f - weight;
+ scale1 = weight;
}
- // Calculate final values
+ // Calculate final values.
return new Quat
(
scale0 * x + scale1 * to1.x,
@@ -163,9 +264,17 @@ namespace Godot
);
}
- public Quat Slerpni(Quat b, real_t t)
+ /// <summary>
+ /// Returns the result of the spherical linear interpolation between
+ /// this quaternion and `to` by amount `weight`, but without
+ /// checking if the rotation path is not bigger than 90 degrees.
+ /// </summary>
+ /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting quaternion of the interpolation.</returns>
+ public Quat Slerpni(Quat to, real_t weight)
{
- real_t dot = Dot(b);
+ real_t dot = Dot(to);
if (Mathf.Abs(dot) > 0.9999f)
{
@@ -174,33 +283,54 @@ namespace Godot
real_t theta = Mathf.Acos(dot);
real_t sinT = 1.0f / Mathf.Sin(theta);
- real_t newFactor = Mathf.Sin(t * theta) * sinT;
- real_t invFactor = Mathf.Sin((1.0f - t) * theta) * sinT;
+ real_t newFactor = Mathf.Sin(weight * theta) * sinT;
+ real_t invFactor = Mathf.Sin((1.0f - weight) * theta) * sinT;
return new Quat
(
- invFactor * x + newFactor * b.x,
- invFactor * y + newFactor * b.y,
- invFactor * z + newFactor * b.z,
- invFactor * w + newFactor * b.w
+ invFactor * x + newFactor * to.x,
+ invFactor * y + newFactor * to.y,
+ invFactor * z + newFactor * to.z,
+ invFactor * w + newFactor * to.w
);
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by this quaternion.
+ /// </summary>
+ /// <param name="v">A vector to transform.</param>
+ /// <returns>The transformed vector.</returns>
public Vector3 Xform(Vector3 v)
{
#if DEBUG
if (!IsNormalized())
+ {
throw new InvalidOperationException("Quat is not normalized");
+ }
#endif
var u = new Vector3(x, y, z);
Vector3 uv = u.Cross(v);
return v + ((uv * w) + u.Cross(uv)) * 2;
}
- // Static Readonly Properties
- public static Quat Identity { get; } = new Quat(0f, 0f, 0f, 1f);
-
- // Constructors
+ // Constants
+ private static readonly Quat _identity = new Quat(0, 0, 0, 1);
+
+ /// <summary>
+ /// The identity quaternion, representing no rotation.
+ /// Equivalent to an identity <see cref="Basis"/> matrix. If a vector is transformed by
+ /// an identity quaternion, it will not change.
+ /// </summary>
+ /// <value>Equivalent to `new Quat(0, 0, 0, 1)`.</value>
+ public static Quat Identity { get { return _identity; } }
+
+ /// <summary>
+ /// Constructs a quaternion defined by the given values.
+ /// </summary>
+ /// <param name="x">X component of the quaternion (imaginary `i` axis part).</param>
+ /// <param name="y">Y component of the quaternion (imaginary `j` axis part).</param>
+ /// <param name="z">Z component of the quaternion (imaginary `k` axis part).</param>
+ /// <param name="w">W component of the quaternion (real part).</param>
public Quat(real_t x, real_t y, real_t z, real_t w)
{
this.x = x;
@@ -209,21 +339,31 @@ namespace Godot
this.w = w;
}
- public bool IsNormalized()
- {
- return Mathf.Abs(LengthSquared - 1) <= Mathf.Epsilon;
- }
-
+ /// <summary>
+ /// Constructs a quaternion from the given quaternion.
+ /// </summary>
+ /// <param name="q">The existing quaternion.</param>
public Quat(Quat q)
{
this = q;
}
+ /// <summary>
+ /// Constructs a quaternion from the given <see cref="Basis"/>.
+ /// </summary>
+ /// <param name="basis">The basis to construct from.</param>
public Quat(Basis basis)
{
this = basis.Quat();
}
+ /// <summary>
+ /// Constructs a quaternion that will perform a rotation specified by
+ /// Euler angles (in the YXZ convention: when decomposing,
+ /// first Z, then X, and Y last),
+ /// given in the vector format as (X angle, Y angle, Z angle).
+ /// </summary>
+ /// <param name="eulerYXZ"></param>
public Quat(Vector3 eulerYXZ)
{
real_t half_a1 = eulerYXZ.y * 0.5f;
@@ -247,11 +387,19 @@ namespace Godot
w = sin_a1 * sin_a2 * sin_a3 + cos_a1 * cos_a2 * cos_a3;
}
+ /// <summary>
+ /// Constructs a quaternion that will rotate around the given axis
+ /// by the specified angle. The axis must be a normalized vector.
+ /// </summary>
+ /// <param name="axis">The axis to rotate around. Must be normalized.</param>
+ /// <param name="angle">The angle to rotate, in radians.</param>
public Quat(Vector3 axis, real_t angle)
{
#if DEBUG
if (!axis.IsNormalized())
+ {
throw new ArgumentException("Argument is not normalized", nameof(axis));
+ }
#endif
real_t d = axis.Length();
@@ -364,6 +512,12 @@ namespace Godot
return x == other.x && y == other.y && z == other.z && w == other.w;
}
+ /// <summary>
+ /// Returns true if this quaternion and `other` are approximately equal, by running
+ /// <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other quaternion to compare.</param>
+ /// <returns>Whether or not the quaternions are approximately equal.</returns>
public bool IsEqualApprox(Quat other)
{
return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z) && Mathf.IsEqualApprox(w, other.w);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
index 1098ffe4e5..868c3536fe 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs
@@ -8,6 +8,10 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 2D axis-aligned bounding box. Rect2 consists of a position, a size, and
+ /// several utility functions. It is typically used for fast overlap tests.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Rect2 : IEquatable<Rect2>
@@ -15,29 +19,52 @@ namespace Godot
private Vector2 _position;
private Vector2 _size;
+ /// <summary>
+ /// Beginning corner. Typically has values lower than End.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector2 Position
{
get { return _position; }
set { _position = value; }
}
+ /// <summary>
+ /// Size from Position to End. Typically all components are positive.
+ /// If the size is negative, you can use <see cref="Abs"/> to fix it.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector2 Size
{
get { return _size; }
set { _size = value; }
}
+ /// <summary>
+ /// Ending corner. This is calculated as <see cref="Position"/> plus
+ /// <see cref="Size"/>. Setting this value will change the size.
+ /// </summary>
+ /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value>
public Vector2 End
{
get { return _position + _size; }
set { _size = value - _position; }
}
+ /// <summary>
+ /// The area of this Rect2.
+ /// </summary>
+ /// <value>Equivalent to <see cref="GetArea()"/>.</value>
public real_t Area
{
get { return GetArea(); }
}
+ /// <summary>
+ /// Returns a Rect2 with equivalent position and size, modified so that
+ /// the top-left corner is the origin and width and height are positive.
+ /// </summary>
+ /// <returns>The modified Rect2.</returns>
public Rect2 Abs()
{
Vector2 end = End;
@@ -45,12 +72,20 @@ namespace Godot
return new Rect2(topLeft, _size.Abs());
}
- public Rect2 Clip(Rect2 b)
+ /// <summary>
+ /// Returns the intersection of this Rect2 and `b`.
+ /// If the rectangles do not intersect, an empty Rect2 is returned.
+ /// </summary>
+ /// <param name="b">The other Rect2.</param>
+ /// <returns>The intersection of this Rect2 and `b`, or an empty Rect2 if they do not intersect.</returns>
+ public Rect2 Intersection(Rect2 b)
{
var newRect = b;
if (!Intersects(newRect))
+ {
return new Rect2();
+ }
newRect._position.x = Mathf.Max(b._position.x, _position.x);
newRect._position.y = Mathf.Max(b._position.y, _position.y);
@@ -64,6 +99,11 @@ namespace Godot
return newRect;
}
+ /// <summary>
+ /// Returns true if this Rect2 completely encloses another one.
+ /// </summary>
+ /// <param name="b">The other Rect2 that may be enclosed.</param>
+ /// <returns>A bool for whether or not this Rect2 encloses `b`.</returns>
public bool Encloses(Rect2 b)
{
return b._position.x >= _position.x && b._position.y >= _position.y &&
@@ -71,6 +111,11 @@ namespace Godot
b._position.y + b._size.y < _position.y + _size.y;
}
+ /// <summary>
+ /// Returns this Rect2 expanded to include a given point.
+ /// </summary>
+ /// <param name="to">The point to include.</param>
+ /// <returns>The expanded Rect2.</returns>
public Rect2 Expand(Vector2 to)
{
var expanded = this;
@@ -79,14 +124,22 @@ namespace Godot
Vector2 end = expanded._position + expanded._size;
if (to.x < begin.x)
+ {
begin.x = to.x;
+ }
if (to.y < begin.y)
+ {
begin.y = to.y;
+ }
if (to.x > end.x)
+ {
end.x = to.x;
+ }
if (to.y > end.y)
+ {
end.y = to.y;
+ }
expanded._position = begin;
expanded._size = end - begin;
@@ -94,11 +147,20 @@ namespace Godot
return expanded;
}
+ /// <summary>
+ /// Returns the area of the Rect2.
+ /// </summary>
+ /// <returns>The area.</returns>
public real_t GetArea()
{
return _size.x * _size.y;
}
+ /// <summary>
+ /// Returns a copy of the Rect2 grown by the specified amount on all sides.
+ /// </summary>
+ /// <param name="by">The amount to grow by.</param>
+ /// <returns>The grown Rect2.</returns>
public Rect2 Grow(real_t by)
{
var g = this;
@@ -111,6 +173,14 @@ namespace Godot
return g;
}
+ /// <summary>
+ /// Returns a copy of the Rect2 grown by the specified amount on each side individually.
+ /// </summary>
+ /// <param name="left">The amount to grow by on the left side.</param>
+ /// <param name="top">The amount to grow by on the top side.</param>
+ /// <param name="right">The amount to grow by on the right side.</param>
+ /// <param name="bottom">The amount to grow by on the bottom side.</param>
+ /// <returns>The grown Rect2.</returns>
public Rect2 GrowIndividual(real_t left, real_t top, real_t right, real_t bottom)
{
var g = this;
@@ -123,23 +193,38 @@ namespace Godot
return g;
}
- public Rect2 GrowMargin(Margin margin, real_t by)
+ /// <summary>
+ /// Returns a copy of the Rect2 grown by the specified amount on the specified Side.
+ /// </summary>
+ /// <param name="side">The side to grow.</param>
+ /// <param name="by">The amount to grow by.</param>
+ /// <returns>The grown Rect2.</returns>
+ public Rect2 GrowSide(Side side, real_t by)
{
var g = this;
- g = g.GrowIndividual(Margin.Left == margin ? by : 0,
- Margin.Top == margin ? by : 0,
- Margin.Right == margin ? by : 0,
- Margin.Bottom == margin ? by : 0);
+ g = g.GrowIndividual(Side.Left == side ? by : 0,
+ Side.Top == side ? by : 0,
+ Side.Right == side ? by : 0,
+ Side.Bottom == side ? by : 0);
return g;
}
+ /// <summary>
+ /// Returns true if the Rect2 is flat or empty, or false otherwise.
+ /// </summary>
+ /// <returns>A bool for whether or not the Rect2 has area.</returns>
public bool HasNoArea()
{
return _size.x <= 0 || _size.y <= 0;
}
+ /// <summary>
+ /// Returns true if the Rect2 contains a point, or false otherwise.
+ /// </summary>
+ /// <param name="point">The point to check.</param>
+ /// <returns>A bool for whether or not the Rect2 contains `point`.</returns>
public bool HasPoint(Vector2 point)
{
if (point.x < _position.x)
@@ -155,20 +240,65 @@ namespace Godot
return true;
}
- public bool Intersects(Rect2 b)
+ /// <summary>
+ /// Returns true if the Rect2 overlaps with `b`
+ /// (i.e. they have at least one point in common).
+ ///
+ /// If `includeBorders` is true, they will also be considered overlapping
+ /// if their borders touch, even without intersection.
+ /// </summary>
+ /// <param name="b">The other Rect2 to check for intersections with.</param>
+ /// <param name="includeBorders">Whether or not to consider borders.</param>
+ /// <returns>A bool for whether or not they are intersecting.</returns>
+ public bool Intersects(Rect2 b, bool includeBorders = false)
{
- if (_position.x >= b._position.x + b._size.x)
- return false;
- if (_position.x + _size.x <= b._position.x)
- return false;
- if (_position.y >= b._position.y + b._size.y)
- return false;
- if (_position.y + _size.y <= b._position.y)
- return false;
+ if (includeBorders)
+ {
+ if (_position.x > b._position.x + b._size.x)
+ {
+ return false;
+ }
+ if (_position.x + _size.x < b._position.x)
+ {
+ return false;
+ }
+ if (_position.y > b._position.y + b._size.y)
+ {
+ return false;
+ }
+ if (_position.y + _size.y < b._position.y)
+ {
+ return false;
+ }
+ }
+ else
+ {
+ if (_position.x >= b._position.x + b._size.x)
+ {
+ return false;
+ }
+ if (_position.x + _size.x <= b._position.x)
+ {
+ return false;
+ }
+ if (_position.y >= b._position.y + b._size.y)
+ {
+ return false;
+ }
+ if (_position.y + _size.y <= b._position.y)
+ {
+ return false;
+ }
+ }
return true;
}
+ /// <summary>
+ /// Returns a larger Rect2 that contains this Rect2 and `b`.
+ /// </summary>
+ /// <param name="b">The other Rect2.</param>
+ /// <returns>The merged Rect2.</returns>
public Rect2 Merge(Rect2 b)
{
Rect2 newRect;
@@ -179,27 +309,53 @@ namespace Godot
newRect._size.x = Mathf.Max(b._position.x + b._size.x, _position.x + _size.x);
newRect._size.y = Mathf.Max(b._position.y + b._size.y, _position.y + _size.y);
- newRect._size = newRect._size - newRect._position; // Make relative again
+ newRect._size -= newRect._position; // Make relative again
return newRect;
}
- // Constructors
+ /// <summary>
+ /// Constructs a Rect2 from a position and size.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="size">The size.</param>
public Rect2(Vector2 position, Vector2 size)
{
_position = position;
_size = size;
}
+
+ /// <summary>
+ /// Constructs a Rect2 from a position, width, and height.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
public Rect2(Vector2 position, real_t width, real_t height)
{
_position = position;
_size = new Vector2(width, height);
}
+
+ /// <summary>
+ /// Constructs a Rect2 from x, y, and size.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="size">The size.</param>
public Rect2(real_t x, real_t y, Vector2 size)
{
_position = new Vector2(x, y);
_size = size;
}
+
+ /// <summary>
+ /// Constructs a Rect2 from x, y, width, and height.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
public Rect2(real_t x, real_t y, real_t width, real_t height)
{
_position = new Vector2(x, y);
@@ -231,6 +387,12 @@ namespace Godot
return _position.Equals(other._position) && _size.Equals(other._size);
}
+ /// <summary>
+ /// Returns true if this Rect2 and `other` are approximately equal, by running
+ /// <see cref="Vector2.IsEqualApprox(Vector2)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other Rect2 to compare.</param>
+ /// <returns>Whether or not the Rect2s are approximately equal.</returns>
public bool IsEqualApprox(Rect2 other)
{
return _position.IsEqualApprox(other._position) && _size.IsEqualApprox(other.Size);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs
index c0b236c524..c27af74866 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs
@@ -3,6 +3,10 @@ using System.Runtime.InteropServices;
namespace Godot
{
+ /// <summary>
+ /// 2D axis-aligned bounding box using integers. Rect2i consists of a position, a size, and
+ /// several utility functions. It is typically used for fast overlap tests.
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Rect2i : IEquatable<Rect2i>
@@ -10,29 +14,52 @@ namespace Godot
private Vector2i _position;
private Vector2i _size;
+ /// <summary>
+ /// Beginning corner. Typically has values lower than End.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector2i Position
{
get { return _position; }
set { _position = value; }
}
+ /// <summary>
+ /// Size from Position to End. Typically all components are positive.
+ /// If the size is negative, you can use <see cref="Abs"/> to fix it.
+ /// </summary>
+ /// <value>Directly uses a private field.</value>
public Vector2i Size
{
get { return _size; }
set { _size = value; }
}
+ /// <summary>
+ /// Ending corner. This is calculated as <see cref="Position"/> plus
+ /// <see cref="Size"/>. Setting this value will change the size.
+ /// </summary>
+ /// <value>Getting is equivalent to `value = Position + Size`, setting is equivalent to `Size = value - Position`.</value>
public Vector2i End
{
get { return _position + _size; }
set { _size = value - _position; }
}
+ /// <summary>
+ /// The area of this Rect2i.
+ /// </summary>
+ /// <value>Equivalent to <see cref="GetArea()"/>.</value>
public int Area
{
get { return GetArea(); }
}
+ /// <summary>
+ /// Returns a Rect2i with equivalent position and size, modified so that
+ /// the top-left corner is the origin and width and height are positive.
+ /// </summary>
+ /// <returns>The modified Rect2i.</returns>
public Rect2i Abs()
{
Vector2i end = End;
@@ -40,12 +67,20 @@ namespace Godot
return new Rect2i(topLeft, _size.Abs());
}
- public Rect2i Clip(Rect2i b)
+ /// <summary>
+ /// Returns the intersection of this Rect2i and `b`.
+ /// If the rectangles do not intersect, an empty Rect2i is returned.
+ /// </summary>
+ /// <param name="b">The other Rect2i.</param>
+ /// <returns>The intersection of this Rect2i and `b`, or an empty Rect2i if they do not intersect.</returns>
+ public Rect2i Intersection(Rect2i b)
{
var newRect = b;
if (!Intersects(newRect))
+ {
return new Rect2i();
+ }
newRect._position.x = Mathf.Max(b._position.x, _position.x);
newRect._position.y = Mathf.Max(b._position.y, _position.y);
@@ -59,6 +94,11 @@ namespace Godot
return newRect;
}
+ /// <summary>
+ /// Returns true if this Rect2i completely encloses another one.
+ /// </summary>
+ /// <param name="b">The other Rect2i that may be enclosed.</param>
+ /// <returns>A bool for whether or not this Rect2i encloses `b`.</returns>
public bool Encloses(Rect2i b)
{
return b._position.x >= _position.x && b._position.y >= _position.y &&
@@ -66,6 +106,11 @@ namespace Godot
b._position.y + b._size.y < _position.y + _size.y;
}
+ /// <summary>
+ /// Returns this Rect2i expanded to include a given point.
+ /// </summary>
+ /// <param name="to">The point to include.</param>
+ /// <returns>The expanded Rect2i.</returns>
public Rect2i Expand(Vector2i to)
{
var expanded = this;
@@ -74,14 +119,22 @@ namespace Godot
Vector2i end = expanded._position + expanded._size;
if (to.x < begin.x)
+ {
begin.x = to.x;
+ }
if (to.y < begin.y)
+ {
begin.y = to.y;
+ }
if (to.x > end.x)
+ {
end.x = to.x;
+ }
if (to.y > end.y)
+ {
end.y = to.y;
+ }
expanded._position = begin;
expanded._size = end - begin;
@@ -89,11 +142,20 @@ namespace Godot
return expanded;
}
+ /// <summary>
+ /// Returns the area of the Rect2.
+ /// </summary>
+ /// <returns>The area.</returns>
public int GetArea()
{
return _size.x * _size.y;
}
+ /// <summary>
+ /// Returns a copy of the Rect2i grown by the specified amount on all sides.
+ /// </summary>
+ /// <param name="by">The amount to grow by.</param>
+ /// <returns>The grown Rect2i.</returns>
public Rect2i Grow(int by)
{
var g = this;
@@ -106,6 +168,14 @@ namespace Godot
return g;
}
+ /// <summary>
+ /// Returns a copy of the Rect2i grown by the specified amount on each side individually.
+ /// </summary>
+ /// <param name="left">The amount to grow by on the left side.</param>
+ /// <param name="top">The amount to grow by on the top side.</param>
+ /// <param name="right">The amount to grow by on the right side.</param>
+ /// <param name="bottom">The amount to grow by on the bottom side.</param>
+ /// <returns>The grown Rect2i.</returns>
public Rect2i GrowIndividual(int left, int top, int right, int bottom)
{
var g = this;
@@ -118,23 +188,38 @@ namespace Godot
return g;
}
- public Rect2i GrowMargin(Margin margin, int by)
+ /// <summary>
+ /// Returns a copy of the Rect2i grown by the specified amount on the specified Side.
+ /// </summary>
+ /// <param name="side">The side to grow.</param>
+ /// <param name="by">The amount to grow by.</param>
+ /// <returns>The grown Rect2i.</returns>
+ public Rect2i GrowSide(Side side, int by)
{
var g = this;
- g = g.GrowIndividual(Margin.Left == margin ? by : 0,
- Margin.Top == margin ? by : 0,
- Margin.Right == margin ? by : 0,
- Margin.Bottom == margin ? by : 0);
+ g = g.GrowIndividual(Side.Left == side ? by : 0,
+ Side.Top == side ? by : 0,
+ Side.Right == side ? by : 0,
+ Side.Bottom == side ? by : 0);
return g;
}
+ /// <summary>
+ /// Returns true if the Rect2i is flat or empty, or false otherwise.
+ /// </summary>
+ /// <returns>A bool for whether or not the Rect2i has area.</returns>
public bool HasNoArea()
{
return _size.x <= 0 || _size.y <= 0;
}
+ /// <summary>
+ /// Returns true if the Rect2i contains a point, or false otherwise.
+ /// </summary>
+ /// <param name="point">The point to check.</param>
+ /// <returns>A bool for whether or not the Rect2i contains `point`.</returns>
public bool HasPoint(Vector2i point)
{
if (point.x < _position.x)
@@ -150,20 +235,49 @@ namespace Godot
return true;
}
- public bool Intersects(Rect2i b)
+ /// <summary>
+ /// Returns true if the Rect2i overlaps with `b`
+ /// (i.e. they have at least one point in common).
+ ///
+ /// If `includeBorders` is true, they will also be considered overlapping
+ /// if their borders touch, even without intersection.
+ /// </summary>
+ /// <param name="b">The other Rect2i to check for intersections with.</param>
+ /// <param name="includeBorders">Whether or not to consider borders.</param>
+ /// <returns>A bool for whether or not they are intersecting.</returns>
+ public bool Intersects(Rect2i b, bool includeBorders = false)
{
- if (_position.x >= b._position.x + b._size.x)
- return false;
- if (_position.x + _size.x <= b._position.x)
- return false;
- if (_position.y >= b._position.y + b._size.y)
- return false;
- if (_position.y + _size.y <= b._position.y)
- return false;
+ if (includeBorders)
+ {
+ if (_position.x > b._position.x + b._size.x)
+ return false;
+ if (_position.x + _size.x < b._position.x)
+ return false;
+ if (_position.y > b._position.y + b._size.y)
+ return false;
+ if (_position.y + _size.y < b._position.y)
+ return false;
+ }
+ else
+ {
+ if (_position.x >= b._position.x + b._size.x)
+ return false;
+ if (_position.x + _size.x <= b._position.x)
+ return false;
+ if (_position.y >= b._position.y + b._size.y)
+ return false;
+ if (_position.y + _size.y <= b._position.y)
+ return false;
+ }
return true;
}
+ /// <summary>
+ /// Returns a larger Rect2i that contains this Rect2i and `b`.
+ /// </summary>
+ /// <param name="b">The other Rect2i.</param>
+ /// <returns>The merged Rect2i.</returns>
public Rect2i Merge(Rect2i b)
{
Rect2i newRect;
@@ -174,27 +288,53 @@ namespace Godot
newRect._size.x = Mathf.Max(b._position.x + b._size.x, _position.x + _size.x);
newRect._size.y = Mathf.Max(b._position.y + b._size.y, _position.y + _size.y);
- newRect._size = newRect._size - newRect._position; // Make relative again
+ newRect._size -= newRect._position; // Make relative again
return newRect;
}
- // Constructors
+ /// <summary>
+ /// Constructs a Rect2i from a position and size.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="size">The size.</param>
public Rect2i(Vector2i position, Vector2i size)
{
_position = position;
_size = size;
}
+
+ /// <summary>
+ /// Constructs a Rect2i from a position, width, and height.
+ /// </summary>
+ /// <param name="position">The position.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
public Rect2i(Vector2i position, int width, int height)
{
_position = position;
_size = new Vector2i(width, height);
}
+
+ /// <summary>
+ /// Constructs a Rect2i from x, y, and size.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="size">The size.</param>
public Rect2i(int x, int y, Vector2i size)
{
_position = new Vector2i(x, y);
_size = size;
}
+
+ /// <summary>
+ /// Constructs a Rect2i from x, y, width, and height.
+ /// </summary>
+ /// <param name="x">The position's X coordinate.</param>
+ /// <param name="y">The position's Y coordinate.</param>
+ /// <param name="width">The width.</param>
+ /// <param name="height">The height.</param>
public Rect2i(int x, int y, int width, int height)
{
_position = new Vector2i(x, y);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
index 099eacd7dd..0700f197ff 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
@@ -12,7 +12,7 @@ namespace Godot
{
private static int GetSliceCount(this string instance, string splitter)
{
- if (instance.Empty() || splitter.Empty())
+ if (string.IsNullOrEmpty(instance) || string.IsNullOrEmpty(splitter))
return 0;
int pos = 0;
@@ -29,7 +29,7 @@ namespace Godot
private static string GetSliceCharacter(this string instance, char splitter, int slice)
{
- if (!instance.Empty() && slice >= 0)
+ if (!string.IsNullOrEmpty(instance) && slice >= 0)
{
int i = 0;
int prev = 0;
@@ -237,10 +237,10 @@ namespace Godot
// </summary>
public static int CompareTo(this string instance, string to, bool caseSensitive = true)
{
- if (instance.Empty())
- return to.Empty() ? 0 : -1;
+ if (string.IsNullOrEmpty(instance))
+ return string.IsNullOrEmpty(to) ? 0 : -1;
- if (to.Empty())
+ if (string.IsNullOrEmpty(to))
return 1;
int instanceIndex = 0;
@@ -287,14 +287,6 @@ namespace Godot
}
// <summary>
- // Return true if the string is empty.
- // </summary>
- public static bool Empty(this string instance)
- {
- return string.IsNullOrEmpty(instance);
- }
-
- // <summary>
// Return true if the strings ends with the given string.
// </summary>
public static bool EndsWith(this string instance, string text)
@@ -330,6 +322,15 @@ namespace Godot
return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
+ /// <summary>Find the first occurrence of a char. Optionally, the search starting position can be passed.</summary>
+ /// <returns>The first instance of the char, or -1 if not found.</returns>
+ public static int Find(this string instance, char what, int from = 0, bool caseSensitive = true)
+ {
+ // TODO: Could be more efficient if we get a char version of `IndexOf`.
+ // See https://github.com/dotnet/runtime/issues/44116
+ return instance.IndexOf(what.ToString(), from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
+ }
+
/// <summary>Find the last occurrence of a substring.</summary>
/// <returns>The starting position of the substring, or -1 if not found.</returns>
public static int FindLast(this string instance, string what, bool caseSensitive = true)
@@ -401,6 +402,35 @@ namespace Godot
return instance.Substring(sep + 1);
}
+ /// <summary>
+ /// Converts the given byte array of ASCII encoded text to a string.
+ /// Faster alternative to <see cref="GetStringFromUTF8"/> if the
+ /// content is ASCII-only. Unlike the UTF-8 function this function
+ /// maps every byte to a character in the array. Multibyte sequences
+ /// will not be interpreted correctly. For parsing user input always
+ /// use <see cref="GetStringFromUTF8"/>.
+ /// </summary>
+ /// <param name="bytes">A byte array of ASCII characters (on the range of 0-127).</param>
+ /// <returns>A string created from the bytes.</returns>
+ public static string GetStringFromASCII(this byte[] bytes)
+ {
+ return Encoding.ASCII.GetString(bytes);
+ }
+
+ /// <summary>
+ /// Converts the given byte array of UTF-8 encoded text to a string.
+ /// Slower than <see cref="GetStringFromASCII"/> but supports UTF-8
+ /// encoded data. Use this function if you are unsure about the
+ /// source of the data. For user input this function
+ /// should always be preferred.
+ /// </summary>
+ /// <param name="bytes">A byte array of UTF-8 characters (a character may take up multiple bytes).</param>
+ /// <returns>A string created from the bytes.</returns>
+ public static string GetStringFromUTF8(this byte[] bytes)
+ {
+ return Encoding.UTF8.GetString(bytes);
+ }
+
// <summary>
// Hash the string and return a 32 bits integer.
// </summary>
@@ -416,6 +446,53 @@ namespace Godot
return hashv;
}
+ /// <summary>
+ /// Returns a hexadecimal representation of this byte as a string.
+ /// </summary>
+ /// <param name="bytes">The byte to encode.</param>
+ /// <returns>The hexadecimal representation of this byte.</returns>
+ internal static string HexEncode(this byte b)
+ {
+ var ret = string.Empty;
+
+ for (int i = 0; i < 2; i++)
+ {
+ char c;
+ int lv = b & 0xF;
+
+ if (lv < 10)
+ {
+ c = (char)('0' + lv);
+ }
+ else
+ {
+ c = (char)('a' + lv - 10);
+ }
+
+ b >>= 4;
+ ret = c + ret;
+ }
+
+ return ret;
+ }
+
+ /// <summary>
+ /// Returns a hexadecimal representation of this byte array as a string.
+ /// </summary>
+ /// <param name="bytes">The byte array to encode.</param>
+ /// <returns>The hexadecimal representation of this byte array.</returns>
+ public static string HexEncode(this byte[] bytes)
+ {
+ var ret = string.Empty;
+
+ foreach (byte b in bytes)
+ {
+ ret += b.HexEncode();
+ }
+
+ return ret;
+ }
+
// <summary>
// Convert a string containing an hexadecimal number into an int.
// </summary>
@@ -448,7 +525,12 @@ namespace Godot
// </summary>
public static bool IsAbsPath(this string instance)
{
- return System.IO.Path.IsPathRooted(instance);
+ if (string.IsNullOrEmpty(instance))
+ return false;
+ else if (instance.Length > 1)
+ return instance[0] == '/' || instance[0] == '\\' || instance.Contains(":/") || instance.Contains(":\\");
+ else
+ return instance[0] == '/' || instance[0] == '\\';
}
// <summary>
@@ -456,7 +538,7 @@ namespace Godot
// </summary>
public static bool IsRelPath(this string instance)
{
- return !System.IO.Path.IsPathRooted(instance);
+ return !IsAbsPath(instance);
}
// <summary>
@@ -632,41 +714,73 @@ namespace Godot
return instance.Length;
}
- // <summary>
- // Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'.
- // </summary>
- public static bool ExprMatch(this string instance, string expr, bool caseSensitive)
+ /// <summary>
+ /// Returns a copy of the string with characters removed from the left.
+ /// </summary>
+ /// <param name="instance">The string to remove characters from.</param>
+ /// <param name="chars">The characters to be removed.</param>
+ /// <returns>A copy of the string with characters removed from the left.</returns>
+ public static string LStrip(this string instance, string chars)
{
- if (expr.Length == 0 || instance.Length == 0)
- return false;
+ int len = instance.Length;
+ int beg;
+
+ for (beg = 0; beg < len; beg++)
+ {
+ if (chars.Find(instance[beg]) == -1)
+ {
+ break;
+ }
+ }
+
+ if (beg == 0)
+ {
+ return instance;
+ }
+
+ return instance.Substr(beg, len - beg);
+ }
+
+ /// <summary>
+ /// Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'.
+ /// </summary>
+ private static bool ExprMatch(this string instance, string expr, bool caseSensitive)
+ {
+ // case '\0':
+ if (expr.Length == 0)
+ return instance.Length == 0;
switch (expr[0])
{
- case '\0':
- return instance[0] == 0;
case '*':
- return ExprMatch(expr + 1, instance, caseSensitive) || instance[0] != 0 && ExprMatch(expr, instance + 1, caseSensitive);
+ return ExprMatch(instance, expr.Substring(1), caseSensitive) || (instance.Length > 0 && ExprMatch(instance.Substring(1), expr, caseSensitive));
case '?':
- return instance[0] != 0 && instance[0] != '.' && ExprMatch(expr + 1, instance + 1, caseSensitive);
+ return instance.Length > 0 && instance[0] != '.' && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
default:
- return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) &&
- ExprMatch(expr + 1, instance + 1, caseSensitive);
+ if (instance.Length == 0) return false;
+ return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive);
}
}
- // <summary>
- // Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]).
- // </summary>
+ /// <summary>
+ /// Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]).
+ /// </summary>
public static bool Match(this string instance, string expr, bool caseSensitive = true)
{
+ if (instance.Length == 0 || expr.Length == 0)
+ return false;
+
return instance.ExprMatch(expr, caseSensitive);
}
- // <summary>
- // Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]).
- // </summary>
+ /// <summary>
+ /// Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]).
+ /// </summary>
public static bool MatchN(this string instance, string expr)
{
+ if (instance.Length == 0 || expr.Length == 0)
+ return false;
+
return instance.ExprMatch(expr, caseSensitive: false);
}
@@ -855,6 +969,33 @@ namespace Godot
return instance.Substring(pos, instance.Length - pos);
}
+ /// <summary>
+ /// Returns a copy of the string with characters removed from the right.
+ /// </summary>
+ /// <param name="instance">The string to remove characters from.</param>
+ /// <param name="chars">The characters to be removed.</param>
+ /// <returns>A copy of the string with characters removed from the right.</returns>
+ public static string RStrip(this string instance, string chars)
+ {
+ int len = instance.Length;
+ int end;
+
+ for (end = len - 1; end >= 0; end--)
+ {
+ if (chars.Find(instance[end]) == -1)
+ {
+ break;
+ }
+ }
+
+ if (end == len - 1)
+ {
+ return instance;
+ }
+
+ return instance.Substr(0, end + 1);
+ }
+
public static byte[] SHA256Buffer(this string instance)
{
return godot_icall_String_sha256_buffer(instance);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs
index 6a58b90561..ac47f6029f 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs
@@ -8,11 +8,28 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 3×4 matrix (3 rows, 4 columns) used for 3D linear transformations.
+ /// It can represent transformations such as translation, rotation, or scaling.
+ /// It consists of a <see cref="Basis"/> (first 3 columns) and a
+ /// <see cref="Vector3"/> for the origin (last column).
+ ///
+ /// For more information, read this documentation article:
+ /// https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Transform : IEquatable<Transform>
{
+ /// <summary>
+ /// The <see cref="Basis"/> of this transform. Contains the X, Y, and Z basis
+ /// vectors (columns 0 to 2) and is responsible for rotation and scale.
+ /// </summary>
public Basis basis;
+
+ /// <summary>
+ /// The origin vector (column 3, the fourth column). Equivalent to array index `[3]`.
+ /// </summary>
public Vector3 origin;
/// <summary>
@@ -85,13 +102,24 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns the inverse of the transform, under the assumption that
+ /// the transformation is composed of rotation, scaling, and translation.
+ /// </summary>
+ /// <returns>The inverse transformation matrix.</returns>
public Transform AffineInverse()
{
Basis basisInv = basis.Inverse();
return new Transform(basisInv, basisInv.Xform(-origin));
}
- public Transform InterpolateWith(Transform transform, real_t c)
+ /// <summary>
+ /// Interpolates this transform to the other `transform` by `weight`.
+ /// </summary>
+ /// <param name="transform">The other transform.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The interpolated transform.</returns>
+ public Transform InterpolateWith(Transform transform, real_t weight)
{
/* not sure if very "efficient" but good enough? */
@@ -104,18 +132,37 @@ namespace Godot
Vector3 destinationLocation = transform.origin;
var interpolated = new Transform();
- interpolated.basis.SetQuatScale(sourceRotation.Slerp(destinationRotation, c).Normalized(), sourceScale.Lerp(destinationScale, c));
- interpolated.origin = sourceLocation.Lerp(destinationLocation, c);
+ interpolated.basis.SetQuatScale(sourceRotation.Slerp(destinationRotation, weight).Normalized(), sourceScale.Lerp(destinationScale, weight));
+ interpolated.origin = sourceLocation.Lerp(destinationLocation, weight);
return interpolated;
}
+ /// <summary>
+ /// Returns the inverse of the transform, under the assumption that
+ /// the transformation is composed of rotation and translation
+ /// (no scaling, use <see cref="AffineInverse"/> for transforms with scaling).
+ /// </summary>
+ /// <returns>The inverse matrix.</returns>
public Transform Inverse()
{
Basis basisTr = basis.Transposed();
return new Transform(basisTr, basisTr.Xform(-origin));
}
+ /// <summary>
+ /// Returns a copy of the transform rotated such that its
+ /// -Z axis (forward) points towards the target position.
+ ///
+ /// The transform will first be rotated around the given up vector,
+ /// and then fully aligned to the target by a further rotation around
+ /// an axis perpendicular to both the target and up vectors.
+ ///
+ /// Operations take place in global space.
+ /// </summary>
+ /// <param name="target">The object to look at.</param>
+ /// <param name="up">The relative up direction</param>
+ /// <returns>The resulting transform.</returns>
public Transform LookingAt(Vector3 target, Vector3 up)
{
var t = this;
@@ -123,22 +170,39 @@ namespace Godot
return t;
}
+ /// <summary>
+ /// Returns the transform with the basis orthogonal (90 degrees),
+ /// and normalized axis vectors (scale of 1 or -1).
+ /// </summary>
+ /// <returns>The orthonormalized transform.</returns>
public Transform Orthonormalized()
{
return new Transform(basis.Orthonormalized(), origin);
}
+ /// <summary>
+ /// Rotates the transform around the given `axis` by `phi` (in radians),
+ /// using matrix multiplication. The axis must be a normalized vector.
+ /// </summary>
+ /// <param name="axis">The axis to rotate around. Must be normalized.</param>
+ /// <param name="phi">The angle to rotate, in radians.</param>
+ /// <returns>The rotated transformation matrix.</returns>
public Transform Rotated(Vector3 axis, real_t phi)
{
return new Transform(new Basis(axis, phi), new Vector3()) * this;
}
+ /// <summary>
+ /// Scales the transform by the given 3D scaling factor, using matrix multiplication.
+ /// </summary>
+ /// <param name="scale">The scale to introduce.</param>
+ /// <returns>The scaled transformation matrix.</returns>
public Transform Scaled(Vector3 scale)
{
return new Transform(basis.Scaled(scale), origin * scale);
}
- public void SetLookAt(Vector3 eye, Vector3 target, Vector3 up)
+ private void SetLookAt(Vector3 eye, Vector3 target, Vector3 up)
{
// Make rotation matrix
// Z vector
@@ -161,16 +225,30 @@ namespace Godot
origin = eye;
}
- public Transform Translated(Vector3 ofs)
+ /// <summary>
+ /// Translates the transform by the given `offset`,
+ /// relative to the transform's basis vectors.
+ ///
+ /// Unlike <see cref="Rotated"/> and <see cref="Scaled"/>,
+ /// this does not use matrix multiplication.
+ /// </summary>
+ /// <param name="offset">The offset to translate by.</param>
+ /// <returns>The translated matrix.</returns>
+ public Transform Translated(Vector3 offset)
{
return new Transform(basis, new Vector3
(
- origin[0] += basis.Row0.Dot(ofs),
- origin[1] += basis.Row1.Dot(ofs),
- origin[2] += basis.Row2.Dot(ofs)
+ origin[0] += basis.Row0.Dot(offset),
+ origin[1] += basis.Row1.Dot(offset),
+ origin[2] += basis.Row2.Dot(offset)
));
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by this transformation matrix.
+ /// </summary>
+ /// <param name="v">A vector to transform.</param>
+ /// <returns>The transformed vector.</returns>
public Vector3 Xform(Vector3 v)
{
return new Vector3
@@ -181,6 +259,14 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the transposed transformation matrix.
+ ///
+ /// Note: This results in a multiplication by the inverse of the
+ /// transformation matrix only if it represents a rotation-reflection.
+ /// </summary>
+ /// <param name="v">A vector to inversely transform.</param>
+ /// <returns>The inversely transformed vector.</returns>
public Vector3 XformInv(Vector3 v)
{
Vector3 vInv = v - origin;
@@ -199,24 +285,58 @@ namespace Godot
private static readonly Transform _flipY = new Transform(new Basis(1, 0, 0, 0, -1, 0, 0, 0, 1), Vector3.Zero);
private static readonly Transform _flipZ = new Transform(new Basis(1, 0, 0, 0, 1, 0, 0, 0, -1), Vector3.Zero);
+ /// <summary>
+ /// The identity transform, with no translation, rotation, or scaling applied.
+ /// This is used as a replacement for `Transform()` in GDScript.
+ /// Do not use `new Transform()` with no arguments in C#, because it sets all values to zero.
+ /// </summary>
+ /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Up, Vector3.Back, Vector3.Zero)`.</value>
public static Transform Identity { get { return _identity; } }
+ /// <summary>
+ /// The transform that will flip something along the X axis.
+ /// </summary>
+ /// <value>Equivalent to `new Transform(Vector3.Left, Vector3.Up, Vector3.Back, Vector3.Zero)`.</value>
public static Transform FlipX { get { return _flipX; } }
+ /// <summary>
+ /// The transform that will flip something along the Y axis.
+ /// </summary>
+ /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Down, Vector3.Back, Vector3.Zero)`.</value>
public static Transform FlipY { get { return _flipY; } }
+ /// <summary>
+ /// The transform that will flip something along the Z axis.
+ /// </summary>
+ /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Up, Vector3.Forward, Vector3.Zero)`.</value>
public static Transform FlipZ { get { return _flipZ; } }
- // Constructors
+ /// <summary>
+ /// Constructs a transformation matrix from 4 vectors (matrix columns).
+ /// </summary>
+ /// <param name="column0">The X vector, or column index 0.</param>
+ /// <param name="column1">The Y vector, or column index 1.</param>
+ /// <param name="column2">The Z vector, or column index 2.</param>
+ /// <param name="origin">The origin vector, or column index 3.</param>
public Transform(Vector3 column0, Vector3 column1, Vector3 column2, Vector3 origin)
{
basis = new Basis(column0, column1, column2);
this.origin = origin;
}
+ /// <summary>
+ /// Constructs a transformation matrix from the given quaternion and origin vector.
+ /// </summary>
+ /// <param name="quat">The <see cref="Godot.Quat"/> to create the basis from.</param>
+ /// <param name="origin">The origin vector, or column index 3.</param>
public Transform(Quat quat, Vector3 origin)
{
basis = new Basis(quat);
this.origin = origin;
}
+ /// <summary>
+ /// Constructs a transformation matrix from the given basis and origin vector.
+ /// </summary>
+ /// <param name="basis">The <see cref="Godot.Basis"/> to create the basis from.</param>
+ /// <param name="origin">The origin vector, or column index 3.</param>
public Transform(Basis basis, Vector3 origin)
{
this.basis = basis;
@@ -255,6 +375,12 @@ namespace Godot
return basis.Equals(other.basis) && origin.Equals(other.origin);
}
+ /// <summary>
+ /// Returns true if this transform and `other` are approximately equal, by running
+ /// <see cref="Vector3.IsEqualApprox(Vector3)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other transform to compare.</param>
+ /// <returns>Whether or not the matrices are approximately equal.</returns>
public bool IsEqualApprox(Transform other)
{
return basis.IsEqualApprox(other.basis) && origin.IsEqualApprox(other.origin);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
index 3ae96d4922..bc0f81b2a7 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs
@@ -8,25 +8,44 @@ using real_t = System.Single;
namespace Godot
{
+ /// <summary>
+ /// 2×3 matrix (2 rows, 3 columns) used for 2D linear transformations.
+ /// It can represent transformations such as translation, rotation, or scaling.
+ /// It consists of a three <see cref="Vector2"/> values: x, y, and the origin.
+ ///
+ /// For more information, read this documentation article:
+ /// https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html
+ /// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Transform2D : IEquatable<Transform2D>
{
+ /// <summary>
+ /// The basis matrix's X vector (column 0). Equivalent to array index `[0]`.
+ /// </summary>
+ /// <value></value>
public Vector2 x;
+
+ /// <summary>
+ /// The basis matrix's Y vector (column 1). Equivalent to array index `[1]`.
+ /// </summary>
public Vector2 y;
+
+ /// <summary>
+ /// The origin vector (column 2, the third column). Equivalent to array index `[2]`.
+ /// The origin vector represents translation.
+ /// </summary>
public Vector2 origin;
+ /// <summary>
+ /// The rotation of this transformation matrix.
+ /// </summary>
+ /// <value>Getting is equivalent to calling <see cref="Mathf.Atan2(real_t, real_t)"/> with the values of <see cref="x"/>.</value>
public real_t Rotation
{
get
{
- real_t det = BasisDeterminant();
- Transform2D t = Orthonormalized();
- if (det < 0)
- {
- t.ScaleBasis(new Vector2(1, -1));
- }
- return Mathf.Atan2(t.x.y, t.x.x);
+ return Mathf.Atan2(x.y, x.x);
}
set
{
@@ -38,6 +57,10 @@ namespace Godot
}
}
+ /// <summary>
+ /// The scale of this transformation matrix.
+ /// </summary>
+ /// <value>Equivalent to the lengths of each column vector, but Y is negative if the determinant is negative.</value>
public Vector2 Scale
{
get
@@ -47,8 +70,7 @@ namespace Godot
}
set
{
- x = x.Normalized();
- y = y.Normalized();
+ value /= Scale; // Value becomes what's called "delta_scale" in core.
x *= value.x;
y *= value.y;
}
@@ -112,6 +134,11 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns the inverse of the transform, under the assumption that
+ /// the transformation is composed of rotation, scaling, and translation.
+ /// </summary>
+ /// <returns>The inverse transformation matrix.</returns>
public Transform2D AffineInverse()
{
real_t det = BasisDeterminant();
@@ -135,28 +162,58 @@ namespace Godot
return inv;
}
+ /// <summary>
+ /// Returns the determinant of the basis matrix. If the basis is
+ /// uniformly scaled, its determinant is the square of the scale.
+ ///
+ /// A negative determinant means the Y scale is negative.
+ /// A zero determinant means the basis isn't invertible,
+ /// and is usually considered invalid.
+ /// </summary>
+ /// <returns>The determinant of the basis matrix.</returns>
private real_t BasisDeterminant()
{
return x.x * y.y - x.y * y.x;
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the basis matrix.
+ /// This method does not account for translation (the origin vector).
+ /// </summary>
+ /// <param name="v">A vector to transform.</param>
+ /// <returns>The transformed vector.</returns>
public Vector2 BasisXform(Vector2 v)
{
return new Vector2(Tdotx(v), Tdoty(v));
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the inverse basis matrix.
+ /// This method does not account for translation (the origin vector).
+ ///
+ /// Note: This results in a multiplication by the inverse of the
+ /// basis matrix only if it represents a rotation-reflection.
+ /// </summary>
+ /// <param name="v">A vector to inversely transform.</param>
+ /// <returns>The inversely transformed vector.</returns>
public Vector2 BasisXformInv(Vector2 v)
{
return new Vector2(x.Dot(v), y.Dot(v));
}
- public Transform2D InterpolateWith(Transform2D m, real_t c)
+ /// <summary>
+ /// Interpolates this transform to the other `transform` by `weight`.
+ /// </summary>
+ /// <param name="transform">The other transform.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The interpolated transform.</returns>
+ public Transform2D InterpolateWith(Transform2D transform, real_t weight)
{
real_t r1 = Rotation;
- real_t r2 = m.Rotation;
+ real_t r2 = transform.Rotation;
Vector2 s1 = Scale;
- Vector2 s2 = m.Scale;
+ Vector2 s2 = transform.Scale;
// Slerp rotation
var v1 = new Vector2(Mathf.Cos(r1), Mathf.Sin(r1));
@@ -164,36 +221,41 @@ namespace Godot
real_t dot = v1.Dot(v2);
- // Clamp dot to [-1, 1]
- dot = dot < -1.0f ? -1.0f : (dot > 1.0f ? 1.0f : dot);
+ dot = Mathf.Clamp(dot, -1.0f, 1.0f);
Vector2 v;
if (dot > 0.9995f)
{
// Linearly interpolate to avoid numerical precision issues
- v = v1.Lerp(v2, c).Normalized();
+ v = v1.Lerp(v2, weight).Normalized();
}
else
{
- real_t angle = c * Mathf.Acos(dot);
+ real_t angle = weight * Mathf.Acos(dot);
Vector2 v3 = (v2 - v1 * dot).Normalized();
v = v1 * Mathf.Cos(angle) + v3 * Mathf.Sin(angle);
}
// Extract parameters
Vector2 p1 = origin;
- Vector2 p2 = m.origin;
+ Vector2 p2 = transform.origin;
// Construct matrix
- var res = new Transform2D(Mathf.Atan2(v.y, v.x), p1.Lerp(p2, c));
- Vector2 scale = s1.Lerp(s2, c);
+ var res = new Transform2D(Mathf.Atan2(v.y, v.x), p1.Lerp(p2, weight));
+ Vector2 scale = s1.Lerp(s2, weight);
res.x *= scale;
res.y *= scale;
return res;
}
+ /// <summary>
+ /// Returns the inverse of the transform, under the assumption that
+ /// the transformation is composed of rotation and translation
+ /// (no scaling, use <see cref="AffineInverse"/> for transforms with scaling).
+ /// </summary>
+ /// <returns>The inverse matrix.</returns>
public Transform2D Inverse()
{
var inv = this;
@@ -208,6 +270,11 @@ namespace Godot
return inv;
}
+ /// <summary>
+ /// Returns the transform with the basis orthogonal (90 degrees),
+ /// and normalized axis vectors (scale of 1 or -1).
+ /// </summary>
+ /// <returns>The orthonormalized transform.</returns>
public Transform2D Orthonormalized()
{
var on = this;
@@ -225,11 +292,21 @@ namespace Godot
return on;
}
+ /// <summary>
+ /// Rotates the transform by `phi` (in radians), using matrix multiplication.
+ /// </summary>
+ /// <param name="phi">The angle to rotate, in radians.</param>
+ /// <returns>The rotated transformation matrix.</returns>
public Transform2D Rotated(real_t phi)
{
return this * new Transform2D(phi, new Vector2());
}
+ /// <summary>
+ /// Scales the transform by the given scaling factor, using matrix multiplication.
+ /// </summary>
+ /// <param name="scale">The scale to introduce.</param>
+ /// <returns>The scaled transformation matrix.</returns>
public Transform2D Scaled(Vector2 scale)
{
var copy = this;
@@ -257,6 +334,15 @@ namespace Godot
return this[0, 1] * with[0] + this[1, 1] * with[1];
}
+ /// <summary>
+ /// Translates the transform by the given `offset`,
+ /// relative to the transform's basis vectors.
+ ///
+ /// Unlike <see cref="Rotated"/> and <see cref="Scaled"/>,
+ /// this does not use matrix multiplication.
+ /// </summary>
+ /// <param name="offset">The offset to translate by.</param>
+ /// <returns>The translated matrix.</returns>
public Transform2D Translated(Vector2 offset)
{
var copy = this;
@@ -264,11 +350,21 @@ namespace Godot
return copy;
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by this transformation matrix.
+ /// </summary>
+ /// <param name="v">A vector to transform.</param>
+ /// <returns>The transformed vector.</returns>
public Vector2 Xform(Vector2 v)
{
return new Vector2(Tdotx(v), Tdoty(v)) + origin;
}
+ /// <summary>
+ /// Returns a vector transformed (multiplied) by the inverse transformation matrix.
+ /// </summary>
+ /// <param name="v">A vector to inversely transform.</param>
+ /// <returns>The inversely transformed vector.</returns>
public Vector2 XformInv(Vector2 v)
{
Vector2 vInv = v - origin;
@@ -280,11 +376,30 @@ namespace Godot
private static readonly Transform2D _flipX = new Transform2D(-1, 0, 0, 1, 0, 0);
private static readonly Transform2D _flipY = new Transform2D(1, 0, 0, -1, 0, 0);
- public static Transform2D Identity => _identity;
- public static Transform2D FlipX => _flipX;
- public static Transform2D FlipY => _flipY;
+ /// <summary>
+ /// The identity transform, with no translation, rotation, or scaling applied.
+ /// This is used as a replacement for `Transform2D()` in GDScript.
+ /// Do not use `new Transform2D()` with no arguments in C#, because it sets all values to zero.
+ /// </summary>
+ /// <value>Equivalent to `new Transform2D(Vector2.Right, Vector2.Down, Vector2.Zero)`.</value>
+ public static Transform2D Identity { get { return _identity; } }
+ /// <summary>
+ /// The transform that will flip something along the X axis.
+ /// </summary>
+ /// <value>Equivalent to `new Transform2D(Vector2.Left, Vector2.Down, Vector2.Zero)`.</value>
+ public static Transform2D FlipX { get { return _flipX; } }
+ /// <summary>
+ /// The transform that will flip something along the Y axis.
+ /// </summary>
+ /// <value>Equivalent to `new Transform2D(Vector2.Right, Vector2.Up, Vector2.Zero)`.</value>
+ public static Transform2D FlipY { get { return _flipY; } }
- // Constructors
+ /// <summary>
+ /// Constructs a transformation matrix from 3 vectors (matrix columns).
+ /// </summary>
+ /// <param name="xAxis">The X vector, or column index 0.</param>
+ /// <param name="yAxis">The Y vector, or column index 1.</param>
+ /// <param name="originPos">The origin vector, or column index 2.</param>
public Transform2D(Vector2 xAxis, Vector2 yAxis, Vector2 originPos)
{
x = xAxis;
@@ -292,7 +407,16 @@ namespace Godot
origin = originPos;
}
- // Arguments are named such that xy is equal to calling x.y
+ /// <summary>
+ /// Constructs a transformation matrix from the given components.
+ /// Arguments are named such that xy is equal to calling x.y
+ /// </summary>
+ /// <param name="xx">The X component of the X column vector, accessed via `t.x.x` or `[0][0]`</param>
+ /// <param name="xy">The Y component of the X column vector, accessed via `t.x.y` or `[0][1]`</param>
+ /// <param name="yx">The X component of the Y column vector, accessed via `t.y.x` or `[1][0]`</param>
+ /// <param name="yy">The Y component of the Y column vector, accessed via `t.y.y` or `[1][1]`</param>
+ /// <param name="ox">The X component of the origin vector, accessed via `t.origin.x` or `[2][0]`</param>
+ /// <param name="oy">The Y component of the origin vector, accessed via `t.origin.y` or `[2][1]`</param>
public Transform2D(real_t xx, real_t xy, real_t yx, real_t yy, real_t ox, real_t oy)
{
x = new Vector2(xx, xy);
@@ -300,6 +424,11 @@ namespace Godot
origin = new Vector2(ox, oy);
}
+ /// <summary>
+ /// Constructs a transformation matrix from a rotation value and origin vector.
+ /// </summary>
+ /// <param name="rot">The rotation of the new transform, in radians.</param>
+ /// <param name="pos">The origin vector, or column index 2.</param>
public Transform2D(real_t rot, Vector2 pos)
{
x.x = y.y = Mathf.Cos(rot);
@@ -345,6 +474,12 @@ namespace Godot
return x.Equals(other.x) && y.Equals(other.y) && origin.Equals(other.origin);
}
+ /// <summary>
+ /// Returns true if this transform and `other` are approximately equal, by running
+ /// <see cref="Vector2.IsEqualApprox(Vector2)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other transform to compare.</param>
+ /// <returns>Whether or not the matrices are approximately equal.</returns>
public bool IsEqualApprox(Transform2D other)
{
return x.IsEqualApprox(other.x) && y.IsEqualApprox(other.y) && origin.IsEqualApprox(other.origin);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
index 7e4804f9fd..6279ea1ace 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
@@ -21,15 +21,29 @@ namespace Godot
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
+ /// <summary>
+ /// Enumerated index values for the axes.
+ /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>.
+ /// </summary>
public enum Axis
{
X = 0,
Y
}
+ /// <summary>
+ /// The vector's X component. Also accessible by using the index position `[0]`.
+ /// </summary>
public real_t x;
+ /// <summary>
+ /// The vector's Y component. Also accessible by using the index position `[1]`.
+ /// </summary>
public real_t y;
+ /// <summary>
+ /// Access vector components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`.</value>
public real_t this[int index]
{
get
@@ -76,41 +90,80 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns a new vector with all components in absolute values (i.e. positive).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Abs(real_t)"/> called on each component.</returns>
public Vector2 Abs()
{
return new Vector2(Mathf.Abs(x), Mathf.Abs(y));
}
+ /// <summary>
+ /// Returns this vector's angle with respect to the X axis, or (1, 0) vector, in radians.
+ ///
+ /// Equivalent to the result of <see cref="Mathf.Atan2(real_t, real_t)"/> when
+ /// called with the vector's `y` and `x` as parameters: `Mathf.Atan2(v.y, v.x)`.
+ /// </summary>
+ /// <returns>The angle of this vector, in radians.</returns>
public real_t Angle()
{
return Mathf.Atan2(y, x);
}
+ /// <summary>
+ /// Returns the angle to the given vector, in radians.
+ /// </summary>
+ /// <param name="to">The other vector to compare this vector to.</param>
+ /// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleTo(Vector2 to)
{
return Mathf.Atan2(Cross(to), Dot(to));
}
+ /// <summary>
+ /// Returns the angle between the line connecting the two points and the X axis, in radians.
+ /// </summary>
+ /// <param name="to">The other vector to compare this vector to.</param>
+ /// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleToPoint(Vector2 to)
{
return Mathf.Atan2(y - to.y, x - to.x);
}
+ /// <summary>
+ /// Returns the aspect ratio of this vector, the ratio of `x` to `y`.
+ /// </summary>
+ /// <returns>The `x` component divided by the `y` component.</returns>
public real_t Aspect()
{
return x / y;
}
- public Vector2 Bounce(Vector2 n)
+ /// <summary>
+ /// Returns the vector "bounced off" from a plane defined by the given normal.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to bounce off. Must be normalized.</param>
+ /// <returns>The bounced vector.</returns>
+ public Vector2 Bounce(Vector2 normal)
{
- return -Reflect(n);
+ return -Reflect(normal);
}
+ /// <summary>
+ /// Returns a new vector with all components rounded up (towards positive infinity).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Ceil"/> called on each component.</returns>
public Vector2 Ceil()
{
return new Vector2(Mathf.Ceil(x), Mathf.Ceil(y));
}
+ /// <summary>
+ /// Returns the vector with a maximum length by limiting its length to `length`.
+ /// </summary>
+ /// <param name="length">The length to limit to.</param>
+ /// <returns>The vector with its length limited.</returns>
public Vector2 Clamped(real_t length)
{
var v = this;
@@ -125,18 +178,32 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns the cross product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector.</param>
+ /// <returns>The cross product value.</returns>
public real_t Cross(Vector2 b)
{
return x * b.y - y * b.x;
}
- public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t t)
+ /// <summary>
+ /// Performs a cubic interpolation between vectors `preA`, this vector, `b`, and `postB`, by the given amount `t`.
+ /// </summary>
+ /// <param name="b">The destination vector.</param>
+ /// <param name="preA">A vector before this vector.</param>
+ /// <param name="postB">A vector after `b`.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The interpolated vector.</returns>
+ public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t weight)
{
- var p0 = preA;
- var p1 = this;
- var p2 = b;
- var p3 = postB;
+ Vector2 p0 = preA;
+ Vector2 p1 = this;
+ Vector2 p2 = b;
+ Vector2 p3 = postB;
+ real_t t = weight;
real_t t2 = t * t;
real_t t3 = t2 * t;
@@ -146,46 +213,102 @@ namespace Godot
(-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
}
+ /// <summary>
+ /// Returns the normalized vector pointing from this vector to `b`.
+ /// </summary>
+ /// <param name="b">The other vector to point towards.</param>
+ /// <returns>The direction from this vector to `b`.</returns>
public Vector2 DirectionTo(Vector2 b)
{
return new Vector2(b.x - x, b.y - y).Normalized();
}
+ /// <summary>
+ /// Returns the squared distance between this vector and `to`.
+ /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if
+ /// you need to compare vectors or need the squared distance for some formula.
+ /// </summary>
+ /// <param name="to">The other vector to use.</param>
+ /// <returns>The squared distance between the two vectors.</returns>
public real_t DistanceSquaredTo(Vector2 to)
{
return (x - to.x) * (x - to.x) + (y - to.y) * (y - to.y);
}
+ /// <summary>
+ /// Returns the distance between this vector and `to`.
+ /// </summary>
+ /// <param name="to">The other vector to use.</param>
+ /// <returns>The distance between the two vectors.</returns>
public real_t DistanceTo(Vector2 to)
{
return Mathf.Sqrt((x - to.x) * (x - to.x) + (y - to.y) * (y - to.y));
}
+ /// <summary>
+ /// Returns the dot product of this vector and `with`.
+ /// </summary>
+ /// <param name="with">The other vector to use.</param>
+ /// <returns>The dot product of the two vectors.</returns>
public real_t Dot(Vector2 with)
{
return x * with.x + y * with.y;
}
+ /// <summary>
+ /// Returns a new vector with all components rounded down (towards negative infinity).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Floor"/> called on each component.</returns>
public Vector2 Floor()
{
return new Vector2(Mathf.Floor(x), Mathf.Floor(y));
}
+ /// <summary>
+ /// Returns the inverse of this vector. This is the same as `new Vector2(1 / v.x, 1 / v.y)`.
+ /// </summary>
+ /// <returns>The inverse of this vector.</returns>
+ public Vector2 Inverse()
+ {
+ return new Vector2(1 / x, 1 / y);
+ }
+
+ /// <summary>
+ /// Returns true if the vector is normalized, and false otherwise.
+ /// </summary>
+ /// <returns>A bool indicating whether or not the vector is normalized.</returns>
public bool IsNormalized()
{
return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon;
}
+ /// <summary>
+ /// Returns the length (magnitude) of this vector.
+ /// </summary>
+ /// <returns>The length of this vector.</returns>
public real_t Length()
{
return Mathf.Sqrt(x * x + y * y);
}
+ /// <summary>
+ /// Returns the squared length (squared magnitude) of this vector.
+ /// This method runs faster than <see cref="Length"/>, so prefer it if
+ /// you need to compare vectors or need the squared length for some formula.
+ /// </summary>
+ /// <returns>The squared length of this vector.</returns>
public real_t LengthSquared()
{
return x * x + y * y;
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this vector and `to` by amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
public Vector2 Lerp(Vector2 to, real_t weight)
{
return new Vector2
@@ -195,6 +318,13 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this vector and `to` by the vector amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation.</param>
+ /// <param name="weight">A vector with components on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
public Vector2 Lerp(Vector2 to, Vector2 weight)
{
return new Vector2
@@ -204,6 +334,32 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the axis of the vector's largest value. See <see cref="Axis"/>.
+ /// If both components are equal, this method returns <see cref="Axis.X"/>.
+ /// </summary>
+ /// <returns>The index of the largest axis.</returns>
+ public Axis MaxAxis()
+ {
+ return x < y ? Axis.Y : Axis.X;
+ }
+
+ /// <summary>
+ /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>.
+ /// If both components are equal, this method returns <see cref="Axis.Y"/>.
+ /// </summary>
+ /// <returns>The index of the smallest axis.</returns>
+ public Axis MinAxis()
+ {
+ return x < y ? Axis.X : Axis.Y;
+ }
+
+ /// <summary>
+ /// Moves this vector toward `to` by the fixed `delta` amount.
+ /// </summary>
+ /// <param name="to">The vector to move towards.</param>
+ /// <param name="delta">The amount to move towards by.</param>
+ /// <returns>The resulting vector.</returns>
public Vector2 MoveToward(Vector2 to, real_t delta)
{
var v = this;
@@ -212,6 +368,10 @@ namespace Godot
return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta;
}
+ /// <summary>
+ /// Returns the vector scaled to unit length. Equivalent to `v / v.Length()`.
+ /// </summary>
+ /// <returns>A normalized version of the vector.</returns>
public Vector2 Normalized()
{
var v = this;
@@ -219,6 +379,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(real_t, real_t)"/> of this vector's components and `mod`.
+ /// </summary>
+ /// <param name="mod">A value representing the divisor of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(real_t, real_t)"/> by `mod`.</returns>
public Vector2 PosMod(real_t mod)
{
Vector2 v;
@@ -227,6 +392,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(real_t, real_t)"/> of this vector's components and `modv`'s components.
+ /// </summary>
+ /// <param name="modv">A vector representing the divisors of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(real_t, real_t)"/> by `modv`'s components.</returns>
public Vector2 PosMod(Vector2 modv)
{
Vector2 v;
@@ -235,27 +405,62 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns this vector projected onto another vector `b`.
+ /// </summary>
+ /// <param name="onNormal">The vector to project onto.</param>
+ /// <returns>The projected vector.</returns>
public Vector2 Project(Vector2 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
}
- public Vector2 Reflect(Vector2 n)
+ /// <summary>
+ /// Returns this vector reflected from a plane defined by the given `normal`.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to reflect from. Must be normalized.</param>
+ /// <returns>The reflected vector.</returns>
+ public Vector2 Reflect(Vector2 normal)
{
- return 2 * Dot(n) * n - this;
+#if DEBUG
+ if (!normal.IsNormalized())
+ {
+ throw new ArgumentException("Argument is not normalized", nameof(normal));
+ }
+#endif
+ return 2 * Dot(normal) * normal - this;
}
+ /// <summary>
+ /// Rotates this vector by `phi` radians.
+ /// </summary>
+ /// <param name="phi">The angle to rotate by, in radians.</param>
+ /// <returns>The rotated vector.</returns>
public Vector2 Rotated(real_t phi)
{
- real_t rads = Angle() + phi;
- return new Vector2(Mathf.Cos(rads), Mathf.Sin(rads)) * Length();
+ real_t sine = Mathf.Sin(phi);
+ real_t cosi = Mathf.Cos(phi);
+ return new Vector2(
+ x * cosi - y * sine,
+ x * sine + y * cosi);
}
+ /// <summary>
+ /// Returns this vector with all components rounded to the nearest integer,
+ /// with halfway cases rounded towards the nearest multiple of two.
+ /// </summary>
+ /// <returns>The rounded vector.</returns>
public Vector2 Round()
{
return new Vector2(Mathf.Round(x), Mathf.Round(y));
}
+ /// <summary>
+ /// Returns a vector with each component set to one or negative one, depending
+ /// on the signs of this vector's components, or zero if the component is zero,
+ /// by calling <see cref="Mathf.Sign(real_t)"/> on each component.
+ /// </summary>
+ /// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns>
public Vector2 Sign()
{
Vector2 v;
@@ -264,23 +469,57 @@ namespace Godot
return v;
}
- public Vector2 Slerp(Vector2 b, real_t t)
+ /// <summary>
+ /// Returns the result of the spherical linear interpolation between
+ /// this vector and `to` by amount `weight`.
+ ///
+ /// Note: Both vectors must be normalized.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation. Must be normalized.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
+ public Vector2 Slerp(Vector2 to, real_t weight)
{
- real_t theta = AngleTo(b);
- return Rotated(theta * t);
+#if DEBUG
+ if (!IsNormalized())
+ {
+ throw new InvalidOperationException("Vector2.Slerp: From vector is not normalized.");
+ }
+ if (!to.IsNormalized())
+ {
+ throw new InvalidOperationException("Vector2.Slerp: `to` is not normalized.");
+ }
+#endif
+ return Rotated(AngleTo(to) * weight);
}
- public Vector2 Slide(Vector2 n)
+ /// <summary>
+ /// Returns this vector slid along a plane defined by the given normal.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to slide on.</param>
+ /// <returns>The slid vector.</returns>
+ public Vector2 Slide(Vector2 normal)
{
- return this - n * Dot(n);
+ return this - normal * Dot(normal);
}
- public Vector2 Snapped(Vector2 by)
+ /// <summary>
+ /// Returns this vector with each component snapped to the nearest multiple of `step`.
+ /// This can also be used to round to an arbitrary number of decimals.
+ /// </summary>
+ /// <param name="step">A vector value representing the step size to snap to.</param>
+ /// <returns>The snapped vector.</returns>
+ public Vector2 Snapped(Vector2 step)
{
- return new Vector2(Mathf.Stepify(x, by.x), Mathf.Stepify(y, by.y));
+ return new Vector2(Mathf.Snapped(x, step.x), Mathf.Snapped(y, step.y));
}
- public Vector2 Tangent()
+ /// <summary>
+ /// Returns a perpendicular vector rotated 90 degrees counter-clockwise
+ /// compared to the original, with the same length.
+ /// </summary>
+ /// <returns>The perpendicular vector.</returns>
+ public Vector2 Perpendicular()
{
return new Vector2(y, -x);
}
@@ -288,7 +527,6 @@ namespace Godot
// Constants
private static readonly Vector2 _zero = new Vector2(0, 0);
private static readonly Vector2 _one = new Vector2(1, 1);
- private static readonly Vector2 _negOne = new Vector2(-1, -1);
private static readonly Vector2 _inf = new Vector2(Mathf.Inf, Mathf.Inf);
private static readonly Vector2 _up = new Vector2(0, -1);
@@ -296,22 +534,58 @@ namespace Godot
private static readonly Vector2 _right = new Vector2(1, 0);
private static readonly Vector2 _left = new Vector2(-1, 0);
+ /// <summary>
+ /// Zero vector, a vector with all components set to `0`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(0, 0)`</value>
public static Vector2 Zero { get { return _zero; } }
- public static Vector2 NegOne { get { return _negOne; } }
+ /// <summary>
+ /// One vector, a vector with all components set to `1`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(1, 1)`</value>
public static Vector2 One { get { return _one; } }
+ /// <summary>
+ /// Infinity vector, a vector with all components set to `Mathf.Inf`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(Mathf.Inf, Mathf.Inf)`</value>
public static Vector2 Inf { get { return _inf; } }
+ /// <summary>
+ /// Up unit vector. Y is down in 2D, so this vector points -Y.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(0, -1)`</value>
public static Vector2 Up { get { return _up; } }
+ /// <summary>
+ /// Down unit vector. Y is down in 2D, so this vector points +Y.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(0, 1)`</value>
public static Vector2 Down { get { return _down; } }
+ /// <summary>
+ /// Right unit vector. Represents the direction of right.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(1, 0)`</value>
public static Vector2 Right { get { return _right; } }
+ /// <summary>
+ /// Left unit vector. Represents the direction of left.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2(-1, 0)`</value>
public static Vector2 Left { get { return _left; } }
- // Constructors
+ /// <summary>
+ /// Constructs a new <see cref="Vector2"/> with the given components.
+ /// </summary>
+ /// <param name="x">The vector's X component.</param>
+ /// <param name="y">The vector's Y component.</param>
public Vector2(real_t x, real_t y)
{
this.x = x;
this.y = y;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector2"/> from an existing <see cref="Vector2"/>.
+ /// </summary>
+ /// <param name="v">The existing <see cref="Vector2"/>.</param>
public Vector2(Vector2 v)
{
x = v.x;
@@ -400,41 +674,37 @@ namespace Godot
public static bool operator <(Vector2 left, Vector2 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
return left.y < right.y;
}
-
return left.x < right.x;
}
public static bool operator >(Vector2 left, Vector2 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
return left.y > right.y;
}
-
return left.x > right.x;
}
public static bool operator <=(Vector2 left, Vector2 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
return left.y <= right.y;
}
-
return left.x <= right.x;
}
public static bool operator >=(Vector2 left, Vector2 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
return left.y >= right.y;
}
-
return left.x >= right.x;
}
@@ -444,7 +714,6 @@ namespace Godot
{
return Equals((Vector2)obj);
}
-
return false;
}
@@ -453,6 +722,12 @@ namespace Godot
return x == other.x && y == other.y;
}
+ /// <summary>
+ /// Returns true if this vector and `other` are approximately equal, by running
+ /// <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other vector to compare.</param>
+ /// <returns>Whether or not the vectors are approximately equal.</returns>
public bool IsEqualApprox(Vector2 other)
{
return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
index 7dc22d7918..8dd9ab2f0d 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs
@@ -16,15 +16,29 @@ namespace Godot
[StructLayout(LayoutKind.Sequential)]
public struct Vector2i : IEquatable<Vector2i>
{
+ /// <summary>
+ /// Enumerated index values for the axes.
+ /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>.
+ /// </summary>
public enum Axis
{
X = 0,
Y
}
+ /// <summary>
+ /// The vector's X component. Also accessible by using the index position `[0]`.
+ /// </summary>
public int x;
+ /// <summary>
+ /// The vector's Y component. Also accessible by using the index position `[1]`.
+ /// </summary>
public int y;
+ /// <summary>
+ /// Access vector components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`.</value>
public int this[int index]
{
get
@@ -55,56 +69,102 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns a new vector with all components in absolute values (i.e. positive).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns>
public Vector2i Abs()
{
return new Vector2i(Mathf.Abs(x), Mathf.Abs(y));
}
+ /// <summary>
+ /// Returns this vector's angle with respect to the X axis, or (1, 0) vector, in radians.
+ ///
+ /// Equivalent to the result of <see cref="Mathf.Atan2(real_t, real_t)"/> when
+ /// called with the vector's `y` and `x` as parameters: `Mathf.Atan2(v.y, v.x)`.
+ /// </summary>
+ /// <returns>The angle of this vector, in radians.</returns>
public real_t Angle()
{
return Mathf.Atan2(y, x);
}
+ /// <summary>
+ /// Returns the angle to the given vector, in radians.
+ /// </summary>
+ /// <param name="to">The other vector to compare this vector to.</param>
+ /// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleTo(Vector2i to)
{
return Mathf.Atan2(Cross(to), Dot(to));
}
+ /// <summary>
+ /// Returns the angle between the line connecting the two points and the X axis, in radians.
+ /// </summary>
+ /// <param name="to">The other vector to compare this vector to.</param>
+ /// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleToPoint(Vector2i to)
{
return Mathf.Atan2(y - to.y, x - to.x);
}
+ /// <summary>
+ /// Returns the aspect ratio of this vector, the ratio of `x` to `y`.
+ /// </summary>
+ /// <returns>The `x` component divided by the `y` component.</returns>
public real_t Aspect()
{
return x / (real_t)y;
}
- public Vector2i Bounce(Vector2i n)
- {
- return -Reflect(n);
- }
-
+ /// <summary>
+ /// Returns the cross product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector.</param>
+ /// <returns>The cross product vector.</returns>
public int Cross(Vector2i b)
{
return x * b.y - y * b.x;
}
+ /// <summary>
+ /// Returns the squared distance between this vector and `b`.
+ /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if
+ /// you need to compare vectors or need the squared distance for some formula.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The squared distance between the two vectors.</returns>
public int DistanceSquaredTo(Vector2i b)
{
return (b - this).LengthSquared();
}
+ /// <summary>
+ /// Returns the distance between this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The distance between the two vectors.</returns>
public real_t DistanceTo(Vector2i b)
{
return (b - this).Length();
}
+ /// <summary>
+ /// Returns the dot product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The dot product of the two vectors.</returns>
public int Dot(Vector2i b)
{
return x * b.x + y * b.y;
}
+ /// <summary>
+ /// Returns the length (magnitude) of this vector.
+ /// </summary>
+ /// <returns>The length of this vector.</returns>
public real_t Length()
{
int x2 = x * x;
@@ -113,6 +173,12 @@ namespace Godot
return Mathf.Sqrt(x2 + y2);
}
+ /// <summary>
+ /// Returns the squared length (squared magnitude) of this vector.
+ /// This method runs faster than <see cref="Length"/>, so prefer it if
+ /// you need to compare vectors or need the squared length for some formula.
+ /// </summary>
+ /// <returns>The squared length of this vector.</returns>
public int LengthSquared()
{
int x2 = x * x;
@@ -121,16 +187,31 @@ namespace Godot
return x2 + y2;
}
+ /// <summary>
+ /// Returns the axis of the vector's largest value. See <see cref="Axis"/>.
+ /// If both components are equal, this method returns <see cref="Axis.X"/>.
+ /// </summary>
+ /// <returns>The index of the largest axis.</returns>
public Axis MaxAxis()
{
return x < y ? Axis.Y : Axis.X;
}
+ /// <summary>
+ /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>.
+ /// If both components are equal, this method returns <see cref="Axis.Y"/>.
+ /// </summary>
+ /// <returns>The index of the smallest axis.</returns>
public Axis MinAxis()
{
- return x > y ? Axis.Y : Axis.X;
+ return x < y ? Axis.X : Axis.Y;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `mod`.
+ /// </summary>
+ /// <param name="mod">A value representing the divisor of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `mod`.</returns>
public Vector2i PosMod(int mod)
{
Vector2i v = this;
@@ -139,6 +220,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `modv`'s components.
+ /// </summary>
+ /// <param name="modv">A vector representing the divisors of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `modv`'s components.</returns>
public Vector2i PosMod(Vector2i modv)
{
Vector2i v = this;
@@ -147,11 +233,12 @@ namespace Godot
return v;
}
- public Vector2i Reflect(Vector2i n)
- {
- return 2 * Dot(n) * n - this;
- }
-
+ /// <summary>
+ /// Returns a vector with each component set to one or negative one, depending
+ /// on the signs of this vector's components, or zero if the component is zero,
+ /// by calling <see cref="Mathf.Sign(int)"/> on each component.
+ /// </summary>
+ /// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns>
public Vector2i Sign()
{
Vector2i v = this;
@@ -160,9 +247,14 @@ namespace Godot
return v;
}
- public Vector2i Tangent()
+ /// <summary>
+ /// Returns a vector rotated 90 degrees counter-clockwise
+ /// compared to the original, with the same length.
+ /// </summary>
+ /// <returns>The perpendicular vector.</returns>
+ public Vector2 Perpendicular()
{
- return new Vector2i(y, -x);
+ return new Vector2(y, -x);
}
// Constants
@@ -174,25 +266,64 @@ namespace Godot
private static readonly Vector2i _right = new Vector2i(1, 0);
private static readonly Vector2i _left = new Vector2i(-1, 0);
+ /// <summary>
+ /// Zero vector, a vector with all components set to `0`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(0, 0)`</value>
public static Vector2i Zero { get { return _zero; } }
+ /// <summary>
+ /// One vector, a vector with all components set to `1`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(1, 1)`</value>
public static Vector2i One { get { return _one; } }
+ /// <summary>
+ /// Up unit vector. Y is down in 2D, so this vector points -Y.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(0, -1)`</value>
public static Vector2i Up { get { return _up; } }
+ /// <summary>
+ /// Down unit vector. Y is down in 2D, so this vector points +Y.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(0, 1)`</value>
public static Vector2i Down { get { return _down; } }
+ /// <summary>
+ /// Right unit vector. Represents the direction of right.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(1, 0)`</value>
public static Vector2i Right { get { return _right; } }
+ /// <summary>
+ /// Left unit vector. Represents the direction of left.
+ /// </summary>
+ /// <value>Equivalent to `new Vector2i(-1, 0)`</value>
public static Vector2i Left { get { return _left; } }
- // Constructors
+ /// <summary>
+ /// Constructs a new <see cref="Vector2i"/> with the given components.
+ /// </summary>
+ /// <param name="x">The vector's X component.</param>
+ /// <param name="y">The vector's Y component.</param>
public Vector2i(int x, int y)
{
this.x = x;
this.y = y;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2i"/>.
+ /// </summary>
+ /// <param name="vi">The existing <see cref="Vector2i"/>.</param>
public Vector2i(Vector2i vi)
{
this.x = vi.x;
this.y = vi.y;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector2i"/> from an existing <see cref="Vector2"/>
+ /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
+ /// </summary>
+ /// <param name="v">The <see cref="Vector2"/> to convert.</param>
public Vector2i(Vector2 v)
{
this.x = Mathf.RoundToInt(v.x);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
index b26e17ecba..42dbdf25c3 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
@@ -21,6 +21,10 @@ namespace Godot
[StructLayout(LayoutKind.Sequential)]
public struct Vector3 : IEquatable<Vector3>
{
+ /// <summary>
+ /// Enumerated index values for the axes.
+ /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>.
+ /// </summary>
public enum Axis
{
X = 0,
@@ -28,10 +32,23 @@ namespace Godot
Z
}
+ /// <summary>
+ /// The vector's X component. Also accessible by using the index position `[0]`.
+ /// </summary>
public real_t x;
+ /// <summary>
+ /// The vector's Y component. Also accessible by using the index position `[1]`.
+ /// </summary>
public real_t y;
+ /// <summary>
+ /// The vector's Z component. Also accessible by using the index position `[2]`.
+ /// </summary>
public real_t z;
+ /// <summary>
+ /// Access vector components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`.</value>
public real_t this[int index]
{
get
@@ -84,26 +101,49 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns a new vector with all components in absolute values (i.e. positive).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Abs(real_t)"/> called on each component.</returns>
public Vector3 Abs()
{
return new Vector3(Mathf.Abs(x), Mathf.Abs(y), Mathf.Abs(z));
}
+ /// <summary>
+ /// Returns the minimum angle to the given vector, in radians.
+ /// </summary>
+ /// <param name="to">The other vector to compare this vector to.</param>
+ /// <returns>The angle between the two vectors, in radians.</returns>
public real_t AngleTo(Vector3 to)
{
return Mathf.Atan2(Cross(to).Length(), Dot(to));
}
- public Vector3 Bounce(Vector3 n)
+ /// <summary>
+ /// Returns this vector "bounced off" from a plane defined by the given normal.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to bounce off. Must be normalized.</param>
+ /// <returns>The bounced vector.</returns>
+ public Vector3 Bounce(Vector3 normal)
{
- return -Reflect(n);
+ return -Reflect(normal);
}
+ /// <summary>
+ /// Returns a new vector with all components rounded up (towards positive infinity).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Ceil"/> called on each component.</returns>
public Vector3 Ceil()
{
return new Vector3(Mathf.Ceil(x), Mathf.Ceil(y), Mathf.Ceil(z));
}
+ /// <summary>
+ /// Returns the cross product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector.</param>
+ /// <returns>The cross product vector.</returns>
public Vector3 Cross(Vector3 b)
{
return new Vector3
@@ -114,13 +154,23 @@ namespace Godot
);
}
- public Vector3 CubicInterpolate(Vector3 b, Vector3 preA, Vector3 postB, real_t t)
+ /// <summary>
+ /// Performs a cubic interpolation between vectors `preA`, this vector,
+ /// `b`, and `postB`, by the given amount `t`.
+ /// </summary>
+ /// <param name="b">The destination vector.</param>
+ /// <param name="preA">A vector before this vector.</param>
+ /// <param name="postB">A vector after `b`.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The interpolated vector.</returns>
+ public Vector3 CubicInterpolate(Vector3 b, Vector3 preA, Vector3 postB, real_t weight)
{
- var p0 = preA;
- var p1 = this;
- var p2 = b;
- var p3 = postB;
+ Vector3 p0 = preA;
+ Vector3 p1 = this;
+ Vector3 p2 = b;
+ Vector3 p3 = postB;
+ real_t t = weight;
real_t t2 = t * t;
real_t t3 = t2 * t;
@@ -131,41 +181,79 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the normalized vector pointing from this vector to `b`.
+ /// </summary>
+ /// <param name="b">The other vector to point towards.</param>
+ /// <returns>The direction from this vector to `b`.</returns>
public Vector3 DirectionTo(Vector3 b)
{
return new Vector3(b.x - x, b.y - y, b.z - z).Normalized();
}
+ /// <summary>
+ /// Returns the squared distance between this vector and `b`.
+ /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if
+ /// you need to compare vectors or need the squared distance for some formula.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The squared distance between the two vectors.</returns>
public real_t DistanceSquaredTo(Vector3 b)
{
return (b - this).LengthSquared();
}
+ /// <summary>
+ /// Returns the distance between this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The distance between the two vectors.</returns>
public real_t DistanceTo(Vector3 b)
{
return (b - this).Length();
}
+ /// <summary>
+ /// Returns the dot product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The dot product of the two vectors.</returns>
public real_t Dot(Vector3 b)
{
return x * b.x + y * b.y + z * b.z;
}
+ /// <summary>
+ /// Returns a new vector with all components rounded down (towards negative infinity).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Floor"/> called on each component.</returns>
public Vector3 Floor()
{
return new Vector3(Mathf.Floor(x), Mathf.Floor(y), Mathf.Floor(z));
}
+ /// <summary>
+ /// Returns the inverse of this vector. This is the same as `new Vector3(1 / v.x, 1 / v.y, 1 / v.z)`.
+ /// </summary>
+ /// <returns>The inverse of this vector.</returns>
public Vector3 Inverse()
{
- return new Vector3(1.0f / x, 1.0f / y, 1.0f / z);
+ return new Vector3(1 / x, 1 / y, 1 / z);
}
+ /// <summary>
+ /// Returns true if the vector is normalized, and false otherwise.
+ /// </summary>
+ /// <returns>A bool indicating whether or not the vector is normalized.</returns>
public bool IsNormalized()
{
return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon;
}
+ /// <summary>
+ /// Returns the length (magnitude) of this vector.
+ /// </summary>
+ /// <returns>The length of this vector.</returns>
public real_t Length()
{
real_t x2 = x * x;
@@ -175,6 +263,12 @@ namespace Godot
return Mathf.Sqrt(x2 + y2 + z2);
}
+ /// <summary>
+ /// Returns the squared length (squared magnitude) of this vector.
+ /// This method runs faster than <see cref="Length"/>, so prefer it if
+ /// you need to compare vectors or need the squared length for some formula.
+ /// </summary>
+ /// <returns>The squared length of this vector.</returns>
public real_t LengthSquared()
{
real_t x2 = x * x;
@@ -184,6 +278,13 @@ namespace Godot
return x2 + y2 + z2;
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this vector and `to` by amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
public Vector3 Lerp(Vector3 to, real_t weight)
{
return new Vector3
@@ -194,6 +295,13 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns the result of the linear interpolation between
+ /// this vector and `to` by the vector amount `weight`.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation.</param>
+ /// <param name="weight">A vector with components on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
public Vector3 Lerp(Vector3 to, Vector3 weight)
{
return new Vector3
@@ -204,24 +312,44 @@ 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;
- }
-
+ /// <summary>
+ /// Returns the axis of the vector's largest value. See <see cref="Axis"/>.
+ /// If all components are equal, this method returns <see cref="Axis.X"/>.
+ /// </summary>
+ /// <returns>The index of the largest axis.</returns>
public Axis MaxAxis()
{
return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X);
}
+ /// <summary>
+ /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>.
+ /// If all components are equal, this method returns <see cref="Axis.Z"/>.
+ /// </summary>
+ /// <returns>The index of the smallest axis.</returns>
public Axis MinAxis()
{
return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z);
}
+ /// <summary>
+ /// Moves this vector toward `to` by the fixed `delta` amount.
+ /// </summary>
+ /// <param name="to">The vector to move towards.</param>
+ /// <param name="delta">The amount to move towards by.</param>
+ /// <returns>The resulting vector.</returns>
+ 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;
+ }
+
+ /// <summary>
+ /// Returns the vector scaled to unit length. Equivalent to `v / v.Length()`.
+ /// </summary>
+ /// <returns>A normalized version of the vector.</returns>
public Vector3 Normalized()
{
var v = this;
@@ -229,6 +357,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns the outer product with `b`.
+ /// </summary>
+ /// <param name="b">The other vector.</param>
+ /// <returns>A <see cref="Basis"/> representing the outer product matrix.</returns>
public Basis Outer(Vector3 b)
{
return new Basis(
@@ -238,6 +371,11 @@ namespace Godot
);
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(real_t, real_t)"/> of this vector's components and `mod`.
+ /// </summary>
+ /// <param name="mod">A value representing the divisor of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(real_t, real_t)"/> by `mod`.</returns>
public Vector3 PosMod(real_t mod)
{
Vector3 v;
@@ -247,6 +385,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(real_t, real_t)"/> of this vector's components and `modv`'s components.
+ /// </summary>
+ /// <param name="modv">A vector representing the divisors of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(real_t, real_t)"/> by `modv`'s components.</returns>
public Vector3 PosMod(Vector3 modv)
{
Vector3 v;
@@ -256,30 +399,66 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns this vector projected onto another vector `b`.
+ /// </summary>
+ /// <param name="onNormal">The vector to project onto.</param>
+ /// <returns>The projected vector.</returns>
public Vector3 Project(Vector3 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
}
- public Vector3 Reflect(Vector3 n)
+ /// <summary>
+ /// Returns this vector reflected from a plane defined by the given `normal`.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to reflect from. Must be normalized.</param>
+ /// <returns>The reflected vector.</returns>
+ public Vector3 Reflect(Vector3 normal)
{
#if DEBUG
- if (!n.IsNormalized())
- throw new ArgumentException("Argument is not normalized", nameof(n));
+ if (!normal.IsNormalized())
+ {
+ throw new ArgumentException("Argument is not normalized", nameof(normal));
+ }
#endif
- return 2.0f * n * Dot(n) - this;
+ return 2.0f * Dot(normal) * normal - this;
}
- public Vector3 Round()
+ /// <summary>
+ /// Rotates this vector around a given `axis` vector by `phi` radians.
+ /// The `axis` vector must be a normalized vector.
+ /// </summary>
+ /// <param name="axis">The vector to rotate around. Must be normalized.</param>
+ /// <param name="phi">The angle to rotate by, in radians.</param>
+ /// <returns>The rotated vector.</returns>
+ public Vector3 Rotated(Vector3 axis, real_t phi)
{
- return new Vector3(Mathf.Round(x), Mathf.Round(y), Mathf.Round(z));
+#if DEBUG
+ if (!axis.IsNormalized())
+ {
+ throw new ArgumentException("Argument is not normalized", nameof(axis));
+ }
+#endif
+ return new Basis(axis, phi).Xform(this);
}
- public Vector3 Rotated(Vector3 axis, real_t phi)
+ /// <summary>
+ /// Returns this vector with all components rounded to the nearest integer,
+ /// with halfway cases rounded towards the nearest multiple of two.
+ /// </summary>
+ /// <returns>The rounded vector.</returns>
+ public Vector3 Round()
{
- return new Basis(axis, phi).Xform(this);
+ return new Vector3(Mathf.Round(x), Mathf.Round(y), Mathf.Round(z));
}
+ /// <summary>
+ /// Returns a vector with each component set to one or negative one, depending
+ /// on the signs of this vector's components, or zero if the component is zero,
+ /// by calling <see cref="Mathf.Sign(real_t)"/> on each component.
+ /// </summary>
+ /// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns>
public Vector3 Sign()
{
Vector3 v;
@@ -289,44 +468,76 @@ namespace Godot
return v;
}
- public Vector3 Slerp(Vector3 b, real_t t)
+ /// <summary>
+ /// Returns the result of the spherical linear interpolation between
+ /// this vector and `to` by amount `weight`.
+ ///
+ /// Note: Both vectors must be normalized.
+ /// </summary>
+ /// <param name="to">The destination vector for interpolation. Must be normalized.</param>
+ /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
+ /// <returns>The resulting vector of the interpolation.</returns>
+ public Vector3 Slerp(Vector3 to, real_t weight)
{
#if DEBUG
if (!IsNormalized())
- throw new InvalidOperationException("Vector3 is not normalized");
+ {
+ throw new InvalidOperationException("Vector3.Slerp: From vector is not normalized.");
+ }
+ if (!to.IsNormalized())
+ {
+ throw new InvalidOperationException("Vector3.Slerp: `to` is not normalized.");
+ }
#endif
- real_t theta = AngleTo(b);
- return Rotated(Cross(b), theta * t);
+ real_t theta = AngleTo(to);
+ return Rotated(Cross(to), theta * weight);
}
- public Vector3 Slide(Vector3 n)
+ /// <summary>
+ /// Returns this vector slid along a plane defined by the given normal.
+ /// </summary>
+ /// <param name="normal">The normal vector defining the plane to slide on.</param>
+ /// <returns>The slid vector.</returns>
+ public Vector3 Slide(Vector3 normal)
{
- return this - n * Dot(n);
+ return this - normal * Dot(normal);
}
- public Vector3 Snapped(Vector3 by)
+ /// <summary>
+ /// Returns this vector with each component snapped to the nearest multiple of `step`.
+ /// This can also be used to round to an arbitrary number of decimals.
+ /// </summary>
+ /// <param name="step">A vector value representing the step size to snap to.</param>
+ /// <returns>The snapped vector.</returns>
+ public Vector3 Snapped(Vector3 step)
{
return new Vector3
(
- Mathf.Stepify(x, by.x),
- Mathf.Stepify(y, by.y),
- Mathf.Stepify(z, by.z)
+ Mathf.Snapped(x, step.x),
+ Mathf.Snapped(y, step.y),
+ Mathf.Snapped(z, step.z)
);
}
+ /// <summary>
+ /// Returns a diagonal matrix with the vector as main diagonal.
+ ///
+ /// This is equivalent to a Basis with no rotation or shearing and
+ /// this vector's components set as the scale.
+ /// </summary>
+ /// <returns>A Basis with the vector as its main diagonal.</returns>
public Basis ToDiagonalMatrix()
{
return new Basis(
- x, 0f, 0f,
- 0f, y, 0f,
- 0f, 0f, z
+ x, 0, 0,
+ 0, y, 0,
+ 0, 0, z
);
}
// Constants
private static readonly Vector3 _zero = new Vector3(0, 0, 0);
private static readonly Vector3 _one = new Vector3(1, 1, 1);
- private static readonly Vector3 _negOne = new Vector3(-1, -1, -1);
private static readonly Vector3 _inf = new Vector3(Mathf.Inf, Mathf.Inf, Mathf.Inf);
private static readonly Vector3 _up = new Vector3(0, 1, 0);
@@ -336,25 +547,74 @@ namespace Godot
private static readonly Vector3 _forward = new Vector3(0, 0, -1);
private static readonly Vector3 _back = new Vector3(0, 0, 1);
+ /// <summary>
+ /// Zero vector, a vector with all components set to `0`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(0, 0, 0)`</value>
public static Vector3 Zero { get { return _zero; } }
+ /// <summary>
+ /// One vector, a vector with all components set to `1`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(1, 1, 1)`</value>
public static Vector3 One { get { return _one; } }
- public static Vector3 NegOne { get { return _negOne; } }
+ /// <summary>
+ /// Infinity vector, a vector with all components set to `Mathf.Inf`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(Mathf.Inf, Mathf.Inf, Mathf.Inf)`</value>
public static Vector3 Inf { get { return _inf; } }
+ /// <summary>
+ /// Up unit vector.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(0, 1, 0)`</value>
public static Vector3 Up { get { return _up; } }
+ /// <summary>
+ /// Down unit vector.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(0, -1, 0)`</value>
public static Vector3 Down { get { return _down; } }
+ /// <summary>
+ /// Right unit vector. Represents the local direction of right,
+ /// and the global direction of east.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(1, 0, 0)`</value>
public static Vector3 Right { get { return _right; } }
+ /// <summary>
+ /// Left unit vector. Represents the local direction of left,
+ /// and the global direction of west.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(-1, 0, 0)`</value>
public static Vector3 Left { get { return _left; } }
+ /// <summary>
+ /// Forward unit vector. Represents the local direction of forward,
+ /// and the global direction of north.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(0, 0, -1)`</value>
public static Vector3 Forward { get { return _forward; } }
+ /// <summary>
+ /// Back unit vector. Represents the local direction of back,
+ /// and the global direction of south.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3(0, 0, 1)`</value>
public static Vector3 Back { get { return _back; } }
- // Constructors
+ /// <summary>
+ /// Constructs a new <see cref="Vector3"/> with the given components.
+ /// </summary>
+ /// <param name="x">The vector's X component.</param>
+ /// <param name="y">The vector's Y component.</param>
+ /// <param name="z">The vector's Z component.</param>
public Vector3(real_t x, real_t y, real_t z)
{
this.x = x;
this.y = y;
this.z = z;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector3"/> from an existing <see cref="Vector3"/>.
+ /// </summary>
+ /// <param name="v">The existing <see cref="Vector3"/>.</param>
public Vector3(Vector3 v)
{
x = v.x;
@@ -454,49 +714,53 @@ namespace Godot
public static bool operator <(Vector3 left, Vector3 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
- if (Mathf.IsEqualApprox(left.y, right.y))
+ if (left.y == right.y)
+ {
return left.z < right.z;
+ }
return left.y < right.y;
}
-
return left.x < right.x;
}
public static bool operator >(Vector3 left, Vector3 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
- if (Mathf.IsEqualApprox(left.y, right.y))
+ if (left.y == right.y)
+ {
return left.z > right.z;
+ }
return left.y > right.y;
}
-
return left.x > right.x;
}
public static bool operator <=(Vector3 left, Vector3 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
- if (Mathf.IsEqualApprox(left.y, right.y))
+ if (left.y == right.y)
+ {
return left.z <= right.z;
+ }
return left.y < right.y;
}
-
return left.x < right.x;
}
public static bool operator >=(Vector3 left, Vector3 right)
{
- if (Mathf.IsEqualApprox(left.x, right.x))
+ if (left.x == right.x)
{
- if (Mathf.IsEqualApprox(left.y, right.y))
+ if (left.y == right.y)
+ {
return left.z >= right.z;
+ }
return left.y > right.y;
}
-
return left.x > right.x;
}
@@ -515,6 +779,12 @@ namespace Godot
return x == other.x && y == other.y && z == other.z;
}
+ /// <summary>
+ /// Returns true if this vector and `other` are approximately equal, by running
+ /// <see cref="Mathf.IsEqualApprox(real_t, real_t)"/> on each component.
+ /// </summary>
+ /// <param name="other">The other vector to compare.</param>
+ /// <returns>Whether or not the vectors are approximately equal.</returns>
public bool IsEqualApprox(Vector3 other)
{
return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
index c17f900131..bf25ba9cb3 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs
@@ -16,6 +16,10 @@ namespace Godot
[StructLayout(LayoutKind.Sequential)]
public struct Vector3i : IEquatable<Vector3i>
{
+ /// <summary>
+ /// Enumerated index values for the axes.
+ /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>.
+ /// </summary>
public enum Axis
{
X = 0,
@@ -23,10 +27,23 @@ namespace Godot
Z
}
+ /// <summary>
+ /// The vector's X component. Also accessible by using the index position `[0]`.
+ /// </summary>
public int x;
+ /// <summary>
+ /// The vector's Y component. Also accessible by using the index position `[1]`.
+ /// </summary>
public int y;
+ /// <summary>
+ /// The vector's Z component. Also accessible by using the index position `[2]`.
+ /// </summary>
public int z;
+ /// <summary>
+ /// Access vector components using their index.
+ /// </summary>
+ /// <value>`[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`, `[2]` is equivalent to `.z`.</value>
public int this[int index]
{
get
@@ -62,39 +79,51 @@ namespace Godot
}
}
+ /// <summary>
+ /// Returns a new vector with all components in absolute values (i.e. positive).
+ /// </summary>
+ /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns>
public Vector3i Abs()
{
- Vector3i v = this;
- if (v.x < 0)
- {
- v.x = -v.x;
- }
- if (v.y < 0)
- {
- v.y = -v.y;
- }
- if (v.z < 0)
- {
- v.z = -v.z;
- }
- return v;
+ return new Vector3i(Mathf.Abs(x), Mathf.Abs(y), Mathf.Abs(z));
}
+ /// <summary>
+ /// Returns the squared distance between this vector and `b`.
+ /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if
+ /// you need to compare vectors or need the squared distance for some formula.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The squared distance between the two vectors.</returns>
public int DistanceSquaredTo(Vector3i b)
{
return (b - this).LengthSquared();
}
+ /// <summary>
+ /// Returns the distance between this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The distance between the two vectors.</returns>
public real_t DistanceTo(Vector3i b)
{
return (b - this).Length();
}
+ /// <summary>
+ /// Returns the dot product of this vector and `b`.
+ /// </summary>
+ /// <param name="b">The other vector to use.</param>
+ /// <returns>The dot product of the two vectors.</returns>
public int Dot(Vector3i b)
{
return x * b.x + y * b.y + z * b.z;
}
+ /// <summary>
+ /// Returns the length (magnitude) of this vector.
+ /// </summary>
+ /// <returns>The length of this vector.</returns>
public real_t Length()
{
int x2 = x * x;
@@ -104,6 +133,12 @@ namespace Godot
return Mathf.Sqrt(x2 + y2 + z2);
}
+ /// <summary>
+ /// Returns the squared length (squared magnitude) of this vector.
+ /// This method runs faster than <see cref="Length"/>, so prefer it if
+ /// you need to compare vectors or need the squared length for some formula.
+ /// </summary>
+ /// <returns>The squared length of this vector.</returns>
public int LengthSquared()
{
int x2 = x * x;
@@ -113,16 +148,31 @@ namespace Godot
return x2 + y2 + z2;
}
+ /// <summary>
+ /// Returns the axis of the vector's largest value. See <see cref="Axis"/>.
+ /// If all components are equal, this method returns <see cref="Axis.X"/>.
+ /// </summary>
+ /// <returns>The index of the largest axis.</returns>
public Axis MaxAxis()
{
return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X);
}
+ /// <summary>
+ /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>.
+ /// If all components are equal, this method returns <see cref="Axis.Z"/>.
+ /// </summary>
+ /// <returns>The index of the smallest axis.</returns>
public Axis MinAxis()
{
return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z);
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `mod`.
+ /// </summary>
+ /// <param name="mod">A value representing the divisor of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `mod`.</returns>
public Vector3i PosMod(int mod)
{
Vector3i v = this;
@@ -132,6 +182,11 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components and `modv`'s components.
+ /// </summary>
+ /// <param name="modv">A vector representing the divisors of the operation.</param>
+ /// <returns>A vector with each component <see cref="Mathf.PosMod(int, int)"/> by `modv`'s components.</returns>
public Vector3i PosMod(Vector3i modv)
{
Vector3i v = this;
@@ -141,6 +196,12 @@ namespace Godot
return v;
}
+ /// <summary>
+ /// Returns a vector with each component set to one or negative one, depending
+ /// on the signs of this vector's components, or zero if the component is zero,
+ /// by calling <see cref="Mathf.Sign(int)"/> on each component.
+ /// </summary>
+ /// <returns>A vector with all components as either `1`, `-1`, or `0`.</returns>
public Vector3i Sign()
{
Vector3i v = this;
@@ -161,29 +222,81 @@ namespace Godot
private static readonly Vector3i _forward = new Vector3i(0, 0, -1);
private static readonly Vector3i _back = new Vector3i(0, 0, 1);
+ /// <summary>
+ /// Zero vector, a vector with all components set to `0`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(0, 0, 0)`</value>
public static Vector3i Zero { get { return _zero; } }
+ /// <summary>
+ /// One vector, a vector with all components set to `1`.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(1, 1, 1)`</value>
public static Vector3i One { get { return _one; } }
+ /// <summary>
+ /// Up unit vector.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(0, 1, 0)`</value>
public static Vector3i Up { get { return _up; } }
+ /// <summary>
+ /// Down unit vector.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(0, -1, 0)`</value>
public static Vector3i Down { get { return _down; } }
+ /// <summary>
+ /// Right unit vector. Represents the local direction of right,
+ /// and the global direction of east.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(1, 0, 0)`</value>
public static Vector3i Right { get { return _right; } }
+ /// <summary>
+ /// Left unit vector. Represents the local direction of left,
+ /// and the global direction of west.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(-1, 0, 0)`</value>
public static Vector3i Left { get { return _left; } }
+ /// <summary>
+ /// Forward unit vector. Represents the local direction of forward,
+ /// and the global direction of north.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(0, 0, -1)`</value>
public static Vector3i Forward { get { return _forward; } }
+ /// <summary>
+ /// Back unit vector. Represents the local direction of back,
+ /// and the global direction of south.
+ /// </summary>
+ /// <value>Equivalent to `new Vector3i(0, 0, 1)`</value>
public static Vector3i Back { get { return _back; } }
- // Constructors
+ /// <summary>
+ /// Constructs a new <see cref="Vector3i"/> with the given components.
+ /// </summary>
+ /// <param name="x">The vector's X component.</param>
+ /// <param name="y">The vector's Y component.</param>
+ /// <param name="z">The vector's Z component.</param>
public Vector3i(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3i"/>.
+ /// </summary>
+ /// <param name="vi">The existing <see cref="Vector3i"/>.</param>
public Vector3i(Vector3i vi)
{
this.x = vi.x;
this.y = vi.y;
this.z = vi.z;
}
+
+ /// <summary>
+ /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3"/>
+ /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>.
+ /// </summary>
+ /// <param name="v">The <see cref="Vector3"/> to convert.</param>
public Vector3i(Vector3 v)
{
this.x = Mathf.RoundToInt(v.x);
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
index ba0bbd7630..86a16c17f1 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj
@@ -1,38 +1,17 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AEBF0036-DA76-4341-B651-A3F2856AB2FA}</ProjectGuid>
- <OutputType>Library</OutputType>
<OutputPath>bin/$(Configuration)</OutputPath>
+ <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RootNamespace>Godot</RootNamespace>
- <AssemblyName>GodotSharp</AssemblyName>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFramework>netstandard2.1</TargetFramework>
<DocumentationFile>$(OutputPath)/$(AssemblyName).xml</DocumentationFile>
- <BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath>
+ <EnableDefaultItems>false</EnableDefaultItems>
</PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>portable</DebugType>
- <Optimize>false</Optimize>
- <DefineConstants>$(GodotDefineConstants);GODOT;DEBUG;</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <ConsolePause>false</ConsolePause>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>portable</DebugType>
- <Optimize>true</Optimize>
- <DefineConstants>$(GodotDefineConstants);GODOT;</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <ConsolePause>false</ConsolePause>
+ <PropertyGroup>
+ <DefineConstants>$(DefineConstants);GODOT</DefineConstants>
</PropertyGroup>
<ItemGroup>
- <Reference Include="System" />
- </ItemGroup>
- <ItemGroup>
<Compile Include="Core\AABB.cs" />
<Compile Include="Core\Array.cs" />
<Compile Include="Core\Attributes\ExportAttribute.cs" />
@@ -52,6 +31,7 @@
<Compile Include="Core\Extensions\NodeExtensions.cs" />
<Compile Include="Core\Extensions\ObjectExtensions.cs" />
<Compile Include="Core\Extensions\ResourceLoaderExtensions.cs" />
+ <Compile Include="Core\Extensions\SceneTreeExtensions.cs" />
<Compile Include="Core\GD.cs" />
<Compile Include="Core\GodotSynchronizationContext.cs" />
<Compile Include="Core\GodotTaskScheduler.cs" />
@@ -88,5 +68,4 @@
Fortunately code completion, go to definition and such still work.
-->
<Import Project="Generated\GeneratedIncludes.props" />
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Properties/AssemblyInfo.cs b/modules/mono/glue/GodotSharp/GodotSharp/Properties/AssemblyInfo.cs
index f84e0183f6..da6f293871 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Properties/AssemblyInfo.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Properties/AssemblyInfo.cs
@@ -1,27 +1,3 @@
-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("GodotSharp")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("")]
-[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("")]
[assembly: InternalsVisibleTo("GodotSharpEditor")]
diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
index 22853797c1..a8c4ba96b5 100644
--- a/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
+++ b/modules/mono/glue/GodotSharp/GodotSharpEditor/GodotSharpEditor.csproj
@@ -1,45 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8FBEC238-D944-4074-8548-B3B524305905}</ProjectGuid>
- <OutputType>Library</OutputType>
<OutputPath>bin/$(Configuration)</OutputPath>
+ <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<RootNamespace>Godot</RootNamespace>
- <AssemblyName>GodotSharpEditor</AssemblyName>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFramework>netstandard2.1</TargetFramework>
<DocumentationFile>$(OutputPath)/$(AssemblyName).xml</DocumentationFile>
- <BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath>
+ <EnableDefaultItems>false</EnableDefaultItems>
</PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>portable</DebugType>
- <Optimize>false</Optimize>
- <DefineConstants>$(GodotDefineConstants);GODOT;DEBUG;</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <ConsolePause>false</ConsolePause>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>portable</DebugType>
- <Optimize>true</Optimize>
- <DefineConstants>$(GodotDefineConstants);GODOT;</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <ConsolePause>false</ConsolePause>
+ <PropertyGroup>
+ <DefineConstants>$(DefineConstants);GODOT</DefineConstants>
</PropertyGroup>
<ItemGroup>
- <Reference Include="System" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="Properties\AssemblyInfo.cs" />
- </ItemGroup>
- <Import Project="Generated\GeneratedIncludes.props" />
- <ItemGroup>
<ProjectReference Include="..\GodotSharp\GodotSharp.csproj">
- <Private>False</Private>
+ <Private>false</Private>
</ProjectReference>
</ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <!--
+ We import a props file with auto-generated includes. This works well with Rider.
+ However, Visual Studio and MonoDevelop won't list them in the solution explorer.
+ We can't use wildcards as there may be undesired old files still hanging around.
+ Fortunately code completion, go to definition and such still work.
+ -->
+ <Import Project="Generated\GeneratedIncludes.props" />
</Project>
diff --git a/modules/mono/glue/GodotSharp/GodotSharpEditor/Properties/AssemblyInfo.cs b/modules/mono/glue/GodotSharp/GodotSharpEditor/Properties/AssemblyInfo.cs
deleted file mode 100644
index 3684b7a3cb..0000000000
--- a/modules/mono/glue/GodotSharp/GodotSharpEditor/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-using System.Reflection;
-
-// Information about this assembly is defined by the following attributes.
-// Change them to the values specific to your project.
-
-[assembly: AssemblyTitle("GodotSharpEditor")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("")]
-[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/glue/arguments_vector.h b/modules/mono/glue/arguments_vector.h
index aeb466ba72..9ba6a05ac6 100644
--- a/modules/mono/glue/arguments_vector.h
+++ b/modules/mono/glue/arguments_vector.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,14 +35,13 @@
template <typename T, int POOL_SIZE = 5>
struct ArgumentsVector {
-
private:
T pool[POOL_SIZE];
T *_ptr;
int size;
- ArgumentsVector();
- ArgumentsVector(const ArgumentsVector &);
+ ArgumentsVector() = delete;
+ ArgumentsVector(const ArgumentsVector &) = delete;
public:
T *ptr() { return _ptr; }
diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp
index f370883320..34a96eba17 100644
--- a/modules/mono/glue/base_object_glue.cpp
+++ b/modules/mono/glue/base_object_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,17 +28,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "base_object_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/reference.h"
-#include "core/string_name.h"
+#include "core/object/class_db.h"
+#include "core/object/reference.h"
+#include "core/string/string_name.h"
#include "../csharp_script.h"
#include "../mono_gd/gd_mono_cache.h"
#include "../mono_gd/gd_mono_class.h"
#include "../mono_gd/gd_mono_internals.h"
+#include "../mono_gd/gd_mono_marshal.h"
#include "../mono_gd/gd_mono_utils.h"
#include "../signal_awaiter_utils.h"
#include "arguments_vector.h"
@@ -140,16 +140,18 @@ MethodBind *godot_icall_Object_ClassDB_get_method(StringName *p_type, MonoString
}
MonoObject *godot_icall_Object_weakref(Object *p_ptr) {
- if (!p_ptr)
+ if (!p_ptr) {
return nullptr;
+ }
Ref<WeakRef> wref;
Reference *ref = Object::cast_to<Reference>(p_ptr);
if (ref) {
REF r = ref;
- if (!r.is_valid())
+ if (!r.is_valid()) {
return nullptr;
+ }
wref.instance();
wref->set_ref(r);
@@ -161,9 +163,9 @@ MonoObject *godot_icall_Object_weakref(Object *p_ptr) {
return GDMonoUtils::unmanaged_get_managed(wref.ptr());
}
-Error godot_icall_SignalAwaiter_connect(Object *p_source, StringName *p_signal, Object *p_target, MonoObject *p_awaiter) {
+int32_t godot_icall_SignalAwaiter_connect(Object *p_source, StringName *p_signal, Object *p_target, MonoObject *p_awaiter) {
StringName signal = p_signal ? *p_signal : StringName();
- return gd_mono_connect_signal_awaiter(p_source, signal, p_target, p_awaiter);
+ return (int32_t)gd_mono_connect_signal_awaiter(p_source, signal, p_target, p_awaiter);
}
MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) {
@@ -238,17 +240,18 @@ MonoString *godot_icall_Object_ToString(Object *p_ptr) {
}
void godot_register_object_icalls() {
- mono_add_internal_call("Godot.Object::godot_icall_Object_Ctor", (void *)godot_icall_Object_Ctor);
- mono_add_internal_call("Godot.Object::godot_icall_Object_Disposed", (void *)godot_icall_Object_Disposed);
- mono_add_internal_call("Godot.Object::godot_icall_Reference_Disposed", (void *)godot_icall_Reference_Disposed);
- mono_add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", (void *)godot_icall_Object_ClassDB_get_method);
- mono_add_internal_call("Godot.Object::godot_icall_Object_ToString", (void *)godot_icall_Object_ToString);
- mono_add_internal_call("Godot.Object::godot_icall_Object_weakref", (void *)godot_icall_Object_weakref);
- mono_add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", (void *)godot_icall_SignalAwaiter_connect);
- mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", (void *)godot_icall_DynamicGodotObject_SetMemberList);
- mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_InvokeMember", (void *)godot_icall_DynamicGodotObject_InvokeMember);
- mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_GetMember", (void *)godot_icall_DynamicGodotObject_GetMember);
- mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMember", (void *)godot_icall_DynamicGodotObject_SetMember);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Ctor", godot_icall_Object_Ctor);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Disposed", godot_icall_Object_Disposed);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Reference_Disposed", godot_icall_Reference_Disposed);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ConnectEventSignals", godot_icall_Object_ConnectEventSignals);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", godot_icall_Object_ClassDB_get_method);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ToString", godot_icall_Object_ToString);
+ GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_weakref", godot_icall_Object_weakref);
+ GDMonoUtils::add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", godot_icall_SignalAwaiter_connect);
+ GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", godot_icall_DynamicGodotObject_SetMemberList);
+ GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_InvokeMember", godot_icall_DynamicGodotObject_InvokeMember);
+ GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_GetMember", godot_icall_DynamicGodotObject_GetMember);
+ GDMonoUtils::add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMember", godot_icall_DynamicGodotObject_SetMember);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/collections_glue.cpp b/modules/mono/glue/collections_glue.cpp
index 4e3dc9c4ea..191f863350 100644
--- a/modules/mono/glue/collections_glue.cpp
+++ b/modules/mono/glue/collections_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,14 +28,15 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "collections_glue.h"
-
#ifdef MONO_GLUE_ENABLED
#include <mono/metadata/exception.h>
+#include "core/variant/array.h"
+
#include "../mono_gd/gd_mono_cache.h"
#include "../mono_gd/gd_mono_class.h"
+#include "../mono_gd/gd_mono_marshal.h"
#include "../mono_gd/gd_mono_utils.h"
Array *godot_icall_Array_Ctor() {
@@ -46,7 +47,7 @@ void godot_icall_Array_Dtor(Array *ptr) {
memdelete(ptr);
}
-MonoObject *godot_icall_Array_At(Array *ptr, int index) {
+MonoObject *godot_icall_Array_At(Array *ptr, int32_t index) {
if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return nullptr;
@@ -54,7 +55,7 @@ MonoObject *godot_icall_Array_At(Array *ptr, int index) {
return GDMonoMarshal::variant_to_mono_object(ptr->operator[](index));
}
-MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_encoding, GDMonoClass *type_class) {
+MonoObject *godot_icall_Array_At_Generic(Array *ptr, int32_t index, uint32_t type_encoding, GDMonoClass *type_class) {
if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return nullptr;
@@ -62,7 +63,7 @@ MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_en
return GDMonoMarshal::variant_to_mono_object(ptr->operator[](index), ManagedType(type_encoding, type_class));
}
-void godot_icall_Array_SetAt(Array *ptr, int index, MonoObject *value) {
+void godot_icall_Array_SetAt(Array *ptr, int32_t index, MonoObject *value) {
if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return;
@@ -70,11 +71,11 @@ void godot_icall_Array_SetAt(Array *ptr, int index, MonoObject *value) {
ptr->operator[](index) = GDMonoMarshal::mono_object_to_variant(value);
}
-int godot_icall_Array_Count(Array *ptr) {
+int32_t godot_icall_Array_Count(Array *ptr) {
return ptr->size();
}
-int godot_icall_Array_Add(Array *ptr, MonoObject *item) {
+int32_t godot_icall_Array_Add(Array *ptr, MonoObject *item) {
ptr->append(GDMonoMarshal::mono_object_to_variant(item));
return ptr->size();
}
@@ -87,7 +88,7 @@ MonoBoolean godot_icall_Array_Contains(Array *ptr, MonoObject *item) {
return ptr->find(GDMonoMarshal::mono_object_to_variant(item)) != -1;
}
-void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int array_index) {
+void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int32_t array_index) {
unsigned int count = ptr->size();
if (mono_array_length(array) < (array_index + count)) {
@@ -103,15 +104,36 @@ void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int array_index) {
}
}
+Array *godot_icall_Array_Ctor_MonoArray(MonoArray *mono_array) {
+ Array *godot_array = memnew(Array);
+ unsigned int count = mono_array_length(mono_array);
+ godot_array->resize(count);
+ for (unsigned int i = 0; i < count; i++) {
+ MonoObject *item = mono_array_get(mono_array, MonoObject *, i);
+ godot_icall_Array_SetAt(godot_array, i, item);
+ }
+ return godot_array;
+}
+
Array *godot_icall_Array_Duplicate(Array *ptr, MonoBoolean deep) {
return memnew(Array(ptr->duplicate(deep)));
}
-int godot_icall_Array_IndexOf(Array *ptr, MonoObject *item) {
+Array *godot_icall_Array_Concatenate(Array *left, Array *right) {
+ int count = left->size() + right->size();
+ Array *new_array = memnew(Array(left->duplicate(false)));
+ new_array->resize(count);
+ for (unsigned int i = 0; i < (unsigned int)right->size(); i++) {
+ new_array->operator[](i + left->size()) = right->operator[](i);
+ }
+ return new_array;
+}
+
+int32_t godot_icall_Array_IndexOf(Array *ptr, MonoObject *item) {
return ptr->find(GDMonoMarshal::mono_object_to_variant(item));
}
-void godot_icall_Array_Insert(Array *ptr, int index, MonoObject *item) {
+void godot_icall_Array_Insert(Array *ptr, int32_t index, MonoObject *item) {
if (index < 0 || index > ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return;
@@ -128,7 +150,7 @@ MonoBoolean godot_icall_Array_Remove(Array *ptr, MonoObject *item) {
return false;
}
-void godot_icall_Array_RemoveAt(Array *ptr, int index) {
+void godot_icall_Array_RemoveAt(Array *ptr, int32_t index) {
if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return;
@@ -136,8 +158,12 @@ void godot_icall_Array_RemoveAt(Array *ptr, int index) {
ptr->remove(index);
}
-Error godot_icall_Array_Resize(Array *ptr, int new_size) {
- return ptr->resize(new_size);
+int32_t godot_icall_Array_Resize(Array *ptr, int32_t new_size) {
+ return (int32_t)ptr->resize(new_size);
+}
+
+void godot_icall_Array_Shuffle(Array *ptr) {
+ ptr->shuffle();
}
void godot_icall_Array_Generic_GetElementTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class) {
@@ -200,7 +226,7 @@ Array *godot_icall_Dictionary_Values(Dictionary *ptr) {
return memnew(Array(ptr->values()));
}
-int godot_icall_Dictionary_Count(Dictionary *ptr) {
+int32_t godot_icall_Dictionary_Count(Dictionary *ptr) {
return ptr->size();
}
@@ -282,44 +308,47 @@ MonoString *godot_icall_Dictionary_ToString(Dictionary *ptr) {
}
void godot_register_collections_icalls() {
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor", (void *)godot_icall_Array_Ctor);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Dtor", (void *)godot_icall_Array_Dtor);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_At", (void *)godot_icall_Array_At);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_At_Generic", (void *)godot_icall_Array_At_Generic);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_SetAt", (void *)godot_icall_Array_SetAt);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Count", (void *)godot_icall_Array_Count);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Add", (void *)godot_icall_Array_Add);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Clear", (void *)godot_icall_Array_Clear);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Contains", (void *)godot_icall_Array_Contains);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_CopyTo", (void *)godot_icall_Array_CopyTo);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Duplicate", (void *)godot_icall_Array_Duplicate);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_IndexOf", (void *)godot_icall_Array_IndexOf);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Insert", (void *)godot_icall_Array_Insert);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Remove", (void *)godot_icall_Array_Remove);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_RemoveAt", (void *)godot_icall_Array_RemoveAt);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Resize", (void *)godot_icall_Array_Resize);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_Generic_GetElementTypeInfo", (void *)godot_icall_Array_Generic_GetElementTypeInfo);
- mono_add_internal_call("Godot.Collections.Array::godot_icall_Array_ToString", (void *)godot_icall_Array_ToString);
-
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Ctor", (void *)godot_icall_Dictionary_Ctor);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Dtor", (void *)godot_icall_Dictionary_Dtor);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue", (void *)godot_icall_Dictionary_GetValue);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue_Generic", (void *)godot_icall_Dictionary_GetValue_Generic);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_SetValue", (void *)godot_icall_Dictionary_SetValue);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Keys", (void *)godot_icall_Dictionary_Keys);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Values", (void *)godot_icall_Dictionary_Values);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Count", (void *)godot_icall_Dictionary_Count);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Add", (void *)godot_icall_Dictionary_Add);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Clear", (void *)godot_icall_Dictionary_Clear);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Contains", (void *)godot_icall_Dictionary_Contains);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ContainsKey", (void *)godot_icall_Dictionary_ContainsKey);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Duplicate", (void *)godot_icall_Dictionary_Duplicate);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_RemoveKey", (void *)godot_icall_Dictionary_RemoveKey);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Remove", (void *)godot_icall_Dictionary_Remove);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue", (void *)godot_icall_Dictionary_TryGetValue);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue_Generic", (void *)godot_icall_Dictionary_TryGetValue_Generic);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Generic_GetValueTypeInfo", (void *)godot_icall_Dictionary_Generic_GetValueTypeInfo);
- mono_add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ToString", (void *)godot_icall_Dictionary_ToString);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor", godot_icall_Array_Ctor);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Ctor_MonoArray", godot_icall_Array_Ctor_MonoArray);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Dtor", godot_icall_Array_Dtor);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_At", godot_icall_Array_At);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_At_Generic", godot_icall_Array_At_Generic);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_SetAt", godot_icall_Array_SetAt);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Count", godot_icall_Array_Count);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Add", godot_icall_Array_Add);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Clear", godot_icall_Array_Clear);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Concatenate", godot_icall_Array_Concatenate);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Contains", godot_icall_Array_Contains);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_CopyTo", godot_icall_Array_CopyTo);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Duplicate", godot_icall_Array_Duplicate);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_IndexOf", godot_icall_Array_IndexOf);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Insert", godot_icall_Array_Insert);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Remove", godot_icall_Array_Remove);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_RemoveAt", godot_icall_Array_RemoveAt);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Resize", godot_icall_Array_Resize);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Shuffle", godot_icall_Array_Shuffle);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_Generic_GetElementTypeInfo", godot_icall_Array_Generic_GetElementTypeInfo);
+ GDMonoUtils::add_internal_call("Godot.Collections.Array::godot_icall_Array_ToString", godot_icall_Array_ToString);
+
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Ctor", godot_icall_Dictionary_Ctor);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Dtor", godot_icall_Dictionary_Dtor);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue", godot_icall_Dictionary_GetValue);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_GetValue_Generic", godot_icall_Dictionary_GetValue_Generic);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_SetValue", godot_icall_Dictionary_SetValue);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Keys", godot_icall_Dictionary_Keys);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Values", godot_icall_Dictionary_Values);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Count", godot_icall_Dictionary_Count);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Add", godot_icall_Dictionary_Add);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Clear", godot_icall_Dictionary_Clear);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Contains", godot_icall_Dictionary_Contains);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ContainsKey", godot_icall_Dictionary_ContainsKey);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Duplicate", godot_icall_Dictionary_Duplicate);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_RemoveKey", godot_icall_Dictionary_RemoveKey);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Remove", godot_icall_Dictionary_Remove);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue", godot_icall_Dictionary_TryGetValue);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_TryGetValue_Generic", godot_icall_Dictionary_TryGetValue_Generic);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Generic_GetValueTypeInfo", godot_icall_Dictionary_Generic_GetValueTypeInfo);
+ GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_ToString", godot_icall_Dictionary_ToString);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/collections_glue.h b/modules/mono/glue/collections_glue.h
deleted file mode 100644
index f8351a1fc7..0000000000
--- a/modules/mono/glue/collections_glue.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*************************************************************************/
-/* collections_glue.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 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 COLLECTIONS_GLUE_H
-#define COLLECTIONS_GLUE_H
-
-#ifdef MONO_GLUE_ENABLED
-
-#include "core/array.h"
-
-#include "../mono_gd/gd_mono_marshal.h"
-
-// Array
-
-Array *godot_icall_Array_Ctor();
-
-void godot_icall_Array_Dtor(Array *ptr);
-
-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);
-
-void godot_icall_Array_SetAt(Array *ptr, int index, MonoObject *value);
-
-int godot_icall_Array_Count(Array *ptr);
-
-int godot_icall_Array_Add(Array *ptr, MonoObject *item);
-
-void godot_icall_Array_Clear(Array *ptr);
-
-MonoBoolean godot_icall_Array_Contains(Array *ptr, MonoObject *item);
-
-void godot_icall_Array_CopyTo(Array *ptr, MonoArray *array, int array_index);
-
-Array *godot_icall_Array_Duplicate(Array *ptr, MonoBoolean deep);
-
-int godot_icall_Array_IndexOf(Array *ptr, MonoObject *item);
-
-void godot_icall_Array_Insert(Array *ptr, int index, MonoObject *item);
-
-MonoBoolean godot_icall_Array_Remove(Array *ptr, MonoObject *item);
-
-void godot_icall_Array_RemoveAt(Array *ptr, int index);
-
-Error godot_icall_Array_Resize(Array *ptr, int new_size);
-
-void godot_icall_Array_Generic_GetElementTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class);
-
-MonoString *godot_icall_Array_ToString(Array *ptr);
-
-// Dictionary
-
-Dictionary *godot_icall_Dictionary_Ctor();
-
-void godot_icall_Dictionary_Dtor(Dictionary *ptr);
-
-MonoObject *godot_icall_Dictionary_GetValue(Dictionary *ptr, MonoObject *key);
-
-MonoObject *godot_icall_Dictionary_GetValue_Generic(Dictionary *ptr, MonoObject *key, uint32_t type_encoding, GDMonoClass *type_class);
-
-void godot_icall_Dictionary_SetValue(Dictionary *ptr, MonoObject *key, MonoObject *value);
-
-Array *godot_icall_Dictionary_Keys(Dictionary *ptr);
-
-Array *godot_icall_Dictionary_Values(Dictionary *ptr);
-
-int godot_icall_Dictionary_Count(Dictionary *ptr);
-
-void godot_icall_Dictionary_Add(Dictionary *ptr, MonoObject *key, MonoObject *value);
-
-void godot_icall_Dictionary_Clear(Dictionary *ptr);
-
-MonoBoolean godot_icall_Dictionary_Contains(Dictionary *ptr, MonoObject *key, MonoObject *value);
-
-MonoBoolean godot_icall_Dictionary_ContainsKey(Dictionary *ptr, MonoObject *key);
-
-Dictionary *godot_icall_Dictionary_Duplicate(Dictionary *ptr, MonoBoolean deep);
-
-MonoBoolean godot_icall_Dictionary_RemoveKey(Dictionary *ptr, MonoObject *key);
-
-MonoBoolean godot_icall_Dictionary_Remove(Dictionary *ptr, MonoObject *key, MonoObject *value);
-
-MonoBoolean godot_icall_Dictionary_TryGetValue(Dictionary *ptr, MonoObject *key, MonoObject **value);
-
-MonoBoolean godot_icall_Dictionary_TryGetValue_Generic(Dictionary *ptr, MonoObject *key, MonoObject **value, uint32_t type_encoding, GDMonoClass *type_class);
-
-void godot_icall_Dictionary_Generic_GetValueTypeInfo(MonoReflectionType *refltype, uint32_t *type_encoding, GDMonoClass **type_class);
-
-MonoString *godot_icall_Dictionary_ToString(Dictionary *ptr);
-
-// Register internal calls
-
-void godot_register_collections_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // COLLECTIONS_GLUE_H
diff --git a/modules/mono/glue/gd_glue.cpp b/modules/mono/glue/gd_glue.cpp
index 2da39a916a..a2ff868f65 100644
--- a/modules/mono/glue/gd_glue.cpp
+++ b/modules/mono/glue/gd_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,18 +28,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "gd_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/array.h"
#include "core/io/marshalls.h"
#include "core/os/os.h"
-#include "core/ustring.h"
-#include "core/variant.h"
-#include "core/variant_parser.h"
+#include "core/string/ustring.h"
+#include "core/variant/array.h"
+#include "core/variant/variant.h"
+#include "core/variant/variant_parser.h"
#include "../mono_gd/gd_mono_cache.h"
+#include "../mono_gd/gd_mono_marshal.h"
#include "../mono_gd/gd_mono_utils.h"
MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) {
@@ -56,7 +55,8 @@ MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) {
Variant what = GDMonoMarshal::mono_object_to_variant(p_what);
const Variant *args[1] = { &what };
Callable::CallError ce;
- Variant ret = Variant::construct(Variant::Type(p_type), args, 1, ce);
+ Variant ret;
+ Variant::construct(Variant::Type(p_type), ret, args, 1, ce);
ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr);
return GDMonoMarshal::variant_to_mono_object(ret);
}
@@ -91,7 +91,6 @@ void godot_icall_GD_print(MonoArray *p_what) {
}
void godot_icall_GD_printerr(MonoArray *p_what) {
-
String str;
int length = mono_array_length(p_what);
@@ -148,8 +147,9 @@ void godot_icall_GD_prints(MonoArray *p_what) {
return;
}
- if (i)
+ if (i) {
str += " ";
+ }
str += elem_str;
}
@@ -172,8 +172,9 @@ void godot_icall_GD_printt(MonoArray *p_what) {
return;
}
- if (i)
+ if (i) {
str += "\t";
+ }
str += elem_str;
}
@@ -193,12 +194,16 @@ void godot_icall_GD_randomize() {
Math::randomize();
}
-double godot_icall_GD_rand_range(double from, double to) {
+double godot_icall_GD_randf_range(double from, double to) {
+ return Math::random(from, to);
+}
+
+int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) {
return Math::random(from, to);
}
uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) {
- int ret = Math::rand_from_seed(&seed);
+ uint32_t ret = Math::rand_from_seed(&seed);
*newSeed = seed;
return ret;
}
@@ -214,10 +219,11 @@ MonoString *godot_icall_GD_str(MonoArray *p_what) {
for (int i = 0; i < what.size(); i++) {
String os = what[i].operator String();
- if (i == 0)
+ if (i == 0) {
str = os;
- else
+ } else {
str += os;
+ }
}
return GDMonoMarshal::mono_string_from_godot(str);
@@ -283,32 +289,33 @@ MonoObject *godot_icall_DefaultGodotTaskScheduler() {
}
void godot_register_gd_icalls() {
- mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var);
- mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert);
- mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash);
- mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id);
- mono_add_internal_call("Godot.GD::godot_icall_GD_pusherror", (void *)godot_icall_GD_pusherror);
- mono_add_internal_call("Godot.GD::godot_icall_GD_pushwarning", (void *)godot_icall_GD_pushwarning);
- mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print);
- mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr);
- mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw);
- mono_add_internal_call("Godot.GD::godot_icall_GD_prints", (void *)godot_icall_GD_prints);
- mono_add_internal_call("Godot.GD::godot_icall_GD_printt", (void *)godot_icall_GD_printt);
- mono_add_internal_call("Godot.GD::godot_icall_GD_randf", (void *)godot_icall_GD_randf);
- mono_add_internal_call("Godot.GD::godot_icall_GD_randi", (void *)godot_icall_GD_randi);
- mono_add_internal_call("Godot.GD::godot_icall_GD_randomize", (void *)godot_icall_GD_randomize);
- mono_add_internal_call("Godot.GD::godot_icall_GD_rand_range", (void *)godot_icall_GD_rand_range);
- mono_add_internal_call("Godot.GD::godot_icall_GD_rand_seed", (void *)godot_icall_GD_rand_seed);
- mono_add_internal_call("Godot.GD::godot_icall_GD_seed", (void *)godot_icall_GD_seed);
- mono_add_internal_call("Godot.GD::godot_icall_GD_str", (void *)godot_icall_GD_str);
- mono_add_internal_call("Godot.GD::godot_icall_GD_str2var", (void *)godot_icall_GD_str2var);
- mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists);
- mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes);
- mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str);
- mono_add_internal_call("Godot.GD::godot_icall_TypeToVariantType", (void *)godot_icall_TypeToVariantType);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_bytes2var", godot_icall_GD_bytes2var);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_convert", godot_icall_GD_convert);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_hash", godot_icall_GD_hash);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", godot_icall_GD_instance_from_id);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_pusherror", godot_icall_GD_pusherror);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_pushwarning", godot_icall_GD_pushwarning);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_print", godot_icall_GD_print);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printerr", godot_icall_GD_printerr);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printraw", godot_icall_GD_printraw);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_prints", godot_icall_GD_prints);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_printt", godot_icall_GD_printt);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randf", godot_icall_GD_randf);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randi", godot_icall_GD_randi);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randomize", godot_icall_GD_randomize);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randf_range", godot_icall_GD_randf_range);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_randi_range", godot_icall_GD_randi_range);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_rand_seed", godot_icall_GD_rand_seed);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_seed", godot_icall_GD_seed);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_str", godot_icall_GD_str);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_str2var", godot_icall_GD_str2var);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_type_exists", godot_icall_GD_type_exists);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_var2bytes", godot_icall_GD_var2bytes);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_GD_var2str", godot_icall_GD_var2str);
+ GDMonoUtils::add_internal_call("Godot.GD::godot_icall_TypeToVariantType", godot_icall_TypeToVariantType);
// Dispatcher
- mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler);
+ GDMonoUtils::add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", godot_icall_DefaultGodotTaskScheduler);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/glue_header.h b/modules/mono/glue/glue_header.h
index ee99a300b9..3db52d7c30 100644
--- a/modules/mono/glue/glue_header.h
+++ b/modules/mono/glue/glue_header.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,16 @@
#ifdef MONO_GLUE_ENABLED
-#include "base_object_glue.h"
-#include "collections_glue.h"
-#include "gd_glue.h"
-#include "nodepath_glue.h"
-#include "rid_glue.h"
-#include "string_glue.h"
-#include "string_name_glue.h"
+#include "../mono_gd/gd_mono_marshal.h"
+
+void godot_register_collections_icalls();
+void godot_register_gd_icalls();
+void godot_register_string_name_icalls();
+void godot_register_nodepath_icalls();
+void godot_register_object_icalls();
+void godot_register_rid_icalls();
+void godot_register_string_icalls();
+void godot_register_scene_tree_icalls();
/**
* Registers internal calls that were not generated. This function is called
@@ -50,20 +53,20 @@ void godot_register_glue_header_icalls() {
godot_register_object_icalls();
godot_register_rid_icalls();
godot_register_string_icalls();
+ godot_register_scene_tree_icalls();
}
// Used by the generated glue
-#include "core/array.h"
-#include "core/class_db.h"
-#include "core/dictionary.h"
-#include "core/engine.h"
-#include "core/method_bind.h"
-#include "core/node_path.h"
-#include "core/object.h"
-#include "core/reference.h"
+#include "core/config/engine.h"
+#include "core/object/class_db.h"
+#include "core/object/method_bind.h"
+#include "core/object/reference.h"
+#include "core/string/node_path.h"
+#include "core/string/ustring.h"
#include "core/typedefs.h"
-#include "core/ustring.h"
+#include "core/variant/array.h"
+#include "core/variant/dictionary.h"
#include "../mono_gd/gd_mono_class.h"
#include "../mono_gd/gd_mono_internals.h"
diff --git a/modules/mono/glue/nodepath_glue.cpp b/modules/mono/glue/nodepath_glue.cpp
index e413f404d8..4ddb94e1a8 100644
--- a/modules/mono/glue/nodepath_glue.cpp
+++ b/modules/mono/glue/nodepath_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,11 +28,12 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "nodepath_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/ustring.h"
+#include "core/string/node_path.h"
+#include "core/string/ustring.h"
+
+#include "../mono_gd/gd_mono_marshal.h"
NodePath *godot_icall_NodePath_Ctor(MonoString *p_path) {
return memnew(NodePath(GDMonoMarshal::mono_string_to_godot(p_path)));
@@ -51,7 +52,7 @@ MonoBoolean godot_icall_NodePath_is_absolute(NodePath *p_ptr) {
return (MonoBoolean)p_ptr->is_absolute();
}
-uint32_t godot_icall_NodePath_get_name_count(NodePath *p_ptr) {
+int32_t godot_icall_NodePath_get_name_count(NodePath *p_ptr) {
return p_ptr->get_name_count();
}
@@ -59,7 +60,7 @@ MonoString *godot_icall_NodePath_get_name(NodePath *p_ptr, uint32_t p_idx) {
return GDMonoMarshal::mono_string_from_godot(p_ptr->get_name(p_idx));
}
-uint32_t godot_icall_NodePath_get_subname_count(NodePath *p_ptr) {
+int32_t godot_icall_NodePath_get_subname_count(NodePath *p_ptr) {
return p_ptr->get_subname_count();
}
@@ -80,17 +81,17 @@ MonoBoolean godot_icall_NodePath_is_empty(NodePath *p_ptr) {
}
void godot_register_nodepath_icalls() {
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_Ctor", (void *)godot_icall_NodePath_Ctor);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_Dtor", (void *)godot_icall_NodePath_Dtor);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_operator_String", (void *)godot_icall_NodePath_operator_String);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_as_property_path", (void *)godot_icall_NodePath_get_as_property_path);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_concatenated_subnames", (void *)godot_icall_NodePath_get_concatenated_subnames);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name", (void *)godot_icall_NodePath_get_name);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name_count", (void *)godot_icall_NodePath_get_name_count);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname", (void *)godot_icall_NodePath_get_subname);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname_count", (void *)godot_icall_NodePath_get_subname_count);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_is_absolute", (void *)godot_icall_NodePath_is_absolute);
- mono_add_internal_call("Godot.NodePath::godot_icall_NodePath_is_empty", (void *)godot_icall_NodePath_is_empty);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_Ctor", godot_icall_NodePath_Ctor);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_Dtor", godot_icall_NodePath_Dtor);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_operator_String", godot_icall_NodePath_operator_String);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_as_property_path", godot_icall_NodePath_get_as_property_path);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_concatenated_subnames", godot_icall_NodePath_get_concatenated_subnames);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name", godot_icall_NodePath_get_name);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_name_count", godot_icall_NodePath_get_name_count);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname", godot_icall_NodePath_get_subname);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_get_subname_count", godot_icall_NodePath_get_subname_count);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_is_absolute", godot_icall_NodePath_is_absolute);
+ GDMonoUtils::add_internal_call("Godot.NodePath::godot_icall_NodePath_is_empty", godot_icall_NodePath_is_empty);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/rid_glue.cpp b/modules/mono/glue/rid_glue.cpp
index 66a49d8fec..f464e63a81 100644
--- a/modules/mono/glue/rid_glue.cpp
+++ b/modules/mono/glue/rid_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,17 +28,20 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "rid_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/resource.h"
+#include "core/io/resource.h"
+#include "core/object/class_db.h"
+#include "core/templates/rid.h"
+
+#include "../mono_gd/gd_mono_marshal.h"
RID *godot_icall_RID_Ctor(Object *p_from) {
Resource *res_from = Object::cast_to<Resource>(p_from);
- if (res_from)
+ if (res_from) {
return memnew(RID(res_from->get_rid()));
+ }
return memnew(RID);
}
@@ -53,9 +56,9 @@ uint32_t godot_icall_RID_get_id(RID *p_ptr) {
}
void godot_register_rid_icalls() {
- mono_add_internal_call("Godot.RID::godot_icall_RID_Ctor", (void *)godot_icall_RID_Ctor);
- mono_add_internal_call("Godot.RID::godot_icall_RID_Dtor", (void *)godot_icall_RID_Dtor);
- mono_add_internal_call("Godot.RID::godot_icall_RID_get_id", (void *)godot_icall_RID_get_id);
+ GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_Ctor", godot_icall_RID_Ctor);
+ GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_Dtor", godot_icall_RID_Dtor);
+ GDMonoUtils::add_internal_call("Godot.RID::godot_icall_RID_get_id", godot_icall_RID_get_id);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/scene_tree_glue.cpp b/modules/mono/glue/scene_tree_glue.cpp
new file mode 100644
index 0000000000..5a6fd69db8
--- /dev/null
+++ b/modules/mono/glue/scene_tree_glue.cpp
@@ -0,0 +1,86 @@
+/*************************************************************************/
+/* scene_tree_glue.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#ifdef MONO_GLUE_ENABLED
+
+#include "core/object/class_db.h"
+#include "core/string/string_name.h"
+#include "core/variant/array.h"
+#include "scene/main/node.h"
+#include "scene/main/scene_tree.h"
+
+#include "../csharp_script.h"
+#include "../mono_gd/gd_mono_marshal.h"
+#include "../mono_gd/gd_mono_utils.h"
+
+Array *godot_icall_SceneTree_get_nodes_in_group_Generic(SceneTree *ptr, StringName *group, MonoReflectionType *refltype) {
+ List<Node *> nodes;
+ Array ret;
+
+ // Retrieve all the nodes in the group
+ ptr->get_nodes_in_group(*group, &nodes);
+
+ // No need to bother if the group is empty
+ if (!nodes.is_empty()) {
+ MonoType *elem_type = mono_reflection_type_get_type(refltype);
+ MonoClass *mono_class = mono_class_from_mono_type(elem_type);
+ GDMonoClass *klass = GDMono::get_singleton()->get_class(mono_class);
+
+ if (klass == GDMonoUtils::get_class_native_base(klass)) {
+ // If we're trying to get native objects, just check the inheritance list
+ StringName native_class_name = GDMonoUtils::get_native_godot_class_name(klass);
+ for (int i = 0; i < nodes.size(); ++i) {
+ if (ClassDB::is_parent_class(nodes[i]->get_class(), native_class_name)) {
+ ret.push_back(nodes[i]);
+ }
+ }
+ } else {
+ // If we're trying to get csharpscript instances, get the mono object and compare the classes
+ for (int i = 0; i < nodes.size(); ++i) {
+ CSharpInstance *si = CAST_CSHARP_INSTANCE(nodes[i]->get_script_instance());
+
+ if (si != nullptr) {
+ MonoObject *obj = si->get_mono_object();
+ if (obj != nullptr && mono_object_get_class(obj) == mono_class) {
+ ret.push_back(nodes[i]);
+ }
+ }
+ }
+ }
+ }
+
+ return memnew(Array(ret));
+}
+
+void godot_register_scene_tree_icalls() {
+ GDMonoUtils::add_internal_call("Godot.SceneTree::godot_icall_SceneTree_get_nodes_in_group_Generic", godot_icall_SceneTree_get_nodes_in_group_Generic);
+}
+
+#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/string_glue.cpp b/modules/mono/glue/string_glue.cpp
index e407a70db9..18a9221f89 100644
--- a/modules/mono/glue/string_glue.cpp
+++ b/modules/mono/glue/string_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,13 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "string_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/ustring.h"
-#include "core/variant.h"
-#include "core/vector.h"
+#include "core/string/ustring.h"
+#include "core/templates/vector.h"
+#include "core/variant/variant.h"
+
+#include "../mono_gd/gd_mono_marshal.h"
MonoArray *godot_icall_String_md5_buffer(MonoString *p_str) {
Vector<uint8_t> ret = GDMonoMarshal::mono_string_to_godot(p_str).md5_buffer();
@@ -68,12 +68,12 @@ MonoString *godot_icall_String_sha256_text(MonoString *p_str) {
}
void godot_register_string_icalls() {
- 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);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_md5_buffer", godot_icall_String_md5_buffer);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_md5_text", godot_icall_String_md5_text);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_rfind", godot_icall_String_rfind);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_rfindn", godot_icall_String_rfindn);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_buffer", godot_icall_String_sha256_buffer);
+ GDMonoUtils::add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_text", godot_icall_String_sha256_text);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/glue/string_name_glue.cpp b/modules/mono/glue/string_name_glue.cpp
index 81006e5849..f537896559 100644
--- a/modules/mono/glue/string_name_glue.cpp
+++ b/modules/mono/glue/string_name_glue.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,11 +28,12 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "string_name_glue.h"
-
#ifdef MONO_GLUE_ENABLED
-#include "core/ustring.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
+
+#include "../mono_gd/gd_mono_marshal.h"
StringName *godot_icall_StringName_Ctor(MonoString *p_path) {
return memnew(StringName(GDMonoMarshal::mono_string_to_godot(p_path)));
@@ -48,14 +49,14 @@ MonoString *godot_icall_StringName_operator_String(StringName *p_np) {
}
MonoBoolean godot_icall_StringName_is_empty(StringName *p_ptr) {
- return (MonoBoolean)(p_ptr == StringName());
+ return (MonoBoolean)(*p_ptr == StringName());
}
void godot_register_string_name_icalls() {
- mono_add_internal_call("Godot.StringName::godot_icall_StringName_Ctor", (void *)godot_icall_StringName_Ctor);
- mono_add_internal_call("Godot.StringName::godot_icall_StringName_Dtor", (void *)godot_icall_StringName_Dtor);
- mono_add_internal_call("Godot.StringName::godot_icall_StringName_operator_String", (void *)godot_icall_StringName_operator_String);
- mono_add_internal_call("Godot.StringName::godot_icall_StringName_is_empty", (void *)godot_icall_StringName_is_empty);
+ GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_Ctor", godot_icall_StringName_Ctor);
+ GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_Dtor", godot_icall_StringName_Dtor);
+ GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_operator_String", godot_icall_StringName_operator_String);
+ GDMonoUtils::add_internal_call("Godot.StringName::godot_icall_StringName_is_empty", godot_icall_StringName_is_empty);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/godotsharp_defs.h b/modules/mono/godotsharp_defs.h
index 7d57d0fac3..273dba52f9 100644
--- a/modules/mono/godotsharp_defs.h
+++ b/modules/mono/godotsharp_defs.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp
index d596163926..a39a6fe381 100644
--- a/modules/mono/godotsharp_dirs.cpp
+++ b/modules/mono/godotsharp_dirs.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,9 +30,9 @@
#include "godotsharp_dirs.h"
+#include "core/config/project_settings.h"
#include "core/os/dir_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#ifdef TOOLS_ENABLED
#include "core/version.h"
@@ -86,7 +86,6 @@ String _get_mono_user_dir() {
}
class _GodotSharpDirs {
-
public:
String res_data_dir;
String res_metadata_dir;
@@ -123,7 +122,7 @@ public:
private:
_GodotSharpDirs() {
- res_data_dir = "res://.mono";
+ res_data_dir = "res://.godot/mono";
res_metadata_dir = res_data_dir.plus_file("metadata");
res_assemblies_base_dir = res_data_dir.plus_file("assemblies");
res_assemblies_dir = res_assemblies_base_dir.plus_file(GDMono::get_expected_api_build_config());
@@ -147,7 +146,7 @@ private:
String appname = ProjectSettings::get_singleton()->get("application/config/name");
String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- if (appname_safe.empty()) {
+ if (appname_safe.is_empty()) {
appname_safe = "UnnamedProject";
}
@@ -323,5 +322,4 @@ String get_data_mono_bin_dir() {
return _GodotSharpDirs::get_singleton().data_mono_bin_dir;
}
#endif
-
} // namespace GodotSharpDirs
diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h
index 2ab4b0e309..3a3c6f980e 100644
--- a/modules/mono/godotsharp_dirs.h
+++ b/modules/mono/godotsharp_dirs.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef GODOTSHARP_DIRS_H
#define GODOTSHARP_DIRS_H
-#include "core/ustring.h"
+#include "core/string/ustring.h"
namespace GodotSharpDirs {
@@ -66,7 +66,6 @@ String get_data_mono_lib_dir();
#ifdef WINDOWS_ENABLED
String get_data_mono_bin_dir();
#endif
-
} // namespace GodotSharpDirs
#endif // GODOTSHARP_DIRS_H
diff --git a/modules/mono/icons/CSharpScript.svg b/modules/mono/icons/CSharpScript.svg
index 69664ca553..0b2cc840f8 100644
--- a/modules/mono/icons/CSharpScript.svg
+++ b/modules/mono/icons/CSharpScript.svg
@@ -1,5 +1 @@
-<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 d="m6 1046.4c-1.6569 0-3 1.3431-3 3s1.3431 3 3 3h1v-2h-1c-0.55228 0-1-0.4478-1-1 0-0.5523 0.44772-1 1-1h1v-2zm1-9-0.56445 2.2578c-0.23643 0.076-0.46689 0.1692-0.68945 0.2793l-1.9883-1.1933-1.4141 1.414 1.1953 1.9942c-0.11191 0.2211-0.20723 0.4502-0.28516 0.6855l-2.2539 0.5625v2h5.2715c-0.17677-0.3037-0.27041-0.6486-0.27148-1 9.6e-6 -1.1046 0.89543-2 2-2s2 0.8954 2 2c-4.817e-4 0.3512-0.093442 0.6961-0.26953 1h5.2695v-2l-2.2578-0.5645c-0.07594-0.2357-0.1693-0.4655-0.2793-0.6875l1.1934-1.9902-1.4141-1.414-1.9941 1.1953c-0.22113-0.1119-0.45028-0.2073-0.68555-0.2852l-0.5625-2.2539zm4 9c-0.71466-1e-4 -1.3751 0.3811-1.7324 1-0.35727 0.6188-0.35727 1.3812 0 2 0.35733 0.6189 1.0178 1.0001 1.7324 1h-2v2h2c0.71466 1e-4 1.3751-0.3811 1.7324-1 0.35727-0.6188 0.35727-1.3812 0-2-0.35733-0.6189-1.0178-1.0001-1.7324-1h2v-2z" fill="#e0e0e0"/>
-</g>
-</svg>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m6 1046.4c-1.6569 0-3 1.3431-3 3s1.3431 3 3 3h1v-2h-1c-.55228 0-1-.4478-1-1 0-.5523.44772-1 1-1h1v-2zm1-9-.56445 2.2578c-.23643.076-.46689.1692-.68945.2793l-1.9883-1.1933-1.4141 1.414 1.1953 1.9942c-.11191.2211-.20723.4502-.28516.6855l-2.2539.5625v2h5.2715c-.17677-.3037-.27041-.6486-.27148-1 .0000096-1.1046.89543-2 2-2s2 .8954 2 2c-.0004817.3512-.093442.6961-.26953 1h5.2695v-2l-2.2578-.5645c-.07594-.2357-.1693-.4655-.2793-.6875l1.1934-1.9902-1.4141-1.414-1.9941 1.1953c-.22113-.1119-.45028-.2073-.68555-.2852l-.5625-2.2539zm4 9c-.71466-.0001-1.3751.3811-1.7324 1-.35727.6188-.35727 1.3812 0 2 .35733.6189 1.0178 1.0001 1.7324 1h-2v2h2c.71466.0001 1.3751-.3811 1.7324-1 .35727-.6188.35727-1.3812 0-2-.35733-.6189-1.0178-1.0001-1.7324-1h2v-2z" fill="#e0e0e0" transform="translate(0 -1036.4)"/></svg>
diff --git a/modules/mono/managed_callable.cpp b/modules/mono/managed_callable.cpp
index dfd78a8244..6d868b527c 100644
--- a/modules/mono/managed_callable.cpp
+++ b/modules/mono/managed_callable.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -48,8 +48,9 @@ bool ManagedCallable::compare_equal(const CallableCustom *p_a, const CallableCus
MonoDelegate *delegate_b = (MonoDelegate *)b->delegate_handle.get_target();
if (!delegate_a || !delegate_b) {
- if (!delegate_a && !delegate_b)
+ if (!delegate_a && !delegate_b) {
return true;
+ }
return false;
}
@@ -58,8 +59,9 @@ bool ManagedCallable::compare_equal(const CallableCustom *p_a, const CallableCus
}
bool ManagedCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
- if (compare_equal(p_a, p_b))
+ if (compare_equal(p_a, p_b)) {
return false;
+ }
return p_a < p_b;
}
@@ -82,6 +84,7 @@ CallableCustom::CompareLessFunc ManagedCallable::get_compare_less_func() const {
}
ObjectID ManagedCallable::get_object() const {
+ // TODO: If the delegate target extends Godot.Object, use that instead!
return CSharpLanguage::get_singleton()->get_managed_callable_middleman()->get_instance_id();
}
diff --git a/modules/mono/managed_callable.h b/modules/mono/managed_callable.h
index 4f71e14a2f..c620eee60d 100644
--- a/modules/mono/managed_callable.h
+++ b/modules/mono/managed_callable.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,9 +33,9 @@
#include <mono/metadata/object.h>
-#include "core/callable.h"
#include "core/os/mutex.h"
-#include "core/self_list.h"
+#include "core/templates/self_list.h"
+#include "core/variant/callable.h"
#include "mono_gc_handle.h"
#include "mono_gd/gd_mono_method.h"
diff --git a/modules/mono/mono_gc_handle.cpp b/modules/mono/mono_gc_handle.cpp
index e362d5affb..8583065016 100644
--- a/modules/mono/mono_gc_handle.cpp
+++ b/modules/mono/mono_gc_handle.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -56,11 +56,9 @@ MonoGCHandleData MonoGCHandleData::new_weak_handle(MonoObject *p_object) {
}
Ref<MonoGCHandleRef> MonoGCHandleRef::create_strong(MonoObject *p_object) {
-
return memnew(MonoGCHandleRef(MonoGCHandleData::new_strong_handle(p_object)));
}
Ref<MonoGCHandleRef> MonoGCHandleRef::create_weak(MonoObject *p_object) {
-
return memnew(MonoGCHandleRef(MonoGCHandleData::new_weak_handle(p_object)));
}
diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h
index fbcb405b0d..f435aab3dd 100644
--- a/modules/mono/mono_gc_handle.h
+++ b/modules/mono/mono_gc_handle.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,7 @@
#include <mono/jit/jit.h>
-#include "core/reference.h"
+#include "core/object/reference.h"
namespace gdmono {
@@ -42,13 +42,12 @@ enum class GCHandleType : char {
STRONG_HANDLE,
WEAK_HANDLE
};
-
}
// Manual release of the GC handle must be done when using this struct
struct MonoGCHandleData {
- uint32_t handle;
- gdmono::GCHandleType type;
+ uint32_t handle = 0;
+ gdmono::GCHandleType type = gdmono::GCHandleType::NIL;
_FORCE_INLINE_ bool is_released() const { return !handle; }
_FORCE_INLINE_ bool is_weak() const { return type == gdmono::GCHandleType::WEAK_HANDLE; }
@@ -68,10 +67,7 @@ struct MonoGCHandleData {
MonoGCHandleData(const MonoGCHandleData &) = default;
- MonoGCHandleData() :
- handle(0),
- type(gdmono::GCHandleType::NIL) {
- }
+ MonoGCHandleData() {}
MonoGCHandleData(uint32_t p_handle, gdmono::GCHandleType p_type) :
handle(p_handle),
@@ -84,7 +80,6 @@ struct MonoGCHandleData {
};
class MonoGCHandleRef : public Reference {
-
GDCLASS(MonoGCHandleRef, Reference);
MonoGCHandleData data;
diff --git a/modules/mono/mono_gd/android_mono_config.h b/modules/mono/mono_gd/android_mono_config.h
index 93f708bba0..9d7cfe1b7c 100644
--- a/modules/mono/mono_gd/android_mono_config.h
+++ b/modules/mono/mono_gd/android_mono_config.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,7 @@
#ifdef ANDROID_ENABLED
-#include "core/ustring.h"
+#include "core/string/ustring.h"
// This function is defined in an auto-generated source file
String get_godot_android_mono_config();
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp
index 3298c5da4c..43a39a4966 100644
--- a/modules/mono/mono_gd/gd_mono.cpp
+++ b/modules/mono/mono_gd/gd_mono.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,12 +37,12 @@
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/profiler.h>
+#include "core/config/project_settings.h"
#include "core/debugger/engine_debugger.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "core/os/thread.h"
-#include "core/project_settings.h"
#include "../csharp_script.h"
#include "../godotsharp_dirs.h"
@@ -130,19 +130,23 @@ void gd_mono_profiler_init() {
}
void gd_mono_debug_init() {
-
CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
+ if (da_args.length()) {
+ OS::get_singleton()->set_environment("GODOT_MONO_DEBUGGER_AGENT", String());
+ }
+
#ifdef TOOLS_ENABLED
int da_port = GLOBAL_DEF("mono/debugger_agent/port", 23685);
bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
if (Engine::get_singleton()->is_editor_hint() ||
- ProjectSettings::get_singleton()->get_resource_path().empty() ||
+ ProjectSettings::get_singleton()->get_resource_path().is_empty() ||
Main::is_project_manager()) {
- if (da_args.size() == 0)
+ if (da_args.size() == 0) {
return;
+ }
}
if (da_args.length() == 0) {
@@ -197,7 +201,6 @@ MonoDomain *gd_initialize_mono_runtime() {
return mono_jit_init_version("GodotEngine.RootDomain", runtime_version);
}
#endif
-
} // namespace
void GDMono::add_mono_shared_libs_dir_to_path() {
@@ -247,7 +250,6 @@ void GDMono::add_mono_shared_libs_dir_to_path() {
}
void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_dir) {
-
String bundled_assembly_rootdir = GodotSharpDirs::get_data_mono_lib_dir();
String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir();
@@ -295,7 +297,7 @@ void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_di
}
#ifdef WINDOWS_ENABLED
- if (r_assembly_rootdir.empty() || r_config_dir.empty()) {
+ if (r_assembly_rootdir.is_empty() || r_config_dir.is_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);
@@ -310,7 +312,6 @@ void GDMono::determine_mono_dirs(String &r_assembly_rootdir, String &r_config_di
}
void GDMono::initialize() {
-
ERR_FAIL_NULL(Engine::get_singleton());
print_verbose("Mono: Initializing module...");
@@ -359,7 +360,7 @@ void GDMono::initialize() {
#ifndef TOOLS_ENABLED
// Exported games that don't use C# must still work. They likely don't ship with mscorlib.
// We only initialize the Mono runtime if we can find mscorlib. Otherwise it would crash.
- if (GDMonoAssembly::find_assembly("mscorlib.dll").empty()) {
+ if (GDMonoAssembly::find_assembly("mscorlib.dll").is_empty()) {
print_verbose("Mono: Skipping runtime initialization because 'mscorlib.dll' could not be found");
return;
}
@@ -409,7 +410,6 @@ void GDMono::initialize() {
}
void GDMono::initialize_load_assemblies() {
-
#ifndef MONO_GLUE_ENABLED
CRASH_NOW_MSG("Mono: This binary was built with 'mono_glue=no'; cannot load assemblies.");
#endif
@@ -422,22 +422,28 @@ void GDMono::initialize_load_assemblies() {
#if defined(TOOLS_ENABLED)
bool tool_assemblies_loaded = _load_tools_assemblies();
CRASH_COND_MSG(!tool_assemblies_loaded, "Mono: Failed to load '" TOOLS_ASM_NAME "' assemblies.");
+
+ if (Main::is_project_manager()) {
+ return;
+ }
#endif
// 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())
+ 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.assembly && (core_api_assembly.out_of_sync || !GDMonoCache::cached_data.godot_api_cache_updated);
#ifdef TOOLS_ENABLED
- if (!out_of_sync)
+ if (!out_of_sync) {
out_of_sync = editor_api_assembly.assembly && editor_api_assembly.out_of_sync;
+ }
#endif
return out_of_sync;
}
@@ -467,6 +473,7 @@ uint64_t get_editor_api_hash() {
uint32_t get_bindings_version() {
GD_UNREACHABLE();
}
+
uint32_t get_cs_glue_version() {
GD_UNREACHABLE();
}
@@ -508,25 +515,25 @@ void GDMono::_init_exception_policy() {
}
}
-void GDMono::add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly) {
-
+void GDMono::add_assembly(int32_t p_domain_id, GDMonoAssembly *p_assembly) {
assemblies[p_domain_id][p_assembly->get_name()] = p_assembly;
}
GDMonoAssembly *GDMono::get_loaded_assembly(const String &p_name) {
-
- if (p_name == "mscorlib")
- return get_corlib_assembly();
+ if (p_name == "mscorlib" && corlib_assembly) {
+ return corlib_assembly;
+ }
MonoDomain *domain = mono_domain_get();
- uint32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
+ int32_t domain_id = domain ? mono_domain_get_id(domain) : 0;
GDMonoAssembly **result = assemblies[domain_id].getptr(p_name);
return result ? *result : nullptr;
}
bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly) {
-
+#ifdef DEBUG_ENABLED
CRASH_COND(!r_assembly);
+#endif
MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
bool result = load_assembly(p_name, aname, r_assembly, p_refonly);
@@ -537,27 +544,27 @@ bool GDMono::load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bo
}
bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly) {
+#ifdef DEBUG_ENABLED
+ CRASH_COND(!r_assembly);
+#endif
+
+ return load_assembly(p_name, p_aname, r_assembly, p_refonly, GDMonoAssembly::get_default_search_dirs());
+}
+bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs) {
+#ifdef DEBUG_ENABLED
CRASH_COND(!r_assembly);
+#endif
print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
- MonoImageOpenStatus status = MONO_IMAGE_OK;
- MonoAssembly *assembly = mono_assembly_load_full(p_aname, nullptr, &status, p_refonly);
+ GDMonoAssembly *assembly = GDMonoAssembly::load(p_name, p_aname, p_refonly, p_search_dirs);
- if (!assembly)
+ if (!assembly) {
return false;
+ }
- ERR_FAIL_COND_V(status != MONO_IMAGE_OK, false);
-
- uint32_t domain_id = mono_domain_get_id(mono_domain_get());
-
- GDMonoAssembly **stored_assembly = assemblies[domain_id].getptr(p_name);
-
- ERR_FAIL_COND_V(stored_assembly == nullptr, false);
- ERR_FAIL_COND_V((*stored_assembly)->get_assembly() != assembly, false);
-
- *r_assembly = *stored_assembly;
+ *r_assembly = assembly;
print_verbose("Mono: Assembly " + p_name + (p_refonly ? " (refonly)" : "") + " loaded from path: " + (*r_assembly)->get_path());
@@ -565,15 +572,15 @@ bool GDMono::load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMo
}
bool GDMono::load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly) {
-
CRASH_COND(!r_assembly);
print_verbose("Mono: Loading assembly " + p_name + (p_refonly ? " (refonly)" : "") + "...");
GDMonoAssembly *assembly = GDMonoAssembly::load_from(p_name, p_path, p_refonly);
- if (!assembly)
+ if (!assembly) {
return false;
+ }
*r_assembly = assembly;
@@ -586,23 +593,26 @@ ApiAssemblyInfo::Version ApiAssemblyInfo::Version::get_from_loaded_assembly(GDMo
ApiAssemblyInfo::Version api_assembly_version;
const char *nativecalls_name = p_api_type == ApiAssemblyInfo::API_CORE ?
- BINDINGS_CLASS_NATIVECALLS :
- BINDINGS_CLASS_NATIVECALLS_EDITOR;
+ BINDINGS_CLASS_NATIVECALLS :
+ BINDINGS_CLASS_NATIVECALLS_EDITOR;
GDMonoClass *nativecalls_klass = p_api_assembly->get_class(BINDINGS_NAMESPACE, nativecalls_name);
if (nativecalls_klass) {
GDMonoField *api_hash_field = nativecalls_klass->get_field("godot_api_hash");
- if (api_hash_field)
+ if (api_hash_field) {
api_assembly_version.godot_api_hash = GDMonoMarshal::unbox<uint64_t>(api_hash_field->get_value(nullptr));
+ }
GDMonoField *binds_ver_field = nativecalls_klass->get_field("bindings_version");
- if (binds_ver_field)
+ if (binds_ver_field) {
api_assembly_version.bindings_version = GDMonoMarshal::unbox<uint32_t>(binds_ver_field->get_value(nullptr));
+ }
GDMonoField *cs_glue_ver_field = nativecalls_klass->get_field("cs_glue_version");
- if (cs_glue_ver_field)
+ if (cs_glue_ver_field) {
api_assembly_version.cs_glue_version = GDMonoMarshal::unbox<uint32_t>(cs_glue_ver_field->get_value(nullptr));
+ }
}
return api_assembly_version;
@@ -613,21 +623,21 @@ String ApiAssemblyInfo::to_string(ApiAssemblyInfo::Type p_type) {
}
bool GDMono::_load_corlib_assembly() {
-
- if (corlib_assembly)
+ if (corlib_assembly) {
return true;
+ }
bool success = load_assembly("mscorlib", &corlib_assembly);
- if (success)
+ if (success) {
GDMonoCache::update_corlib_cache();
+ }
return success;
}
#ifdef TOOLS_ENABLED
bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const String &p_config) {
-
String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
String dst_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
@@ -648,12 +658,14 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const
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)
+ if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) {
WARN_PRINT("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)
+ if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK) {
WARN_PRINT("Failed to copy '" + pdb_file + "'.");
+ }
String assembly_file = assembly_name + ".dll";
if (da->copy(src_dir.plus_file(assembly_file), dst_dir.plus_file(assembly_file)) != OK) {
@@ -668,13 +680,15 @@ static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool
String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
- if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path))
+ if (!FileAccess::exists(core_api_assembly_path) || !FileAccess::exists(editor_api_assembly_path)) {
return false;
+ }
String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
- if (!FileAccess::exists(cached_api_hash_path))
+ if (!FileAccess::exists(cached_api_hash_path)) {
return false;
+ }
Ref<ConfigFile> cfg;
cfg.instance();
@@ -698,7 +712,6 @@ static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool
}
static void create_cached_api_hash_for(const String &p_api_assemblies_dir) {
-
String core_api_assembly_path = p_api_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
String editor_api_assembly_path = p_api_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg");
@@ -741,15 +754,14 @@ bool GDMono::_temp_domain_load_are_assemblies_out_of_sync(const String &p_config
}
String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const bool *p_core_api_out_of_sync, const bool *p_editor_api_out_of_sync) {
-
#define FAIL_REASON(m_out_of_sync, m_prebuilt_exists) \
( \
(m_out_of_sync ? \
- String("The assembly is invalidated ") : \
- String("The assembly was not found ")) + \
+ String("The assembly is invalidated ") : \
+ String("The assembly was not found ")) + \
(m_prebuilt_exists ? \
- String("and the prebuilt assemblies are missing.") : \
- String("and we failed to copy the prebuilt assemblies.")))
+ String("and the prebuilt assemblies are missing.") : \
+ String("and we failed to copy the prebuilt assemblies.")))
String dst_assemblies_dir = GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config);
@@ -769,8 +781,9 @@ String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const
// Note: Even if only one of the assemblies if missing or out of sync, we update both
- if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path))
+ if (!api_assemblies_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path)) {
return String(); // No update needed
+ }
print_verbose("Updating '" + p_config + "' API assemblies");
@@ -798,17 +811,17 @@ String GDMono::update_api_assemblies_from_prebuilt(const String &p_config, const
#endif
bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
-
- if (r_loaded_api_assembly.assembly)
+ if (r_loaded_api_assembly.assembly) {
return true;
+ }
#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
// If running the project manager, load it from the prebuilt API directory
String assembly_dir = !Main::is_project_manager() ?
- GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
- GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
+ GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
+ GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
String assembly_path = assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
@@ -832,16 +845,16 @@ bool GDMono::_load_core_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, c
#ifdef TOOLS_ENABLED
bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly, const String &p_config, bool p_refonly) {
-
- if (r_loaded_api_assembly.assembly)
+ if (r_loaded_api_assembly.assembly) {
return true;
+ }
// 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
// If running the project manager, load it from the prebuilt API directory
String assembly_dir = !Main::is_project_manager() ?
- GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
- GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
+ GodotSharpDirs::get_res_assemblies_base_dir().plus_file(p_config) :
+ GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file(p_config);
String assembly_path = assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
@@ -864,30 +877,35 @@ bool GDMono::_load_editor_api_assembly(LoadedApiAssembly &r_loaded_api_assembly,
bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, LoadedApiAssembly &r_editor_api_assembly,
const String &p_config, bool p_refonly, CoreApiAssemblyLoadedCallback p_callback) {
if (!_load_core_api_assembly(r_core_api_assembly, p_config, p_refonly)) {
- if (OS::get_singleton()->is_stdout_verbose())
+ if (OS::get_singleton()->is_stdout_verbose()) {
print_error("Mono: Failed to load Core API assembly");
+ }
return false;
}
#ifdef TOOLS_ENABLED
if (!_load_editor_api_assembly(r_editor_api_assembly, p_config, p_refonly)) {
- if (OS::get_singleton()->is_stdout_verbose())
+ if (OS::get_singleton()->is_stdout_verbose()) {
print_error("Mono: Failed to load Editor API assembly");
+ }
return false;
}
- if (r_editor_api_assembly.out_of_sync)
+ if (r_editor_api_assembly.out_of_sync) {
return false;
+ }
#endif
// Check if the core API assembly is out of sync only after trying to load the
// editor API assembly. Otherwise, if both assemblies are out of sync, we would
// only update the former as we won't know the latter also needs to be updated.
- if (r_core_api_assembly.out_of_sync)
+ if (r_core_api_assembly.out_of_sync) {
return false;
+ }
- if (p_callback)
+ if (p_callback) {
return p_callback();
+ }
return true;
}
@@ -895,8 +913,9 @@ bool GDMono::_try_load_api_assemblies(LoadedApiAssembly &r_core_api_assembly, Lo
bool GDMono::_on_core_api_assembly_loaded() {
GDMonoCache::update_godot_api_cache();
- if (!GDMonoCache::cached_data.godot_api_cache_updated)
+ if (!GDMonoCache::cached_data.godot_api_cache_updated) {
return false;
+ }
get_singleton()->_install_trace_listener();
@@ -909,7 +928,6 @@ bool GDMono::_try_load_api_assemblies_preset() {
}
void GDMono::_load_api_assemblies() {
-
bool api_assemblies_loaded = _try_load_api_assemblies_preset();
#if defined(TOOLS_ENABLED) && !defined(GD_MONO_SINGLE_APPDOMAIN)
@@ -926,7 +944,7 @@ void GDMono::_load_api_assemblies() {
// 2. Update the API assemblies
String update_error = update_api_assemblies_from_prebuilt("Debug", &core_api_assembly.out_of_sync, &editor_api_assembly.out_of_sync);
- CRASH_COND_MSG(!update_error.empty(), update_error);
+ CRASH_COND_MSG(!update_error.is_empty(), update_error);
// 3. Load the scripts domain again
Error domain_load_err = _load_scripts_domain();
@@ -962,9 +980,9 @@ void GDMono::_load_api_assemblies() {
#ifdef TOOLS_ENABLED
bool GDMono::_load_tools_assemblies() {
-
- if (tools_assembly && tools_project_editor_assembly)
+ if (tools_assembly && tools_project_editor_assembly) {
return true;
+ }
bool success = load_assembly(TOOLS_ASM_NAME, &tools_assembly) &&
load_assembly(TOOLS_PROJECT_EDITOR_ASM_NAME, &tools_project_editor_assembly);
@@ -974,13 +992,13 @@ bool GDMono::_load_tools_assemblies() {
#endif
bool GDMono::_load_project_assembly() {
-
- if (project_assembly)
+ if (project_assembly) {
return true;
+ }
String appname = ProjectSettings::get_singleton()->get("application/config/name");
String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- if (appname_safe.empty()) {
+ if (appname_safe.is_empty()) {
appname_safe = "UnnamedProject";
}
@@ -994,7 +1012,6 @@ bool GDMono::_load_project_assembly() {
}
void GDMono::_install_trace_listener() {
-
#ifdef DEBUG_ENABLED
// Install the trace listener now before the project assembly is loaded
GDMonoClass *debug_utils = get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, "DebuggingUtils");
@@ -1011,7 +1028,6 @@ void GDMono::_install_trace_listener() {
#ifndef GD_MONO_SINGLE_APPDOMAIN
Error GDMono::_load_scripts_domain() {
-
ERR_FAIL_COND_V(scripts_domain != nullptr, ERR_BUG);
print_verbose("Mono: Loading scripts domain...");
@@ -1026,13 +1042,13 @@ Error GDMono::_load_scripts_domain() {
}
Error GDMono::_unload_scripts_domain() {
-
ERR_FAIL_NULL_V(scripts_domain, ERR_BUG);
print_verbose("Mono: Finalizing scripts domain...");
- if (mono_domain_get() != root_domain)
+ if (mono_domain_get() != root_domain) {
mono_domain_set(root_domain, true);
+ }
finalizing_scripts_domain = true;
@@ -1079,7 +1095,6 @@ Error GDMono::_unload_scripts_domain() {
#ifdef GD_MONO_HOT_RELOAD
Error GDMono::reload_scripts_domain() {
-
ERR_FAIL_COND_V(!runtime_initialized, ERR_BUG);
if (scripts_domain) {
@@ -1116,7 +1131,6 @@ Error GDMono::reload_scripts_domain() {
#ifndef GD_MONO_SINGLE_APPDOMAIN
Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
-
CRASH_COND(p_domain == nullptr);
CRASH_COND(p_domain == GDMono::get_singleton()->get_scripts_domain()); // Should use _unload_scripts_domain() instead
@@ -1124,8 +1138,9 @@ Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
print_verbose("Mono: Unloading domain '" + domain_name + "'...");
- if (mono_domain_get() == p_domain)
+ if (mono_domain_get() == p_domain) {
mono_domain_set(root_domain, true);
+ }
if (!mono_domain_finalize(p_domain, 2000)) {
ERR_PRINT("Mono: Domain finalization timeout.");
@@ -1149,13 +1164,13 @@ Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
#endif
GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
-
MonoImage *image = mono_class_get_image(p_raw_class);
- if (image == corlib_assembly->get_image())
+ if (image == corlib_assembly->get_image()) {
return corlib_assembly->get_class(p_raw_class);
+ }
- uint32_t domain_id = mono_domain_get_id(mono_domain_get());
+ int32_t domain_id = mono_domain_get_id(mono_domain_get());
HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
const String *k = nullptr;
@@ -1163,9 +1178,9 @@ GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
GDMonoAssembly *assembly = domain_assemblies.get(*k);
if (assembly->get_image() == image) {
GDMonoClass *klass = assembly->get_class(p_raw_class);
-
- if (klass)
+ if (klass) {
return klass;
+ }
}
}
@@ -1173,27 +1188,27 @@ GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
}
GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) {
-
GDMonoClass *klass = corlib_assembly->get_class(p_namespace, p_name);
- if (klass)
+ if (klass) {
return klass;
+ }
- uint32_t domain_id = mono_domain_get_id(mono_domain_get());
+ int32_t domain_id = mono_domain_get_id(mono_domain_get());
HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
const String *k = nullptr;
while ((k = domain_assemblies.next(k))) {
GDMonoAssembly *assembly = domain_assemblies.get(*k);
klass = assembly->get_class(p_namespace, p_name);
- if (klass)
+ if (klass) {
return klass;
+ }
}
return nullptr;
}
-void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
-
+void GDMono::_domain_assemblies_cleanup(int32_t p_domain_id) {
HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
const String *k = nullptr;
@@ -1205,15 +1220,15 @@ void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
}
void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) {
-
// This method will be called by the runtime when a thrown exception is not handled.
// It won't be called when we manually treat a thrown exception as unhandled.
// We assume the exception was already printed before calling this hook.
#ifdef DEBUG_ENABLED
GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc);
- if (EngineDebugger::is_active())
+ if (EngineDebugger::is_active()) {
EngineDebugger::get_singleton()->poll_events(false);
+ }
#endif
exit(mono_environment_exitcode_get());
@@ -1222,7 +1237,6 @@ void GDMono::unhandled_exception_hook(MonoObject *p_exc, void *) {
}
GDMono::GDMono() {
-
singleton = this;
gdmono_log = memnew(GDMonoLog);
@@ -1249,7 +1263,6 @@ GDMono::GDMono() {
}
GDMono::~GDMono() {
-
if (is_runtime_initialized()) {
#ifndef GD_MONO_SINGLE_APPDOMAIN
if (scripts_domain) {
@@ -1290,7 +1303,7 @@ GDMono::~GDMono() {
// Leave the rest to 'mono_jit_cleanup'
#endif
- const uint32_t *k = nullptr;
+ const int32_t *k = nullptr;
while ((k = assemblies.next(k))) {
HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies.get(*k);
@@ -1314,8 +1327,9 @@ GDMono::~GDMono() {
gdmono::android::support::cleanup();
#endif
- if (gdmono_log)
+ if (gdmono_log) {
memdelete(gdmono_log);
+ }
singleton = nullptr;
}
@@ -1323,79 +1337,76 @@ GDMono::~GDMono() {
_GodotSharp *_GodotSharp::singleton = nullptr;
void _GodotSharp::attach_thread() {
-
GDMonoUtils::attach_current_thread();
}
void _GodotSharp::detach_thread() {
-
GDMonoUtils::detach_current_thread();
}
int32_t _GodotSharp::get_domain_id() {
-
MonoDomain *domain = mono_domain_get();
- CRASH_COND(!domain); // User must check if runtime is initialized before calling this method
+ ERR_FAIL_NULL_V(domain, -1);
return mono_domain_get_id(domain);
}
int32_t _GodotSharp::get_scripts_domain_id() {
-
+ ERR_FAIL_NULL_V_MSG(GDMono::get_singleton(),
+ -1, "The Mono runtime is not initialized");
MonoDomain *domain = GDMono::get_singleton()->get_scripts_domain();
- CRASH_COND(!domain); // User must check if scripts domain is loaded before calling this method
+ ERR_FAIL_NULL_V(domain, -1);
return mono_domain_get_id(domain);
}
bool _GodotSharp::is_scripts_domain_loaded() {
-
- return GDMono::get_singleton()->is_runtime_initialized() && GDMono::get_singleton()->get_scripts_domain() != nullptr;
+ return GDMono::get_singleton() != nullptr &&
+ GDMono::get_singleton()->is_runtime_initialized() &&
+ GDMono::get_singleton()->get_scripts_domain() != nullptr;
}
bool _GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) {
-
return is_domain_finalizing_for_unload(p_domain_id);
}
-bool _GodotSharp::is_domain_finalizing_for_unload() {
-
- return is_domain_finalizing_for_unload(mono_domain_get());
-}
-
bool _GodotSharp::is_domain_finalizing_for_unload(int32_t p_domain_id) {
-
return is_domain_finalizing_for_unload(mono_domain_get_by_id(p_domain_id));
}
bool _GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) {
+ GDMono *gd_mono = GDMono::get_singleton();
- if (!p_domain)
- return true;
- if (p_domain == GDMono::get_singleton()->get_scripts_domain() && GDMono::get_singleton()->is_finalizing_scripts_domain())
+ ERR_FAIL_COND_V_MSG(!gd_mono || !gd_mono->is_runtime_initialized(),
+ false, "The Mono runtime is not initialized");
+
+ ERR_FAIL_NULL_V(p_domain, true);
+
+ if (p_domain == gd_mono->get_scripts_domain() && gd_mono->is_finalizing_scripts_domain()) {
return true;
+ }
+
return mono_domain_is_unloading(p_domain);
}
bool _GodotSharp::is_runtime_shutting_down() {
-
return mono_runtime_is_shutting_down();
}
bool _GodotSharp::is_runtime_initialized() {
-
- return GDMono::get_singleton()->is_runtime_initialized();
+ return GDMono::get_singleton() != nullptr && GDMono::get_singleton()->is_runtime_initialized();
}
void _GodotSharp::_reload_assemblies(bool p_soft_reload) {
#ifdef GD_MONO_HOT_RELOAD
+ CRASH_COND(CSharpLanguage::get_singleton() == nullptr);
// This method may be called more than once with `call_deferred`, so we need to check
// again if reloading is needed to avoid reloading multiple times unnecessarily.
- if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed())
+ if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) {
CSharpLanguage::get_singleton()->reload_assemblies(p_soft_reload);
+ }
#endif
}
void _GodotSharp::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread);
ClassDB::bind_method(D_METHOD("detach_thread"), &_GodotSharp::detach_thread);
@@ -1410,11 +1421,9 @@ void _GodotSharp::_bind_methods() {
}
_GodotSharp::_GodotSharp() {
-
singleton = this;
}
_GodotSharp::~_GodotSharp() {
-
singleton = nullptr;
}
diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h
index 4898833e8e..5accc21f8e 100644
--- a/modules/mono/mono_gd/gd_mono.h
+++ b/modules/mono/mono_gd/gd_mono.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -48,9 +48,9 @@ enum Type {
};
struct Version {
- uint64_t godot_api_hash;
- uint32_t bindings_version;
- uint32_t cs_glue_version;
+ uint64_t godot_api_hash = 0;
+ uint32_t bindings_version = 0;
+ uint32_t cs_glue_version = 0;
bool operator==(const Version &p_other) const {
return godot_api_hash == p_other.godot_api_hash &&
@@ -58,11 +58,7 @@ struct Version {
cs_glue_version == p_other.cs_glue_version;
}
- Version() :
- godot_api_hash(0),
- bindings_version(0),
- cs_glue_version(0) {
- }
+ Version() {}
Version(uint64_t p_godot_api_hash,
uint32_t p_bindings_version,
@@ -79,7 +75,6 @@ String to_string(Type p_type);
} // namespace ApiAssemblyInfo
class GDMono {
-
public:
enum UnhandledExceptionPolicy {
POLICY_TERMINATE_APP,
@@ -87,13 +82,10 @@ public:
};
struct LoadedApiAssembly {
- GDMonoAssembly *assembly;
- bool out_of_sync;
+ GDMonoAssembly *assembly = nullptr;
+ bool out_of_sync = false;
- LoadedApiAssembly() :
- assembly(nullptr),
- out_of_sync(false) {
- }
+ LoadedApiAssembly() {}
};
private:
@@ -105,7 +97,7 @@ private:
MonoDomain *root_domain;
MonoDomain *scripts_domain;
- HashMap<uint32_t, HashMap<String, GDMonoAssembly *>> assemblies;
+ HashMap<int32_t, HashMap<String, GDMonoAssembly *>> assemblies;
GDMonoAssembly *corlib_assembly;
GDMonoAssembly *project_assembly;
@@ -149,7 +141,7 @@ private:
Error _unload_scripts_domain();
#endif
- void _domain_assemblies_cleanup(uint32_t p_domain_id);
+ void _domain_assemblies_cleanup(int32_t p_domain_id);
uint64_t api_core_hash;
#ifdef TOOLS_ENABLED
@@ -173,14 +165,16 @@ protected:
public:
#ifdef DEBUG_METHODS_ENABLED
uint64_t get_api_core_hash() {
- if (api_core_hash == 0)
+ if (api_core_hash == 0) {
api_core_hash = ClassDB::get_api_hash(ClassDB::API_CORE);
+ }
return api_core_hash;
}
#ifdef TOOLS_ENABLED
uint64_t get_api_editor_hash() {
- if (api_editor_hash == 0)
+ if (api_editor_hash == 0) {
api_editor_hash = ClassDB::get_api_hash(ClassDB::API_EDITOR);
+ }
return api_editor_hash;
}
#endif // TOOLS_ENABLED
@@ -210,7 +204,7 @@ public:
UnhandledExceptionPolicy get_unhandled_exception_policy() const { return unhandled_exception_policy; }
// Do not use these, unless you know what you're doing
- void add_assembly(uint32_t p_domain_id, GDMonoAssembly *p_assembly);
+ void add_assembly(int32_t p_domain_id, GDMonoAssembly *p_assembly);
GDMonoAssembly *get_loaded_assembly(const String &p_name);
_FORCE_INLINE_ bool is_runtime_initialized() const { return runtime_initialized && !mono_runtime_is_shutting_down() /* stays true after shutdown finished */; }
@@ -241,6 +235,7 @@ public:
bool load_assembly(const String &p_name, GDMonoAssembly **r_assembly, bool p_refonly = false);
bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly = false);
+ bool load_assembly(const String &p_name, MonoAssemblyName *p_aname, GDMonoAssembly **r_assembly, bool p_refonly, const Vector<String> &p_search_dirs);
bool load_assembly_from(const String &p_name, const String &p_path, GDMonoAssembly **r_assembly, bool p_refonly = false);
Error finalize_and_unload_domain(MonoDomain *p_domain);
@@ -255,23 +250,22 @@ public:
namespace gdmono {
class ScopeDomain {
-
MonoDomain *prev_domain;
public:
ScopeDomain(MonoDomain *p_domain) {
- MonoDomain *prev_domain = mono_domain_get();
+ prev_domain = mono_domain_get();
if (prev_domain != p_domain) {
- this->prev_domain = prev_domain;
mono_domain_set(p_domain, false);
} else {
- this->prev_domain = nullptr;
+ prev_domain = nullptr;
}
}
~ScopeDomain() {
- if (prev_domain)
+ if (prev_domain) {
mono_domain_set(prev_domain, false);
+ }
}
};
@@ -284,11 +278,11 @@ public:
}
~ScopeExitDomainUnload() {
- if (domain)
+ if (domain) {
GDMono::get_singleton()->finalize_and_unload_domain(domain);
+ }
}
};
-
} // namespace gdmono
#define _GDMONO_SCOPE_DOMAIN_(m_mono_domain) \
@@ -306,9 +300,6 @@ class _GodotSharp : public Object {
bool _is_domain_finalizing_for_unload(int32_t p_domain_id);
- List<NodePath *> np_delete_queue;
- List<RID *> rid_delete_queue;
-
void _reload_assemblies(bool p_soft_reload);
protected:
@@ -326,7 +317,6 @@ public:
bool is_scripts_domain_loaded();
- bool is_domain_finalizing_for_unload();
bool is_domain_finalizing_for_unload(int32_t p_domain_id);
bool is_domain_finalizing_for_unload(MonoDomain *p_domain);
diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp
index 0f211eebc6..c6920814b9 100644
--- a/modules/mono/mono_gd/gd_mono_assembly.cpp
+++ b/modules/mono/mono_gd/gd_mono_assembly.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,10 +33,11 @@
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/tokentype.h>
-#include "core/list.h"
+#include "core/config/project_settings.h"
+#include "core/io/file_access_pack.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
+#include "core/templates/list.h"
#include "../godotsharp_dirs.h"
#include "gd_mono_cache.h"
@@ -45,23 +46,22 @@
Vector<String> GDMonoAssembly::search_dirs;
void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config, const String &p_custom_bcl_dir) {
-
String framework_dir;
- if (!p_custom_bcl_dir.empty()) {
+ if (!p_custom_bcl_dir.is_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()) {
+ if (!framework_dir.is_empty()) {
r_search_dirs.push_back(framework_dir);
r_search_dirs.push_back(framework_dir.plus_file("Facades"));
}
#if !defined(TOOLS_ENABLED)
String data_game_assemblies_dir = GodotSharpDirs::get_data_game_assemblies_dir();
- if (!data_game_assemblies_dir.empty()) {
+ if (!data_game_assemblies_dir.is_empty()) {
r_search_dirs.push_back(data_game_assemblies_dir);
}
#endif
@@ -72,7 +72,7 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin
r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir());
}
- if (p_custom_config.empty()) {
+ if (p_custom_config.is_empty()) {
r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir());
} else {
String api_config = p_custom_config == "ExportRelease" ? "Release" : "Debug";
@@ -99,8 +99,7 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin
// - The 'load' hook is called after the assembly has been loaded. Its job is to add the
// assembly to the list of loaded assemblies so that the 'search' hook can look it up.
-void GDMonoAssembly::assembly_load_hook(MonoAssembly *assembly, void *user_data) {
-
+void GDMonoAssembly::assembly_load_hook(MonoAssembly *assembly, [[maybe_unused]] void *user_data) {
String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
MonoImage *image = mono_assembly_get_image(assembly);
@@ -108,9 +107,10 @@ void GDMonoAssembly::assembly_load_hook(MonoAssembly *assembly, void *user_data)
GDMonoAssembly *gdassembly = memnew(GDMonoAssembly(name, image, assembly));
#ifdef GD_MONO_HOT_RELOAD
- const char *path = mono_image_get_filename(image);
- if (FileAccess::exists(path))
+ String path = String::utf8(mono_image_get_filename(image));
+ if (FileAccess::exists(path)) {
gdassembly->modified_time = FileAccess::get_modified_time(path);
+ }
#endif
MonoDomain *domain = mono_domain_get();
@@ -133,30 +133,24 @@ MonoAssembly *GDMonoAssembly::assembly_refonly_preload_hook(MonoAssemblyName *an
return GDMonoAssembly::_preload_hook(aname, assemblies_path, user_data, true);
}
-MonoAssembly *GDMonoAssembly::_search_hook(MonoAssemblyName *aname, void *user_data, bool refonly) {
-
- (void)user_data; // UNUSED
-
+MonoAssembly *GDMonoAssembly::_search_hook(MonoAssemblyName *aname, [[maybe_unused]] void *user_data, bool refonly) {
String name = String::utf8(mono_assembly_name_get_name(aname));
bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
- if (loaded_asm)
+ if (loaded_asm) {
return loaded_asm->get_assembly();
+ }
return nullptr;
}
-MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, void *user_data, bool refonly) {
-
- (void)user_data; // UNUSED
-
+MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **, [[maybe_unused]] void *user_data, bool refonly) {
String name = String::utf8(mono_assembly_name_get_name(aname));
- return _load_assembly_search(name, search_dirs, refonly);
+ return _load_assembly_search(name, aname, refonly, search_dirs);
}
-MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, const Vector<String> &p_search_dirs, bool p_refonly) {
-
+MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs) {
MonoAssembly *res = nullptr;
String path;
@@ -168,23 +162,26 @@ MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, const
if (has_extension) {
path = search_dir.plus_file(p_name);
if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly);
- if (res != nullptr)
+ res = _real_load_assembly_from(path, p_refonly, p_aname);
+ if (res != nullptr) {
return res;
+ }
}
} else {
path = search_dir.plus_file(p_name + ".dll");
if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly);
- if (res != nullptr)
+ res = _real_load_assembly_from(path, p_refonly, p_aname);
+ if (res != nullptr) {
return res;
+ }
}
path = search_dir.plus_file(p_name + ".exe");
if (FileAccess::exists(path)) {
- res = _real_load_assembly_from(path, p_refonly);
- if (res != nullptr)
+ res = _real_load_assembly_from(path, p_refonly, p_aname);
+ if (res != nullptr) {
return res;
+ }
}
}
}
@@ -193,7 +190,6 @@ MonoAssembly *GDMonoAssembly::_load_assembly_search(const String &p_name, const
}
String GDMonoAssembly::find_assembly(const String &p_name) {
-
String path;
bool has_extension = p_name.ends_with(".dll") || p_name.ends_with(".exe");
@@ -203,16 +199,19 @@ String GDMonoAssembly::find_assembly(const String &p_name) {
if (has_extension) {
path = search_dir.plus_file(p_name);
- if (FileAccess::exists(path))
+ if (FileAccess::exists(path)) {
return path;
+ }
} else {
path = search_dir.plus_file(p_name + ".dll");
- if (FileAccess::exists(path))
+ if (FileAccess::exists(path)) {
return path;
+ }
path = search_dir.plus_file(p_name + ".exe");
- if (FileAccess::exists(path))
+ if (FileAccess::exists(path)) {
return path;
+ }
}
}
@@ -220,7 +219,6 @@ String GDMonoAssembly::find_assembly(const String &p_name) {
}
void GDMonoAssembly::initialize() {
-
fill_search_dirs(search_dirs);
mono_install_assembly_search_hook(&assembly_search_hook, nullptr);
@@ -230,10 +228,9 @@ void GDMonoAssembly::initialize() {
mono_install_assembly_load_hook(&assembly_load_hook, nullptr);
}
-MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, bool p_refonly) {
-
+MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, bool p_refonly, MonoAssemblyName *p_aname) {
Vector<uint8_t> data = FileAccess::get_file_as_array(p_path);
- ERR_FAIL_COND_V_MSG(data.empty(), nullptr, "Could read the assembly in the specified location");
+ ERR_FAIL_COND_V_MSG(data.is_empty(), nullptr, "Could read the assembly in the specified location");
String image_filename;
@@ -255,7 +252,33 @@ MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, boo
true, &status, p_refonly,
image_filename.utf8());
- ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !image, nullptr, "Failed to open assembly image from the loaded data");
+ ERR_FAIL_COND_V_MSG(status != MONO_IMAGE_OK || !image, nullptr, "Failed to open assembly image from memory: '" + p_path + "'.");
+
+ if (p_aname != nullptr) {
+ // Check assembly version
+ const MonoTableInfo *table = mono_image_get_table_info(image, MONO_TABLE_ASSEMBLY);
+
+ ERR_FAIL_NULL_V(table, nullptr);
+
+ if (mono_table_info_get_rows(table)) {
+ uint32_t cols[MONO_ASSEMBLY_SIZE];
+ mono_metadata_decode_row(table, 0, cols, MONO_ASSEMBLY_SIZE);
+
+ // Not sure about .NET's policy. We will only ensure major and minor are equal, and ignore build and revision.
+ uint16_t major = cols[MONO_ASSEMBLY_MAJOR_VERSION];
+ uint16_t minor = cols[MONO_ASSEMBLY_MINOR_VERSION];
+
+ uint16_t required_minor;
+ uint16_t required_major = mono_assembly_name_get_version(p_aname, &required_minor, nullptr, nullptr);
+
+ if (required_major != 0) {
+ if (major != required_major && minor != required_minor) {
+ mono_image_close(image);
+ return nullptr;
+ }
+ }
+ }
+ }
#ifdef DEBUG_ENABLED
Vector<uint8_t> pdb_data;
@@ -264,8 +287,9 @@ MonoAssembly *GDMonoAssembly::_real_load_assembly_from(const String &p_path, boo
if (!FileAccess::exists(pdb_path)) {
pdb_path = p_path.get_basename() + ".pdb"; // without .dll
- if (!FileAccess::exists(pdb_path))
+ if (!FileAccess::exists(pdb_path)) {
goto no_pdb;
+ }
}
pdb_data = FileAccess::get_file_as_array(pdb_path);
@@ -292,8 +316,9 @@ no_pdb:
String name = String::utf8(mono_assembly_name_get_name(mono_assembly_get_name(assembly)));
bool has_extension = name.ends_with(".dll") || name.ends_with(".exe");
GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(has_extension ? name.get_basename() : name);
- if (!loaded_asm)
+ if (!loaded_asm) {
assembly_load_hook(assembly, nullptr);
+ }
}
// Decrement refcount which was previously incremented by mono_image_open_from_data_with_name
@@ -303,7 +328,6 @@ no_pdb:
}
void GDMonoAssembly::unload() {
-
ERR_FAIL_NULL(image); // Should not be called if already unloaded
for (Map<MonoClass *, GDMonoClass *>::Element *E = cached_raw.front(); E; E = E->next()) {
@@ -322,20 +346,21 @@ String GDMonoAssembly::get_path() const {
}
GDMonoClass *GDMonoAssembly::get_class(const StringName &p_namespace, const StringName &p_name) {
-
ERR_FAIL_NULL_V(image, nullptr);
ClassKey key(p_namespace, p_name);
GDMonoClass **match = cached_classes.getptr(key);
- if (match)
+ if (match) {
return *match;
+ }
MonoClass *mono_class = mono_class_from_name(image, String(p_namespace).utf8(), String(p_name).utf8());
- if (!mono_class)
+ if (!mono_class) {
return nullptr;
+ }
GDMonoClass *wrapped_class = memnew(GDMonoClass(p_namespace, p_name, mono_class, this));
@@ -346,13 +371,13 @@ GDMonoClass *GDMonoAssembly::get_class(const StringName &p_namespace, const Stri
}
GDMonoClass *GDMonoAssembly::get_class(MonoClass *p_mono_class) {
-
ERR_FAIL_NULL_V(image, nullptr);
Map<MonoClass *, GDMonoClass *>::Element *match = cached_raw.find(p_mono_class);
- if (match)
+ if (match) {
return match->value();
+ }
StringName namespace_name = mono_class_get_namespace(p_mono_class);
StringName class_name = mono_class_get_name(p_mono_class);
@@ -366,14 +391,14 @@ GDMonoClass *GDMonoAssembly::get_class(MonoClass *p_mono_class) {
}
GDMonoClass *GDMonoAssembly::get_object_derived_class(const StringName &p_class) {
-
GDMonoClass *match = nullptr;
if (gdobject_class_cache_updated) {
Map<StringName, GDMonoClass *>::Element *result = gdobject_class_cache.find(p_class);
- if (result)
+ if (result) {
match = result->get();
+ }
} else {
List<GDMonoClass *> nested_classes;
@@ -382,30 +407,34 @@ GDMonoClass *GDMonoAssembly::get_object_derived_class(const StringName &p_class)
for (int i = 1; i < rows; i++) {
MonoClass *mono_class = mono_class_get(image, (i + 1) | MONO_TOKEN_TYPE_DEF);
- if (!mono_class_is_assignable_from(CACHED_CLASS_RAW(GodotObject), mono_class))
+ if (!mono_class_is_assignable_from(CACHED_CLASS_RAW(GodotObject), mono_class)) {
continue;
+ }
GDMonoClass *current = get_class(mono_class);
- if (!current)
+ if (!current) {
continue;
+ }
nested_classes.push_back(current);
- if (!match && current->get_name() == p_class)
+ if (!match && current->get_name() == p_class) {
match = current;
+ }
- while (!nested_classes.empty()) {
+ while (!nested_classes.is_empty()) {
GDMonoClass *current_nested = nested_classes.front()->get();
- nested_classes.pop_back();
+ nested_classes.pop_front();
void *iter = nullptr;
while (true) {
MonoClass *raw_nested = mono_class_get_nested_types(current_nested->get_mono_ptr(), &iter);
- if (!raw_nested)
+ if (!raw_nested) {
break;
+ }
GDMonoClass *nested_class = get_class(raw_nested);
@@ -425,10 +454,32 @@ GDMonoClass *GDMonoAssembly::get_object_derived_class(const StringName &p_class)
return match;
}
-GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_path, bool p_refonly) {
+GDMonoAssembly *GDMonoAssembly::load(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs) {
+ if (GDMono::get_singleton()->get_corlib_assembly() && (p_name == "mscorlib" || p_name == "mscorlib.dll")) {
+ return GDMono::get_singleton()->get_corlib_assembly();
+ }
+
+ // We need to manually call the search hook in this case, as it won't be called in the next step
+ MonoAssembly *assembly = mono_assembly_invoke_search_hook(p_aname);
+
+ if (!assembly) {
+ assembly = _load_assembly_search(p_name, p_aname, p_refonly, p_search_dirs);
+ if (!assembly) {
+ return nullptr;
+ }
+ }
+
+ GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name);
+ ERR_FAIL_NULL_V_MSG(loaded_asm, nullptr, "Loaded assembly missing from table. Did we not receive the load hook?");
+ ERR_FAIL_COND_V(loaded_asm->get_assembly() != assembly, nullptr);
- if (p_name == "mscorlib" || p_name == "mscorlib.dll")
+ return loaded_asm;
+}
+
+GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_path, bool p_refonly) {
+ if (p_name == "mscorlib" || p_name == "mscorlib.dll") {
return GDMono::get_singleton()->get_corlib_assembly();
+ }
// We need to manually call the search hook in this case, as it won't be called in the next step
MonoAssemblyName *aname = mono_assembly_name_new(p_name.utf8());
@@ -438,7 +489,9 @@ GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_
if (!assembly) {
assembly = _real_load_assembly_from(p_path, p_refonly);
- ERR_FAIL_NULL_V(assembly, nullptr);
+ if (!assembly) {
+ return nullptr;
+ }
}
GDMonoAssembly *loaded_asm = GDMono::get_singleton()->get_loaded_assembly(p_name);
@@ -447,18 +500,8 @@ GDMonoAssembly *GDMonoAssembly::load_from(const String &p_name, const String &p_
return loaded_asm;
}
-GDMonoAssembly::GDMonoAssembly(const String &p_name, MonoImage *p_image, MonoAssembly *p_assembly) :
- name(p_name),
- image(p_image),
- assembly(p_assembly),
-#ifdef GD_MONO_HOT_RELOAD
- modified_time(0),
-#endif
- gdobject_class_cache_updated(false) {
-}
-
GDMonoAssembly::~GDMonoAssembly() {
-
- if (image)
+ if (image) {
unload();
+ }
}
diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h
index 43c8225b74..350fcf3210 100644
--- a/modules/mono/mono_gd/gd_mono_assembly.h
+++ b/modules/mono/mono_gd/gd_mono_assembly.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,13 +34,12 @@
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
-#include "core/hash_map.h"
-#include "core/map.h"
-#include "core/ustring.h"
+#include "core/string/ustring.h"
+#include "core/templates/hash_map.h"
+#include "core/templates/map.h"
#include "gd_mono_utils.h"
class GDMonoAssembly {
-
struct ClassKey {
struct Hasher {
static _FORCE_INLINE_ uint32_t hash(const ClassKey &p_key) {
@@ -73,10 +72,10 @@ class GDMonoAssembly {
MonoAssembly *assembly;
#ifdef GD_MONO_HOT_RELOAD
- uint64_t modified_time;
+ uint64_t modified_time = 0;
#endif
- bool gdobject_class_cache_updated;
+ bool gdobject_class_cache_updated = false;
Map<StringName, GDMonoClass *> gdobject_class_cache;
HashMap<ClassKey, GDMonoClass *, ClassKey::Hasher> cached_classes;
@@ -93,8 +92,8 @@ class GDMonoAssembly {
static MonoAssembly *_search_hook(MonoAssemblyName *aname, void *user_data, bool refonly);
static MonoAssembly *_preload_hook(MonoAssemblyName *aname, char **assemblies_path, void *user_data, bool refonly);
- static MonoAssembly *_real_load_assembly_from(const String &p_path, bool p_refonly);
- static MonoAssembly *_load_assembly_search(const String &p_name, const Vector<String> &p_search_dirs, bool p_refonly);
+ static MonoAssembly *_real_load_assembly_from(const String &p_path, bool p_refonly, MonoAssemblyName *p_aname = nullptr);
+ static MonoAssembly *_load_assembly_search(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs);
friend class GDMono;
static void initialize();
@@ -120,10 +119,16 @@ public:
static String find_assembly(const String &p_name);
static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String(), const String &p_custom_bcl_dir = String());
+ static const Vector<String> &get_default_search_dirs() { return search_dirs; }
+ static GDMonoAssembly *load(const String &p_name, MonoAssemblyName *p_aname, bool p_refonly, const Vector<String> &p_search_dirs);
static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly);
- GDMonoAssembly(const String &p_name, MonoImage *p_image, MonoAssembly *p_assembly);
+ GDMonoAssembly(const String &p_name, MonoImage *p_image, MonoAssembly *p_assembly) :
+ name(p_name),
+ image(p_image),
+ assembly(p_assembly) {
+ }
~GDMonoAssembly();
};
diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp
index 5ddf18d544..aea467660f 100644
--- a/modules/mono/mono_gd/gd_mono_cache.cpp
+++ b/modules/mono/mono_gd/gd_mono_cache.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -65,7 +65,6 @@ CachedData cached_data;
#define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_METHOD_THUNK_AND_CHECK_IMPL(cached_data.methodthunk_##m_class##_##m_method, m_val)
void CachedData::clear_corlib_cache() {
-
corlib_cache_updated = false;
class_MonoObject = nullptr;
@@ -98,7 +97,6 @@ void CachedData::clear_corlib_cache() {
}
void CachedData::clear_godot_api_cache() {
-
godot_api_cache_updated = false;
rawclass_Dictionary = nullptr;
@@ -193,7 +191,6 @@ void CachedData::clear_godot_api_cache() {
#define GODOT_API_NS_CLASS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class))
void update_corlib_cache() {
-
CACHE_CLASS_AND_CHECK(MonoObject, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_object_class()));
CACHE_CLASS_AND_CHECK(bool, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_boolean_class()));
CACHE_CLASS_AND_CHECK(int8_t, GDMono::get_singleton()->get_corlib_assembly()->get_class(mono_get_sbyte_class()));
@@ -220,7 +217,7 @@ void update_corlib_cache() {
CACHE_METHOD_AND_CHECK(System_Diagnostics_StackTrace, ctor_Exception_bool, CACHED_CLASS(System_Diagnostics_StackTrace)->get_method_with_desc("System.Diagnostics.StackTrace:.ctor(System.Exception,bool)", true));
#endif
- CACHE_METHOD_THUNK_AND_CHECK(Delegate, Equals, GDMono::get_singleton()->get_corlib_assembly()->get_class("System", "Delegate")->get_method_with_desc("System.Delegate:Equals(object)", 1));
+ CACHE_METHOD_THUNK_AND_CHECK(Delegate, Equals, GDMono::get_singleton()->get_corlib_assembly()->get_class("System", "Delegate")->get_method_with_desc("System.Delegate:Equals(object)", true));
CACHE_CLASS_AND_CHECK(KeyNotFoundException, GDMono::get_singleton()->get_corlib_assembly()->get_class("System.Collections.Generic", "KeyNotFoundException"));
@@ -228,7 +225,6 @@ void update_corlib_cache() {
}
void update_godot_api_cache() {
-
CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2));
CACHE_CLASS_AND_CHECK(Vector2i, GODOT_API_CLASS(Vector2i));
CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2));
@@ -320,5 +316,4 @@ void update_godot_api_cache() {
cached_data.godot_api_cache_updated = true;
}
-
} // namespace GDMonoCache
diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h
index 3cf2bd6ce5..fb75cb4b1c 100644
--- a/modules/mono/mono_gd/gd_mono_cache.h
+++ b/modules/mono/mono_gd/gd_mono_cache.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,7 +37,6 @@
namespace GDMonoCache {
struct CachedData {
-
// -----------------------------------------------
// corlib classes
@@ -182,7 +181,6 @@ inline void clear_corlib_cache() {
inline void clear_godot_api_cache() {
cached_data.clear_godot_api_cache();
}
-
} // namespace GDMonoCache
#define CACHED_CLASS(m_class) (GDMonoCache::cached_data.class_##m_class)
diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp
index 2c65f7e3a0..0ed7fcf375 100644
--- a/modules/mono/mono_gd/gd_mono_class.cpp
+++ b/modules/mono/mono_gd/gd_mono_class.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -79,19 +79,34 @@ bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const {
return mono_class_is_assignable_from(mono_class, p_from->mono_class);
}
-GDMonoClass *GDMonoClass::get_parent_class() {
+StringName GDMonoClass::get_namespace() const {
+ GDMonoClass *nesting_class = get_nesting_class();
+ if (!nesting_class) {
+ return namespace_name;
+ }
+ return nesting_class->get_namespace();
+}
+
+String GDMonoClass::get_name_for_lookup() const {
+ GDMonoClass *nesting_class = get_nesting_class();
+ if (!nesting_class) {
+ return class_name;
+ }
+ return nesting_class->get_name_for_lookup() + "/" + class_name;
+}
+
+GDMonoClass *GDMonoClass::get_parent_class() const {
MonoClass *parent_mono_class = mono_class_get_parent(mono_class);
return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : nullptr;
}
-GDMonoClass *GDMonoClass::get_nesting_class() {
+GDMonoClass *GDMonoClass::get_nesting_class() const {
MonoClass *nesting_type = mono_class_get_nesting_type(mono_class);
return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : nullptr;
}
#ifdef TOOLS_ENABLED
Vector<MonoClassField *> GDMonoClass::get_enum_fields() {
-
bool class_is_enum = mono_class_is_enum(mono_class);
ERR_FAIL_COND_V(!class_is_enum, Vector<MonoClassField *>());
@@ -114,37 +129,38 @@ Vector<MonoClassField *> GDMonoClass::get_enum_fields() {
#endif
bool GDMonoClass::has_attribute(GDMonoClass *p_attr_class) {
-
#ifdef DEBUG_ENABLED
ERR_FAIL_NULL_V(p_attr_class, false);
#endif
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return false;
+ }
return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}
MonoObject *GDMonoClass::get_attribute(GDMonoClass *p_attr_class) {
-
#ifdef DEBUG_ENABLED
ERR_FAIL_NULL_V(p_attr_class, nullptr);
#endif
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return nullptr;
+ }
return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}
void GDMonoClass::fetch_attributes() {
-
ERR_FAIL_COND(attributes != nullptr);
attributes = mono_custom_attrs_from_class(get_mono_ptr());
@@ -152,11 +168,11 @@ void GDMonoClass::fetch_attributes() {
}
void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base) {
-
CRASH_COND(!CACHED_CLASS(GodotObject)->is_assignable_from(this));
- if (methods_fetched)
+ if (methods_fetched) {
return;
+ }
void *iter = nullptr;
MonoMethod *raw_method = nullptr;
@@ -168,7 +184,6 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
ERR_CONTINUE(!method);
if (method->get_name() != name) {
-
#ifdef DEBUG_ENABLED
String fullname = method->get_ret_type_full_name() + " " + name + "(" + method->get_signature_desc(true) + ")";
WARN_PRINT("Method '" + fullname + "' is hidden by Godot API method. Should be '" +
@@ -182,7 +197,6 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
// This allows us to warn the user here if he is using snake_case by mistake.
if (p_native_base != this) {
-
GDMonoClass *native_top = p_native_base;
while (native_top) {
GDMonoMethod *m = native_top->get_method(name, method->get_parameters_count());
@@ -195,8 +209,9 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
break;
}
- if (native_top == CACHED_CLASS(GodotObject))
+ if (native_top == CACHED_CLASS(GodotObject)) {
break;
+ }
native_top = native_top->get_parent_class();
}
@@ -205,8 +220,9 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
uint32_t flags = mono_method_get_flags(method->mono_method, nullptr);
- if (!(flags & MONO_METHOD_ATTR_VIRTUAL))
+ if (!(flags & MONO_METHOD_ATTR_VIRTUAL)) {
continue;
+ }
// Virtual method of Godot Object derived type, let's try to find GodotMethod attribute
@@ -228,15 +244,17 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
#endif
MethodKey key = MethodKey(godot_method_name, method->get_parameters_count());
GDMonoMethod **existing_method = methods.getptr(key);
- if (existing_method)
+ if (existing_method) {
memdelete(*existing_method); // Must delete old one
+ }
methods.set(key, method);
break;
}
- if (top == CACHED_CLASS(GodotObject))
+ if (top == CACHED_CLASS(GodotObject)) {
break;
+ }
top = top->get_parent_class();
}
@@ -246,46 +264,44 @@ void GDMonoClass::fetch_methods_with_godot_api_checks(GDMonoClass *p_native_base
}
GDMonoMethod *GDMonoClass::get_fetched_method_unknown_params(const StringName &p_name) {
-
ERR_FAIL_COND_V(!methods_fetched, nullptr);
const MethodKey *k = nullptr;
while ((k = methods.next(k))) {
- if (k->name == p_name)
+ if (k->name == p_name) {
return methods.get(*k);
+ }
}
return nullptr;
}
bool GDMonoClass::has_fetched_method_unknown_params(const StringName &p_name) {
-
return get_fetched_method_unknown_params(p_name) != nullptr;
}
bool GDMonoClass::implements_interface(GDMonoClass *p_interface) {
-
return mono_class_implements_interface(mono_class, p_interface->get_mono_ptr());
}
bool GDMonoClass::has_public_parameterless_ctor() {
-
GDMonoMethod *ctor = get_method(".ctor", 0);
return ctor && ctor->get_visibility() == IMonoClassMember::PUBLIC;
}
-GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, int p_params_count) {
-
+GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, uint16_t p_params_count) {
MethodKey key = MethodKey(p_name, p_params_count);
GDMonoMethod **match = methods.getptr(key);
- if (match)
+ if (match) {
return *match;
+ }
- if (methods_fetched)
+ if (methods_fetched) {
return nullptr;
+ }
MonoMethod *raw_method = mono_class_get_method_from_name(mono_class, String(p_name).utf8().get_data(), p_params_count);
@@ -300,7 +316,6 @@ GDMonoMethod *GDMonoClass::get_method(const StringName &p_name, int p_params_cou
}
GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method) {
-
MonoMethodSignature *sig = mono_method_signature(p_raw_method);
int params_count = mono_signature_get_param_count(sig);
@@ -310,22 +325,21 @@ GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method) {
}
GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name) {
-
MonoMethodSignature *sig = mono_method_signature(p_raw_method);
int params_count = mono_signature_get_param_count(sig);
return get_method(p_raw_method, p_name, params_count);
}
-GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name, int p_params_count) {
-
+GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count) {
ERR_FAIL_NULL_V(p_raw_method, nullptr);
MethodKey key = MethodKey(p_name, p_params_count);
GDMonoMethod **match = methods.getptr(key);
- if (match)
+ if (match) {
return *match;
+ }
GDMonoMethod *method = memnew(GDMonoMethod(p_name, p_raw_method));
methods.set(key, method);
@@ -334,13 +348,13 @@ GDMonoMethod *GDMonoClass::get_method(MonoMethod *p_raw_method, const StringName
}
GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, bool p_include_namespace) {
-
MonoMethodDesc *desc = mono_method_desc_new(p_description.utf8().get_data(), p_include_namespace);
MonoMethod *method = mono_method_desc_search_in_class(desc, mono_class);
mono_method_desc_free(desc);
- if (!method)
+ if (!method) {
return nullptr;
+ }
ERR_FAIL_COND_V(mono_method_get_class(method) != mono_class, nullptr);
@@ -348,14 +362,15 @@ GDMonoMethod *GDMonoClass::get_method_with_desc(const String &p_description, boo
}
GDMonoField *GDMonoClass::get_field(const StringName &p_name) {
-
Map<StringName, GDMonoField *>::Element *result = fields.find(p_name);
- if (result)
+ if (result) {
return result->value();
+ }
- if (fields_fetched)
+ if (fields_fetched) {
return nullptr;
+ }
MonoClassField *raw_field = mono_class_get_field_from_name(mono_class, String(p_name).utf8().get_data());
@@ -370,9 +385,9 @@ GDMonoField *GDMonoClass::get_field(const StringName &p_name) {
}
const Vector<GDMonoField *> &GDMonoClass::get_all_fields() {
-
- if (fields_fetched)
+ if (fields_fetched) {
return fields_list;
+ }
void *iter = nullptr;
MonoClassField *raw_field = nullptr;
@@ -396,14 +411,15 @@ const Vector<GDMonoField *> &GDMonoClass::get_all_fields() {
}
GDMonoProperty *GDMonoClass::get_property(const StringName &p_name) {
-
Map<StringName, GDMonoProperty *>::Element *result = properties.find(p_name);
- if (result)
+ if (result) {
return result->value();
+ }
- if (properties_fetched)
+ if (properties_fetched) {
return nullptr;
+ }
MonoProperty *raw_property = mono_class_get_property_from_name(mono_class, String(p_name).utf8().get_data());
@@ -418,9 +434,9 @@ GDMonoProperty *GDMonoClass::get_property(const StringName &p_name) {
}
const Vector<GDMonoProperty *> &GDMonoClass::get_all_properties() {
-
- if (properties_fetched)
+ if (properties_fetched) {
return properties_list;
+ }
void *iter = nullptr;
MonoProperty *raw_property = nullptr;
@@ -444,8 +460,9 @@ const Vector<GDMonoProperty *> &GDMonoClass::get_all_properties() {
}
const Vector<GDMonoClass *> &GDMonoClass::get_all_delegates() {
- if (delegates_fetched)
+ if (delegates_fetched) {
return delegates_list;
+ }
void *iter = nullptr;
MonoClass *raw_class = nullptr;
@@ -471,7 +488,6 @@ const Vector<GDMonoClass *> &GDMonoClass::get_all_delegates() {
}
const Vector<GDMonoMethod *> &GDMonoClass::get_all_methods() {
-
if (!method_list_fetched) {
void *iter = nullptr;
MonoMethod *raw_method = nullptr;
@@ -486,7 +502,6 @@ const Vector<GDMonoMethod *> &GDMonoClass::get_all_methods() {
}
GDMonoClass::GDMonoClass(const StringName &p_namespace, const StringName &p_name, MonoClass *p_class, GDMonoAssembly *p_assembly) {
-
namespace_name = p_namespace;
class_name = p_name;
mono_class = p_class;
@@ -503,7 +518,6 @@ GDMonoClass::GDMonoClass(const StringName &p_namespace, const StringName &p_name
}
GDMonoClass::~GDMonoClass() {
-
if (attributes) {
mono_custom_attrs_free(attributes);
}
diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h
index 9237aae057..daea75bae8 100644
--- a/modules/mono/mono_gd/gd_mono_class.h
+++ b/modules/mono/mono_gd/gd_mono_class.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef GD_MONO_CLASS_H
#define GD_MONO_CLASS_H
-#include "core/map.h"
-#include "core/ustring.h"
+#include "core/string/ustring.h"
+#include "core/templates/map.h"
#include "gd_mono_field.h"
#include "gd_mono_header.h"
@@ -59,13 +59,12 @@ class GDMonoClass {
MethodKey() {}
- MethodKey(const StringName &p_name, int p_params_count) {
- name = p_name;
- params_count = p_params_count;
+ MethodKey(const StringName &p_name, uint16_t p_params_count) :
+ name(p_name), params_count(p_params_count) {
}
StringName name;
- int params_count;
+ uint16_t params_count = 0;
};
StringName namespace_name;
@@ -113,14 +112,15 @@ public:
bool is_assignable_from(GDMonoClass *p_from) const;
- _FORCE_INLINE_ StringName get_namespace() const { return namespace_name; }
+ StringName get_namespace() const;
_FORCE_INLINE_ StringName get_name() const { return class_name; }
+ String get_name_for_lookup() const;
_FORCE_INLINE_ MonoClass *get_mono_ptr() const { return mono_class; }
_FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; }
- GDMonoClass *get_parent_class();
- GDMonoClass *get_nesting_class();
+ GDMonoClass *get_parent_class() const;
+ GDMonoClass *get_nesting_class() const;
#ifdef TOOLS_ENABLED
Vector<MonoClassField *> get_enum_fields();
@@ -138,10 +138,10 @@ public:
bool implements_interface(GDMonoClass *p_interface);
bool has_public_parameterless_ctor();
- GDMonoMethod *get_method(const StringName &p_name, int p_params_count = 0);
+ GDMonoMethod *get_method(const StringName &p_name, uint16_t p_params_count = 0);
GDMonoMethod *get_method(MonoMethod *p_raw_method);
GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name);
- GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name, int p_params_count);
+ GDMonoMethod *get_method(MonoMethod *p_raw_method, const StringName &p_name, uint16_t p_params_count);
GDMonoMethod *get_method_with_desc(const String &p_description, bool p_include_namespace);
GDMonoField *get_field(const StringName &p_name);
diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp
index e76cb84d43..d91bb8210f 100644
--- a/modules/mono/mono_gd/gd_mono_field.cpp
+++ b/modules/mono/mono_gd/gd_mono_field.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,29 +46,15 @@ void GDMonoField::set_value_raw(MonoObject *p_object, void *p_ptr) {
}
void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_value) {
-#define SET_FROM_STRUCT(m_type) \
- { \
- GDMonoMarshal::M_##m_type from = MARSHALLED_OUT(m_type, p_value.operator ::m_type()); \
- mono_field_set_value(p_object, mono_field, &from); \
- }
-
-#define SET_FROM_ARRAY(m_type) \
- { \
- MonoArray *managed = GDMonoMarshal::m_type##_to_mono_array(p_value.operator ::m_type()); \
- mono_field_set_value(p_object, mono_field, managed); \
- }
-
switch (type.type_encoding) {
case MONO_TYPE_BOOLEAN: {
MonoBoolean val = p_value.operator bool();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
case MONO_TYPE_CHAR: {
int16_t val = p_value.operator unsigned short();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
case MONO_TYPE_I1: {
int8_t val = p_value.operator signed char();
mono_field_set_value(p_object, mono_field, &val);
@@ -85,7 +71,6 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
int64_t val = p_value.operator int64_t();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
case MONO_TYPE_U1: {
uint8_t val = p_value.operator unsigned char();
mono_field_set_value(p_object, mono_field, &val);
@@ -102,93 +87,92 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
uint64_t val = p_value.operator uint64_t();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
case MONO_TYPE_R4: {
float val = p_value.operator float();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
case MONO_TYPE_R8: {
double val = p_value.operator double();
mono_field_set_value(p_object, mono_field, &val);
} break;
-
- case MONO_TYPE_STRING: {
- if (p_value.get_type() == Variant::NIL) {
- // Otherwise, Variant -> String would return the string "Null"
- MonoString *mono_string = nullptr;
- mono_field_set_value(p_object, mono_field, mono_string);
- } else {
- MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
- mono_field_set_value(p_object, mono_field, mono_string);
- }
- } break;
-
case MONO_TYPE_VALUETYPE: {
GDMonoClass *tclass = type.type_class;
if (tclass == CACHED_CLASS(Vector2)) {
- SET_FROM_STRUCT(Vector2);
+ GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_value.operator ::Vector2());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Vector2i)) {
- SET_FROM_STRUCT(Vector2i);
+ GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_value.operator ::Vector2i());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Rect2)) {
- SET_FROM_STRUCT(Rect2);
+ GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_value.operator ::Rect2());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Rect2i)) {
- SET_FROM_STRUCT(Rect2i);
+ GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_value.operator ::Rect2i());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Transform2D)) {
- SET_FROM_STRUCT(Transform2D);
+ GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_value.operator ::Transform2D());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Vector3)) {
- SET_FROM_STRUCT(Vector3);
+ GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_value.operator ::Vector3());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Vector3i)) {
- SET_FROM_STRUCT(Vector3i);
+ GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_value.operator ::Vector3i());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Basis)) {
- SET_FROM_STRUCT(Basis);
+ GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_value.operator ::Basis());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Quat)) {
- SET_FROM_STRUCT(Quat);
+ GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_value.operator ::Quat());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Transform)) {
- SET_FROM_STRUCT(Transform);
+ GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_value.operator ::Transform());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(AABB)) {
- SET_FROM_STRUCT(AABB);
+ GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_value.operator ::AABB());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Color)) {
- SET_FROM_STRUCT(Color);
+ GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_value.operator ::Color());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
if (tclass == CACHED_CLASS(Plane)) {
- SET_FROM_STRUCT(Plane);
+ GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_value.operator ::Plane());
+ mono_field_set_value(p_object, mono_field, &from);
break;
}
@@ -267,118 +251,35 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
ERR_FAIL_MSG("Attempted to set the value of a field of unmarshallable type: '" + tclass->get_name() + "'.");
} break;
-
+ case MONO_TYPE_STRING: {
+ if (p_value.get_type() == Variant::NIL) {
+ // Otherwise, Variant -> String would return the string "Null"
+ MonoString *mono_string = nullptr;
+ mono_field_set_value(p_object, mono_field, mono_string);
+ } else {
+ MonoString *mono_string = GDMonoMarshal::mono_string_from_godot(p_value);
+ mono_field_set_value(p_object, mono_field, mono_string);
+ }
+ } break;
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY: {
- MonoArrayType *array_type = mono_type_get_array_type(type.type_class->get_mono_type());
-
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
- SET_FROM_ARRAY(Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
- SET_FROM_ARRAY(PackedByteArray);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
- SET_FROM_ARRAY(PackedInt32Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
- SET_FROM_ARRAY(PackedInt64Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(float)) {
- SET_FROM_ARRAY(PackedFloat32Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(double)) {
- SET_FROM_ARRAY(PackedFloat64Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(String)) {
- SET_FROM_ARRAY(PackedStringArray);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
- SET_FROM_ARRAY(PackedVector2Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
- SET_FROM_ARRAY(PackedVector3Array);
- break;
- }
-
- if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
- SET_FROM_ARRAY(PackedColorArray);
- break;
- }
-
- GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(array_type->eklass);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class)) {
- MonoArray *managed = GDMonoMarshal::Array_to_mono_array(p_value.operator ::Array(), array_type_class);
+ MonoArray *managed = GDMonoMarshal::variant_to_mono_array(p_value, type.type_class);
+ if (likely(managed != nullptr)) {
mono_field_set_value(p_object, mono_field, managed);
- break;
}
-
- ERR_FAIL_MSG("Attempted to convert Variant to a managed array of unmarshallable element type.");
} break;
-
case MONO_TYPE_CLASS: {
- GDMonoClass *type_class = type.type_class;
-
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *());
+ MonoObject *managed = GDMonoMarshal::variant_to_mono_object_of_class(p_value, type.type_class);
+ if (likely(managed != nullptr)) {
mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- if (CACHED_CLASS(StringName) == type_class) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator StringName());
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- if (CACHED_CLASS(NodePath) == type_class) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath());
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- if (CACHED_CLASS(RID) == type_class) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID());
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // Godot.Collections.Dictionary or IDictionary
- if (CACHED_CLASS(Dictionary) == type_class || type_class == CACHED_CLASS(System_Collections_IDictionary)) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), CACHED_CLASS(Dictionary));
- mono_field_set_value(p_object, mono_field, managed);
- break;
}
-
- // Godot.Collections.Array or ICollection or IEnumerable
- if (CACHED_CLASS(Array) == type_class ||
- type_class == CACHED_CLASS(System_Collections_ICollection) ||
- type_class == CACHED_CLASS(System_Collections_IEnumerable)) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
+ } break;
+ case MONO_TYPE_GENERICINST: {
+ MonoObject *managed = GDMonoMarshal::variant_to_mono_object_of_genericinst(p_value, type.type_class);
+ if (likely(managed != nullptr)) {
mono_field_set_value(p_object, mono_field, managed);
- break;
}
-
- ERR_FAIL_MSG("Attempted to set the value of a field of unmarshallable type: '" + type_class->get_name() + "'.");
} break;
-
case MONO_TYPE_OBJECT: {
// Variant
switch (p_value.get_type()) {
@@ -404,43 +305,56 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
mono_field_set_value(p_object, mono_field, mono_string);
} break;
case Variant::VECTOR2: {
- SET_FROM_STRUCT(Vector2);
+ GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_value.operator ::Vector2());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::VECTOR2I: {
- SET_FROM_STRUCT(Vector2i);
+ GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_value.operator ::Vector2i());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::RECT2: {
- SET_FROM_STRUCT(Rect2);
+ GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_value.operator ::Rect2());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::RECT2I: {
- SET_FROM_STRUCT(Rect2i);
+ GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_value.operator ::Rect2i());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::VECTOR3: {
- SET_FROM_STRUCT(Vector3);
+ GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_value.operator ::Vector3());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::VECTOR3I: {
- SET_FROM_STRUCT(Vector3i);
+ GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_value.operator ::Vector3i());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::TRANSFORM2D: {
- SET_FROM_STRUCT(Transform2D);
+ GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_value.operator ::Transform2D());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::PLANE: {
- SET_FROM_STRUCT(Plane);
+ GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_value.operator ::Plane());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::QUAT: {
- SET_FROM_STRUCT(Quat);
+ GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_value.operator ::Quat());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::AABB: {
- SET_FROM_STRUCT(AABB);
+ GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_value.operator ::AABB());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::BASIS: {
- SET_FROM_STRUCT(Basis);
+ GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_value.operator ::Basis());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::TRANSFORM: {
- SET_FROM_STRUCT(Transform);
+ GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_value.operator ::Transform());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::COLOR: {
- SET_FROM_STRUCT(Color);
+ GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_value.operator ::Color());
+ mono_field_set_value(p_object, mono_field, &from);
} break;
case Variant::STRING_NAME: {
MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator StringName());
@@ -450,8 +364,8 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath());
mono_field_set_value(p_object, mono_field, managed);
} break;
- case Variant::_RID: {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID());
+ case Variant::RID: {
+ MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator ::RID());
mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::OBJECT: {
@@ -475,105 +389,49 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_BYTE_ARRAY: {
- SET_FROM_ARRAY(PackedByteArray);
+ MonoArray *managed = GDMonoMarshal::PackedByteArray_to_mono_array(p_value.operator ::PackedByteArray());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_INT32_ARRAY: {
- SET_FROM_ARRAY(PackedInt32Array);
+ MonoArray *managed = GDMonoMarshal::PackedInt32Array_to_mono_array(p_value.operator ::PackedInt32Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_INT64_ARRAY: {
- SET_FROM_ARRAY(PackedInt64Array);
+ MonoArray *managed = GDMonoMarshal::PackedInt64Array_to_mono_array(p_value.operator ::PackedInt64Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_FLOAT32_ARRAY: {
- SET_FROM_ARRAY(PackedFloat32Array);
+ MonoArray *managed = GDMonoMarshal::PackedFloat32Array_to_mono_array(p_value.operator ::PackedFloat32Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_FLOAT64_ARRAY: {
- SET_FROM_ARRAY(PackedFloat64Array);
+ MonoArray *managed = GDMonoMarshal::PackedFloat64Array_to_mono_array(p_value.operator ::PackedFloat64Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_STRING_ARRAY: {
- SET_FROM_ARRAY(PackedStringArray);
+ MonoArray *managed = GDMonoMarshal::PackedStringArray_to_mono_array(p_value.operator ::PackedStringArray());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_VECTOR2_ARRAY: {
- SET_FROM_ARRAY(PackedVector2Array);
+ MonoArray *managed = GDMonoMarshal::PackedVector2Array_to_mono_array(p_value.operator ::PackedVector2Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_VECTOR3_ARRAY: {
- SET_FROM_ARRAY(PackedVector3Array);
+ MonoArray *managed = GDMonoMarshal::PackedVector3Array_to_mono_array(p_value.operator ::PackedVector3Array());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
case Variant::PACKED_COLOR_ARRAY: {
- SET_FROM_ARRAY(PackedColorArray);
+ MonoArray *managed = GDMonoMarshal::PackedColorArray_to_mono_array(p_value.operator ::PackedColorArray());
+ mono_field_set_value(p_object, mono_field, managed);
} break;
- default: break;
+ default:
+ break;
}
} break;
-
- case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type());
-
- // Godot.Collections.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), type.type_class);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // Godot.Collections.Array<T>
- if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), type.type_class);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // System.Collections.Generic.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
- MonoReflectionType *key_reftype = nullptr;
- MonoReflectionType *value_reftype = nullptr;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- MonoObject *managed = GDMonoMarshal::Dictionary_to_system_generic_dict(p_value.operator Dictionary(),
- type.type_class, key_reftype, value_reftype);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // System.Collections.Generic.List<T>
- if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
- MonoReflectionType *elem_reftype = nullptr;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- MonoObject *managed = GDMonoMarshal::Array_to_system_generic_list(p_value.operator Array(),
- type.type_class, elem_reftype);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // IDictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_idictionary(reftype)) {
- MonoReflectionType *key_reftype;
- MonoReflectionType *value_reftype;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype);
-
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), godot_dict_class);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
-
- // ICollection<T> or IEnumerable<T>
- if (GDMonoUtils::Marshal::type_is_generic_icollection(reftype) || GDMonoUtils::Marshal::type_is_generic_ienumerable(reftype)) {
- MonoReflectionType *elem_reftype;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- GDMonoClass *godot_array_class = GDMonoUtils::Marshal::make_generic_array_type(elem_reftype);
-
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), godot_array_class);
- mono_field_set_value(p_object, mono_field, managed);
- break;
- }
- } break;
-
default: {
ERR_PRINT("Attempted to set the value of a field of unexpected type encoding: " + itos(type.type_encoding) + ".");
} break;
}
-
-#undef SET_FROM_ARRAY_AND_BREAK
-#undef SET_FROM_STRUCT_AND_BREAK
}
MonoObject *GDMonoField::get_value(MonoObject *p_object) {
@@ -596,11 +454,13 @@ String GDMonoField::get_string_value(MonoObject *p_object) {
bool GDMonoField::has_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, false);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return false;
+ }
return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}
@@ -608,11 +468,13 @@ bool GDMonoField::has_attribute(GDMonoClass *p_attr_class) {
MonoObject *GDMonoField::get_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, nullptr);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return nullptr;
+ }
return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}
diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h
index 61f2c8f071..ed5078c673 100644
--- a/modules/mono/mono_gd/gd_mono_field.h
+++ b/modules/mono/mono_gd/gd_mono_field.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,6 @@
#include "i_mono_class_member.h"
class GDMonoField : public IMonoClassMember {
-
GDMonoClass *owner;
MonoClassField *mono_field;
diff --git a/modules/mono/mono_gd/gd_mono_header.h b/modules/mono/mono_gd/gd_mono_header.h
index 0f4f888546..483030610f 100644
--- a/modules/mono/mono_gd/gd_mono_header.h
+++ b/modules/mono/mono_gd/gd_mono_header.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef GD_MONO_HEADER_H
#define GD_MONO_HEADER_H
-#include "core/int_types.h"
+#include <cstdint>
#ifdef WIN32
#define GD_MONO_STDCALL __stdcall
diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp
index 1898785699..65e2680905 100644
--- a/modules/mono/mono_gd/gd_mono_internals.cpp
+++ b/modules/mono/mono_gd/gd_mono_internals.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,7 +45,6 @@
namespace GDMonoInternals {
void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) {
-
// This method should not fail
CRASH_COND(!unmanaged);
@@ -110,12 +109,10 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) {
CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle);
unmanaged->set_script_and_instance(script, csharp_instance);
-
- csharp_instance->connect_event_signals();
}
void unhandled_exception(MonoException *p_exc) {
- mono_unhandled_exception((MonoObject *)p_exc); // prints the exception as well
+ mono_print_unhandled_exception((MonoObject *)p_exc);
if (GDMono::get_singleton()->get_unhandled_exception_policy() == GDMono::POLICY_TERMINATE_APP) {
// Too bad 'mono_invoke_unhandled_exception_hook' is not exposed to embedders
@@ -123,11 +120,11 @@ void unhandled_exception(MonoException *p_exc) {
GD_UNREACHABLE();
} else {
#ifdef DEBUG_ENABLED
- GDMonoUtils::debug_send_unhandled_exception_error((MonoException *)p_exc);
- if (EngineDebugger::is_active())
+ GDMonoUtils::debug_send_unhandled_exception_error(p_exc);
+ if (EngineDebugger::is_active()) {
EngineDebugger::get_singleton()->poll_events(false);
+ }
#endif
}
}
-
} // namespace GDMonoInternals
diff --git a/modules/mono/mono_gd/gd_mono_internals.h b/modules/mono/mono_gd/gd_mono_internals.h
index 038d17f782..34d2d35b2d 100644
--- a/modules/mono/mono_gd/gd_mono_internals.h
+++ b/modules/mono/mono_gd/gd_mono_internals.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,7 @@
#include "../utils/macros.h"
-#include "core/object.h"
+#include "core/object/class_db.h"
namespace GDMonoInternals {
@@ -46,7 +46,6 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged);
* Use GDMonoUtils::debug_unhandled_exception(MonoException *) instead.
*/
void unhandled_exception(MonoException *p_exc);
-
} // namespace GDMonoInternals
#endif // GD_MONO_INTERNALS_H
diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp
index ca16c2b76a..e1d283242c 100644
--- a/modules/mono/mono_gd/gd_mono_log.cpp
+++ b/modules/mono/mono_gd/gd_mono_log.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -51,39 +51,45 @@ GDMonoLog *GDMonoLog::singleton = nullptr;
#ifdef GD_MONO_LOG_ENABLED
static int get_log_level_id(const char *p_log_level) {
-
const char *valid_log_levels[] = { "error", "critical", "warning", "message", "info", "debug", nullptr };
int i = 0;
while (valid_log_levels[i]) {
- if (!strcmp(valid_log_levels[i], p_log_level))
+ if (!strcmp(valid_log_levels[i], p_log_level)) {
return i;
+ }
i++;
}
return -1;
}
-void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *) {
+static String make_text(const char *log_domain, const char *log_level, const char *message) {
+ String text(message);
+ text += " (in domain ";
+ text += log_domain;
+ if (log_level) {
+ text += ", ";
+ text += log_level;
+ }
+ text += ")";
+ return text;
+}
+void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *) {
FileAccess *f = GDMonoLog::get_singleton()->log_file;
if (GDMonoLog::get_singleton()->log_level_id >= get_log_level_id(log_level)) {
- String text(message);
- text += " (in domain ";
- text += log_domain;
- if (log_level) {
- text += ", ";
- text += log_level;
- }
- text += ")\n";
+ String text = make_text(log_domain, log_level, message);
+ text += "\n";
f->seek_end();
f->store_string(text);
}
if (fatal) {
- ERR_PRINT("Mono: FATAL ERROR, ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'.");
+ String text = make_text(log_domain, log_level, message);
+ ERR_PRINT("Mono: FATAL ERROR '" + text + "', ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'.");
// Make sure to flush before aborting
f->flush();
f->close();
@@ -94,7 +100,6 @@ void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level,
}
bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) {
-
if (!DirAccess::exists(p_logs_dir)) {
DirAccessRef diraccess = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(!diraccess, false);
@@ -106,7 +111,6 @@ bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) {
}
void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) {
-
static const uint64_t MAX_SECS = 5 * 86400; // 5 days
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -119,10 +123,12 @@ void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) {
String current;
while ((current = da->get_next()).length()) {
- if (da->current_is_dir())
+ if (da->current_is_dir()) {
continue;
- if (!current.ends_with(".txt"))
+ }
+ if (!current.ends_with(".txt")) {
continue;
+ }
uint64_t modified_time = FileAccess::get_modified_time(da->get_current_dir().plus_file(current));
@@ -135,7 +141,6 @@ void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) {
}
void GDMonoLog::initialize() {
-
CharString log_level = OS::get_singleton()->get_environment("GODOT_MONO_LOG_LEVEL").utf8();
if (log_level.length() != 0 && get_log_level_id(log_level.get_data()) == -1) {
@@ -155,13 +160,13 @@ void GDMonoLog::initialize() {
OS::Date date_now = OS::get_singleton()->get_date();
OS::Time time_now = OS::get_singleton()->get_time();
- String log_file_name = str_format("%d_%02d_%02d %02d.%02d.%02d",
+ String log_file_name = str_format("%04d-%02d-%02d_%02d.%02d.%02d",
date_now.year, date_now.month, date_now.day,
time_now.hour, time_now.min, time_now.sec);
- log_file_name += str_format(" (%d)", OS::get_singleton()->get_process_id());
+ log_file_name += str_format("_%d", OS::get_singleton()->get_process_id());
- log_file_name += ".txt";
+ log_file_name += ".log";
log_file_path = logs_dir.plus_file(log_file_name);
@@ -175,7 +180,7 @@ void GDMonoLog::initialize() {
log_level_id = get_log_level_id(log_level.get_data());
if (log_file) {
- OS::get_singleton()->print("Mono: Logfile is: %s\n", log_file_path.utf8().get_data());
+ OS::get_singleton()->print("Mono: Log file is: '%s'\n", log_file_path.utf8().get_data());
mono_trace_set_log_handler(mono_log_callback, this);
} else {
OS::get_singleton()->printerr("Mono: No log file, using default log handler\n");
@@ -183,14 +188,12 @@ void GDMonoLog::initialize() {
}
GDMonoLog::GDMonoLog() {
-
singleton = this;
log_level_id = -1;
}
GDMonoLog::~GDMonoLog() {
-
singleton = nullptr;
if (log_file) {
@@ -207,12 +210,10 @@ void GDMonoLog::initialize() {
}
GDMonoLog::GDMonoLog() {
-
singleton = this;
}
GDMonoLog::~GDMonoLog() {
-
singleton = nullptr;
}
diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h
index 1fc21f7df5..9a95e3cb0a 100644
--- a/modules/mono/mono_gd/gd_mono_log.h
+++ b/modules/mono/mono_gd/gd_mono_log.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -45,7 +45,6 @@
#endif
class GDMonoLog {
-
#ifdef GD_MONO_LOG_ENABLED
int log_level_id;
diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp
index 91ee07388b..286858bff1 100644
--- a/modules/mono/mono_gd/gd_mono_marshal.cpp
+++ b/modules/mono/mono_gd/gd_mono_marshal.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -72,92 +72,119 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_
case MONO_TYPE_VALUETYPE: {
GDMonoClass *vtclass = p_type.type_class;
- if (vtclass == CACHED_CLASS(Vector2))
+ if (vtclass == CACHED_CLASS(Vector2)) {
return Variant::VECTOR2;
+ }
- if (vtclass == CACHED_CLASS(Vector2i))
+ if (vtclass == CACHED_CLASS(Vector2i)) {
return Variant::VECTOR2I;
+ }
- if (vtclass == CACHED_CLASS(Rect2))
+ if (vtclass == CACHED_CLASS(Rect2)) {
return Variant::RECT2;
+ }
- if (vtclass == CACHED_CLASS(Rect2i))
+ if (vtclass == CACHED_CLASS(Rect2i)) {
return Variant::RECT2I;
+ }
- if (vtclass == CACHED_CLASS(Transform2D))
+ if (vtclass == CACHED_CLASS(Transform2D)) {
return Variant::TRANSFORM2D;
+ }
- if (vtclass == CACHED_CLASS(Vector3))
+ if (vtclass == CACHED_CLASS(Vector3)) {
return Variant::VECTOR3;
+ }
- if (vtclass == CACHED_CLASS(Vector3i))
+ if (vtclass == CACHED_CLASS(Vector3i)) {
return Variant::VECTOR3I;
+ }
- if (vtclass == CACHED_CLASS(Basis))
+ if (vtclass == CACHED_CLASS(Basis)) {
return Variant::BASIS;
+ }
- if (vtclass == CACHED_CLASS(Quat))
+ if (vtclass == CACHED_CLASS(Quat)) {
return Variant::QUAT;
+ }
- if (vtclass == CACHED_CLASS(Transform))
+ if (vtclass == CACHED_CLASS(Transform)) {
return Variant::TRANSFORM;
+ }
- if (vtclass == CACHED_CLASS(AABB))
+ if (vtclass == CACHED_CLASS(AABB)) {
return Variant::AABB;
+ }
- if (vtclass == CACHED_CLASS(Color))
+ if (vtclass == CACHED_CLASS(Color)) {
return Variant::COLOR;
+ }
- if (vtclass == CACHED_CLASS(Plane))
+ if (vtclass == CACHED_CLASS(Plane)) {
return Variant::PLANE;
+ }
- if (vtclass == CACHED_CLASS(Callable))
+ if (vtclass == CACHED_CLASS(Callable)) {
return Variant::CALLABLE;
+ }
- if (vtclass == CACHED_CLASS(SignalInfo))
+ if (vtclass == CACHED_CLASS(SignalInfo)) {
return Variant::SIGNAL;
+ }
- if (mono_class_is_enum(vtclass->get_mono_ptr()))
+ if (mono_class_is_enum(vtclass->get_mono_ptr())) {
return Variant::INT;
+ }
} break;
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY: {
MonoArrayType *array_type = mono_type_get_array_type(p_type.type_class->get_mono_type());
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject))
+ if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
return Variant::ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
return Variant::PACKED_BYTE_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
return Variant::PACKED_INT32_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
return Variant::PACKED_INT64_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(float))
+ if (array_type->eklass == CACHED_CLASS_RAW(float)) {
return Variant::PACKED_FLOAT32_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(double))
+ if (array_type->eklass == CACHED_CLASS_RAW(double)) {
return Variant::PACKED_FLOAT64_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(String))
+ if (array_type->eklass == CACHED_CLASS_RAW(String)) {
return Variant::PACKED_STRING_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2))
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
return Variant::PACKED_VECTOR2_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3))
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
return Variant::PACKED_VECTOR3_ARRAY;
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Color))
+ if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
return Variant::PACKED_COLOR_ARRAY;
+ }
GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(array_type->eklass);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class))
+ if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class)) {
return Variant::ARRAY;
+ }
} break;
case MONO_TYPE_CLASS: {
@@ -177,7 +204,7 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_
}
if (CACHED_CLASS(RID) == type_class) {
- return Variant::_RID;
+ return Variant::RID;
}
if (CACHED_CLASS(Dictionary) == type_class) {
@@ -201,8 +228,9 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_
} break;
case MONO_TYPE_OBJECT: {
- if (r_nil_is_variant)
+ if (r_nil_is_variant) {
*r_nil_is_variant = true;
+ }
return Variant::NIL;
} break;
@@ -244,8 +272,9 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_
} break;
}
- if (r_nil_is_variant)
+ if (r_nil_is_variant) {
*r_nil_is_variant = false;
+ }
// Unknown
return Variant::NIL;
@@ -282,213 +311,590 @@ bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_
return false;
}
-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(mono_domain_get(), p_dictionary_type.type_class->get_mono_type());
+MonoString *variant_to_mono_string(const Variant &p_var) {
+ if (p_var.get_type() == Variant::NIL) {
+ return nullptr; // Otherwise, Variant -> String would return the string "Null"
+ }
+ return mono_string_from_godot(p_var.operator String());
+}
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(dict_reftype) ||
- GDMonoUtils::Marshal::type_is_system_generic_dictionary(dict_reftype) ||
- GDMonoUtils::Marshal::type_is_generic_idictionary(dict_reftype)) {
- MonoReflectionType *key_reftype;
- MonoReflectionType *value_reftype;
+MonoArray *variant_to_mono_array(const Variant &p_var, GDMonoClass *p_type_class) {
+ MonoArrayType *array_type = mono_type_get_array_type(p_type_class->get_mono_type());
- GDMonoUtils::Marshal::dictionary_get_key_value_types(dict_reftype, &key_reftype, &value_reftype);
+ if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
+ return Array_to_mono_array(p_var.operator Array());
+ }
- r_key_type = ManagedType::from_reftype(key_reftype);
- r_value_type = ManagedType::from_reftype(value_reftype);
- return true;
- }
- } break;
- default: {
- } break;
+ if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
+ return PackedByteArray_to_mono_array(p_var.operator PackedByteArray());
}
- return false;
+ if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
+ return PackedInt32Array_to_mono_array(p_var.operator PackedInt32Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
+ return PackedInt64Array_to_mono_array(p_var.operator PackedInt64Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(float)) {
+ return PackedFloat32Array_to_mono_array(p_var.operator PackedFloat32Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(double)) {
+ return PackedFloat64Array_to_mono_array(p_var.operator PackedFloat64Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(String)) {
+ return PackedStringArray_to_mono_array(p_var.operator PackedStringArray());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
+ return PackedVector2Array_to_mono_array(p_var.operator PackedVector2Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
+ return PackedVector3Array_to_mono_array(p_var.operator PackedVector3Array());
+ }
+
+ if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
+ return PackedColorArray_to_mono_array(p_var.operator PackedColorArray());
+ }
+
+ if (mono_class_is_assignable_from(CACHED_CLASS(GodotObject)->get_mono_ptr(), array_type->eklass)) {
+ return Array_to_mono_array(p_var.operator ::Array(), array_type->eklass);
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to array of unsupported element type:" +
+ GDMonoClass::get_full_name(array_type->eklass) + "'.");
}
-String mono_to_utf8_string(MonoString *p_mono_string) {
- MonoError error;
- char *utf8 = mono_string_to_utf8_checked(p_mono_string, &error);
+MonoObject *variant_to_mono_object_of_class(const Variant &p_var, GDMonoClass *p_type_class) {
+ // GodotObject
+ if (CACHED_CLASS(GodotObject)->is_assignable_from(p_type_class)) {
+ return GDMonoUtils::unmanaged_get_managed(p_var.operator Object *());
+ }
- if (!mono_error_ok(&error)) {
- ERR_PRINT(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&error) + "'.");
- mono_error_cleanup(&error);
- return String();
+ if (CACHED_CLASS(StringName) == p_type_class) {
+ return GDMonoUtils::create_managed_from(p_var.operator StringName());
}
- String ret = String::utf8(utf8);
+ if (CACHED_CLASS(NodePath) == p_type_class) {
+ return GDMonoUtils::create_managed_from(p_var.operator NodePath());
+ }
- mono_free(utf8);
+ if (CACHED_CLASS(RID) == p_type_class) {
+ return GDMonoUtils::create_managed_from(p_var.operator ::RID());
+ }
- return ret;
+ // Godot.Collections.Dictionary or IDictionary
+ if (CACHED_CLASS(Dictionary) == p_type_class || CACHED_CLASS(System_Collections_IDictionary) == p_type_class) {
+ return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), CACHED_CLASS(Dictionary));
+ }
+
+ // Godot.Collections.Array or ICollection or IEnumerable
+ if (CACHED_CLASS(Array) == p_type_class ||
+ CACHED_CLASS(System_Collections_ICollection) == p_type_class ||
+ CACHED_CLASS(System_Collections_IEnumerable) == p_type_class) {
+ return GDMonoUtils::create_managed_from(p_var.operator Array(), CACHED_CLASS(Array));
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type: '" +
+ p_type_class->get_full_name() + "'.");
}
-String mono_to_utf16_string(MonoString *p_mono_string) {
- int len = mono_string_length(p_mono_string);
- String ret;
+MonoObject *variant_to_mono_object_of_genericinst(const Variant &p_var, GDMonoClass *p_type_class) {
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type_class->get_mono_type());
- if (len == 0)
- return ret;
+ // Godot.Collections.Dictionary<TKey, TValue>
+ if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
+ return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), p_type_class);
+ }
- ret.resize(len + 1);
- ret.set(len, 0);
+ // Godot.Collections.Array<T>
+ if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
+ return GDMonoUtils::create_managed_from(p_var.operator Array(), p_type_class);
+ }
- CharType *src = (CharType *)mono_string_chars(p_mono_string);
- CharType *dst = ret.ptrw();
+ // System.Collections.Generic.Dictionary<TKey, TValue>
+ if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
+ MonoReflectionType *key_reftype = nullptr;
+ MonoReflectionType *value_reftype = nullptr;
+ GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
+ return Dictionary_to_system_generic_dict(p_var.operator Dictionary(), p_type_class, key_reftype, value_reftype);
+ }
- for (int i = 0; i < len; i++) {
- dst[i] = src[i];
+ // System.Collections.Generic.List<T>
+ if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
+ MonoReflectionType *elem_reftype = nullptr;
+ GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
+ return Array_to_system_generic_list(p_var.operator Array(), p_type_class, elem_reftype);
}
- return ret;
+ // IDictionary<TKey, TValue>
+ if (GDMonoUtils::Marshal::type_is_generic_idictionary(reftype)) {
+ MonoReflectionType *key_reftype;
+ MonoReflectionType *value_reftype;
+ GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
+ GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype);
+
+ return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), godot_dict_class);
+ }
+
+ // ICollection<T> or IEnumerable<T>
+ if (GDMonoUtils::Marshal::type_is_generic_icollection(reftype) || GDMonoUtils::Marshal::type_is_generic_ienumerable(reftype)) {
+ MonoReflectionType *elem_reftype;
+ GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
+ GDMonoClass *godot_array_class = GDMonoUtils::Marshal::make_generic_array_type(elem_reftype);
+
+ return GDMonoUtils::create_managed_from(p_var.operator Array(), godot_array_class);
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported generic type: '" +
+ p_type_class->get_full_name() + "'.");
}
-MonoObject *variant_to_mono_object(const Variant *p_var) {
- ManagedType type;
+MonoObject *variant_to_mono_object(const Variant &p_var) {
+ // Variant
+ switch (p_var.get_type()) {
+ case Variant::BOOL: {
+ MonoBoolean val = p_var.operator bool();
+ return BOX_BOOLEAN(val);
+ }
+ case Variant::INT: {
+ int64_t val = p_var.operator int64_t();
+ return BOX_INT64(val);
+ }
+ case Variant::FLOAT: {
+#ifdef REAL_T_IS_DOUBLE
+ double val = p_var.operator double();
+ return BOX_DOUBLE(val);
+#else
+ float val = p_var.operator float();
+ return BOX_FLOAT(val);
+#endif
+ }
+ case Variant::STRING:
+ return (MonoObject *)mono_string_from_godot(p_var.operator String());
+ case Variant::VECTOR2: {
+ GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_var.operator ::Vector2());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from);
+ }
+ case Variant::VECTOR2I: {
+ GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var.operator ::Vector2i());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from);
+ }
+ case Variant::RECT2: {
+ GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var.operator ::Rect2());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from);
+ }
+ case Variant::RECT2I: {
+ GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var.operator ::Rect2i());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from);
+ }
+ case Variant::VECTOR3: {
+ GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_var.operator ::Vector3());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from);
+ }
+ case Variant::VECTOR3I: {
+ GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var.operator ::Vector3i());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from);
+ }
+ case Variant::TRANSFORM2D: {
+ GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var.operator ::Transform2D());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from);
+ }
+ case Variant::PLANE: {
+ GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_var.operator ::Plane());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Plane), &from);
+ }
+ case Variant::QUAT: {
+ GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_var.operator ::Quat());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quat), &from);
+ }
+ case Variant::AABB: {
+ GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_var.operator ::AABB());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(AABB), &from);
+ }
+ case Variant::BASIS: {
+ GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var.operator ::Basis());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from);
+ }
+ case Variant::TRANSFORM: {
+ GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_var.operator ::Transform());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform), &from);
+ }
+ case Variant::COLOR: {
+ GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_var.operator ::Color());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Color), &from);
+ }
+ case Variant::STRING_NAME:
+ return GDMonoUtils::create_managed_from(p_var.operator StringName());
+ case Variant::NODE_PATH:
+ return GDMonoUtils::create_managed_from(p_var.operator NodePath());
+ case Variant::RID:
+ return GDMonoUtils::create_managed_from(p_var.operator ::RID());
+ case Variant::OBJECT:
+ return GDMonoUtils::unmanaged_get_managed(p_var.operator Object *());
+ case Variant::CALLABLE: {
+ GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Callable), &from);
+ }
+ case Variant::SIGNAL: {
+ GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(SignalInfo), &from);
+ }
+ case Variant::DICTIONARY:
+ return GDMonoUtils::create_managed_from(p_var.operator Dictionary(), CACHED_CLASS(Dictionary));
+ case Variant::ARRAY:
+ return GDMonoUtils::create_managed_from(p_var.operator Array(), CACHED_CLASS(Array));
+ case Variant::PACKED_BYTE_ARRAY:
+ return (MonoObject *)PackedByteArray_to_mono_array(p_var.operator PackedByteArray());
+ case Variant::PACKED_INT32_ARRAY:
+ return (MonoObject *)PackedInt32Array_to_mono_array(p_var.operator PackedInt32Array());
+ case Variant::PACKED_INT64_ARRAY:
+ return (MonoObject *)PackedInt64Array_to_mono_array(p_var.operator PackedInt64Array());
+ case Variant::PACKED_FLOAT32_ARRAY:
+ return (MonoObject *)PackedFloat32Array_to_mono_array(p_var.operator PackedFloat32Array());
+ case Variant::PACKED_FLOAT64_ARRAY:
+ return (MonoObject *)PackedFloat64Array_to_mono_array(p_var.operator PackedFloat64Array());
+ case Variant::PACKED_STRING_ARRAY:
+ return (MonoObject *)PackedStringArray_to_mono_array(p_var.operator PackedStringArray());
+ case Variant::PACKED_VECTOR2_ARRAY:
+ return (MonoObject *)PackedVector2Array_to_mono_array(p_var.operator PackedVector2Array());
+ case Variant::PACKED_VECTOR3_ARRAY:
+ return (MonoObject *)PackedVector3Array_to_mono_array(p_var.operator PackedVector3Array());
+ case Variant::PACKED_COLOR_ARRAY:
+ return (MonoObject *)PackedColorArray_to_mono_array(p_var.operator PackedColorArray());
+ default:
+ return nullptr;
+ }
+}
+
+size_t variant_get_managed_unboxed_size(const ManagedType &p_type) {
+ // This method prints no errors for unsupported types. It's called on all methods, not only
+ // those that end up being invoked with Variant parameters.
+
+ // For MonoObject* we return 0, as it doesn't need to be stored.
+ constexpr size_t zero_for_mono_object = 0;
+
+ switch (p_type.type_encoding) {
+ case MONO_TYPE_BOOLEAN:
+ return sizeof(MonoBoolean);
+ case MONO_TYPE_CHAR:
+ return sizeof(uint16_t);
+ case MONO_TYPE_I1:
+ return sizeof(int8_t);
+ case MONO_TYPE_I2:
+ return sizeof(int16_t);
+ case MONO_TYPE_I4:
+ return sizeof(int32_t);
+ case MONO_TYPE_I8:
+ return sizeof(int64_t);
+ case MONO_TYPE_U1:
+ return sizeof(uint8_t);
+ case MONO_TYPE_U2:
+ return sizeof(uint16_t);
+ case MONO_TYPE_U4:
+ return sizeof(uint32_t);
+ case MONO_TYPE_U8:
+ return sizeof(uint64_t);
+ case MONO_TYPE_R4:
+ return sizeof(float);
+ case MONO_TYPE_R8:
+ return sizeof(double);
+ case MONO_TYPE_VALUETYPE: {
+ GDMonoClass *vtclass = p_type.type_class;
+
+#define RETURN_CHECK_FOR_STRUCT(m_struct) \
+ if (vtclass == CACHED_CLASS(m_struct)) { \
+ return sizeof(M_##m_struct); \
+ }
+
+ RETURN_CHECK_FOR_STRUCT(Vector2);
+ RETURN_CHECK_FOR_STRUCT(Vector2i);
+ RETURN_CHECK_FOR_STRUCT(Rect2);
+ RETURN_CHECK_FOR_STRUCT(Rect2i);
+ RETURN_CHECK_FOR_STRUCT(Transform2D);
+ RETURN_CHECK_FOR_STRUCT(Vector3);
+ RETURN_CHECK_FOR_STRUCT(Vector3i);
+ RETURN_CHECK_FOR_STRUCT(Basis);
+ RETURN_CHECK_FOR_STRUCT(Quat);
+ RETURN_CHECK_FOR_STRUCT(Transform);
+ RETURN_CHECK_FOR_STRUCT(AABB);
+ RETURN_CHECK_FOR_STRUCT(Color);
+ RETURN_CHECK_FOR_STRUCT(Plane);
+ RETURN_CHECK_FOR_STRUCT(Callable);
+ RETURN_CHECK_FOR_STRUCT(SignalInfo);
+
+#undef RETURN_CHECK_FOR_STRUCT
+
+ if (mono_class_is_enum(vtclass->get_mono_ptr())) {
+ MonoType *enum_basetype = mono_class_enum_basetype(vtclass->get_mono_ptr());
+ switch (mono_type_get_type(enum_basetype)) {
+ case MONO_TYPE_BOOLEAN:
+ return sizeof(MonoBoolean);
+ case MONO_TYPE_CHAR:
+ return sizeof(uint16_t);
+ case MONO_TYPE_I1:
+ return sizeof(int8_t);
+ case MONO_TYPE_I2:
+ return sizeof(int16_t);
+ case MONO_TYPE_I4:
+ return sizeof(int32_t);
+ case MONO_TYPE_I8:
+ return sizeof(int64_t);
+ case MONO_TYPE_U1:
+ return sizeof(uint8_t);
+ case MONO_TYPE_U2:
+ return sizeof(uint16_t);
+ case MONO_TYPE_U4:
+ return sizeof(uint32_t);
+ case MONO_TYPE_U8:
+ return sizeof(uint64_t);
+ default: {
+ // Enum with unsupported base type. We return nullptr MonoObject* on error.
+ return zero_for_mono_object;
+ }
+ }
+ }
- type.type_encoding = MONO_TYPE_OBJECT;
- // type.type_class is not needed when we specify the MONO_TYPE_OBJECT encoding
+ // Enum with unsupported value type. We return nullptr MonoObject* on error.
+ } break;
+ case MONO_TYPE_STRING:
+ return zero_for_mono_object;
+ case MONO_TYPE_ARRAY:
+ case MONO_TYPE_SZARRAY:
+ case MONO_TYPE_CLASS:
+ case MONO_TYPE_GENERICINST:
+ return zero_for_mono_object;
+ case MONO_TYPE_OBJECT:
+ return zero_for_mono_object;
+ }
- return variant_to_mono_object(p_var, type);
+ // Unsupported type encoding. We return nullptr MonoObject* on error.
+ return zero_for_mono_object;
}
-MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_type) {
+void *variant_to_managed_unboxed(const Variant &p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset) {
+#define RETURN_TYPE_VAL(m_type, m_val) \
+ *reinterpret_cast<m_type *>(r_buffer) = m_val; \
+ r_offset += sizeof(m_type); \
+ return r_buffer;
+
+ switch (p_type.type_encoding) {
+ case MONO_TYPE_BOOLEAN:
+ RETURN_TYPE_VAL(MonoBoolean, (MonoBoolean)p_var.operator bool());
+ case MONO_TYPE_CHAR:
+ RETURN_TYPE_VAL(uint16_t, p_var.operator unsigned short());
+ case MONO_TYPE_I1:
+ RETURN_TYPE_VAL(int8_t, p_var.operator signed char());
+ case MONO_TYPE_I2:
+ RETURN_TYPE_VAL(int16_t, p_var.operator signed short());
+ case MONO_TYPE_I4:
+ RETURN_TYPE_VAL(int32_t, p_var.operator signed int());
+ case MONO_TYPE_I8:
+ RETURN_TYPE_VAL(int64_t, p_var.operator int64_t());
+ case MONO_TYPE_U1:
+ RETURN_TYPE_VAL(uint8_t, p_var.operator unsigned char());
+ case MONO_TYPE_U2:
+ RETURN_TYPE_VAL(uint16_t, p_var.operator unsigned short());
+ case MONO_TYPE_U4:
+ RETURN_TYPE_VAL(uint32_t, p_var.operator unsigned int());
+ case MONO_TYPE_U8:
+ RETURN_TYPE_VAL(uint64_t, p_var.operator uint64_t());
+ case MONO_TYPE_R4:
+ RETURN_TYPE_VAL(float, p_var.operator float());
+ case MONO_TYPE_R8:
+ RETURN_TYPE_VAL(double, p_var.operator double());
+ case MONO_TYPE_VALUETYPE: {
+ GDMonoClass *vtclass = p_type.type_class;
+
+#define RETURN_CHECK_FOR_STRUCT(m_struct) \
+ if (vtclass == CACHED_CLASS(m_struct)) { \
+ GDMonoMarshal::M_##m_struct from = MARSHALLED_OUT(m_struct, p_var.operator ::m_struct()); \
+ RETURN_TYPE_VAL(M_##m_struct, from); \
+ }
+
+ RETURN_CHECK_FOR_STRUCT(Vector2);
+ RETURN_CHECK_FOR_STRUCT(Vector2i);
+ RETURN_CHECK_FOR_STRUCT(Rect2);
+ RETURN_CHECK_FOR_STRUCT(Rect2i);
+ RETURN_CHECK_FOR_STRUCT(Transform2D);
+ RETURN_CHECK_FOR_STRUCT(Vector3);
+ RETURN_CHECK_FOR_STRUCT(Vector3i);
+ RETURN_CHECK_FOR_STRUCT(Basis);
+ RETURN_CHECK_FOR_STRUCT(Quat);
+ RETURN_CHECK_FOR_STRUCT(Transform);
+ RETURN_CHECK_FOR_STRUCT(AABB);
+ RETURN_CHECK_FOR_STRUCT(Color);
+ RETURN_CHECK_FOR_STRUCT(Plane);
+
+#undef RETURN_CHECK_FOR_STRUCT
+
+ if (vtclass == CACHED_CLASS(Callable)) {
+ GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
+ RETURN_TYPE_VAL(M_Callable, from);
+ }
+
+ if (vtclass == CACHED_CLASS(SignalInfo)) {
+ GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
+ RETURN_TYPE_VAL(M_SignalInfo, from);
+ }
+
+ if (mono_class_is_enum(vtclass->get_mono_ptr())) {
+ MonoType *enum_basetype = mono_class_enum_basetype(vtclass->get_mono_ptr());
+ switch (mono_type_get_type(enum_basetype)) {
+ case MONO_TYPE_BOOLEAN: {
+ MonoBoolean val = p_var.operator bool();
+ RETURN_TYPE_VAL(MonoBoolean, val);
+ }
+ case MONO_TYPE_CHAR: {
+ uint16_t val = p_var.operator unsigned short();
+ RETURN_TYPE_VAL(uint16_t, val);
+ }
+ case MONO_TYPE_I1: {
+ int8_t val = p_var.operator signed char();
+ RETURN_TYPE_VAL(int8_t, val);
+ }
+ case MONO_TYPE_I2: {
+ int16_t val = p_var.operator signed short();
+ RETURN_TYPE_VAL(int16_t, val);
+ }
+ case MONO_TYPE_I4: {
+ int32_t val = p_var.operator signed int();
+ RETURN_TYPE_VAL(int32_t, val);
+ }
+ case MONO_TYPE_I8: {
+ int64_t val = p_var.operator int64_t();
+ RETURN_TYPE_VAL(int64_t, val);
+ }
+ case MONO_TYPE_U1: {
+ uint8_t val = p_var.operator unsigned char();
+ RETURN_TYPE_VAL(uint8_t, val);
+ }
+ case MONO_TYPE_U2: {
+ uint16_t val = p_var.operator unsigned short();
+ RETURN_TYPE_VAL(uint16_t, val);
+ }
+ case MONO_TYPE_U4: {
+ uint32_t val = p_var.operator unsigned int();
+ RETURN_TYPE_VAL(uint32_t, val);
+ }
+ case MONO_TYPE_U8: {
+ uint64_t val = p_var.operator uint64_t();
+ RETURN_TYPE_VAL(uint64_t, val);
+ }
+ default: {
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to enum value of unsupported base type: '" +
+ GDMonoClass::get_full_name(mono_class_from_mono_type(enum_basetype)) + "'.");
+ }
+ }
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported value type: '" +
+ p_type.type_class->get_full_name() + "'.");
+ } break;
+#undef RETURN_TYPE_VAL
+ case MONO_TYPE_STRING:
+ return variant_to_mono_string(p_var);
+ case MONO_TYPE_ARRAY:
+ case MONO_TYPE_SZARRAY:
+ return variant_to_mono_array(p_var, p_type.type_class);
+ case MONO_TYPE_CLASS:
+ return variant_to_mono_object_of_class(p_var, p_type.type_class);
+ case MONO_TYPE_GENERICINST:
+ return variant_to_mono_object_of_genericinst(p_var, p_type.type_class);
+ case MONO_TYPE_OBJECT:
+ return variant_to_mono_object(p_var);
+ }
+
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type with encoding: " +
+ itos(p_type.type_encoding) + ".");
+}
+
+MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_type) {
switch (p_type.type_encoding) {
case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_var->operator bool();
+ MonoBoolean val = p_var.operator bool();
return BOX_BOOLEAN(val);
}
-
case MONO_TYPE_CHAR: {
- uint16_t val = p_var->operator unsigned short();
+ uint16_t val = p_var.operator unsigned short();
return BOX_UINT16(val);
}
-
case MONO_TYPE_I1: {
- int8_t val = p_var->operator signed char();
+ int8_t val = p_var.operator signed char();
return BOX_INT8(val);
}
case MONO_TYPE_I2: {
- int16_t val = p_var->operator signed short();
+ int16_t val = p_var.operator signed short();
return BOX_INT16(val);
}
case MONO_TYPE_I4: {
- int32_t val = p_var->operator signed int();
+ int32_t val = p_var.operator signed int();
return BOX_INT32(val);
}
case MONO_TYPE_I8: {
- int64_t val = p_var->operator int64_t();
+ int64_t val = p_var.operator int64_t();
return BOX_INT64(val);
}
-
case MONO_TYPE_U1: {
- uint8_t val = p_var->operator unsigned char();
+ uint8_t val = p_var.operator unsigned char();
return BOX_UINT8(val);
}
case MONO_TYPE_U2: {
- uint16_t val = p_var->operator unsigned short();
+ uint16_t val = p_var.operator unsigned short();
return BOX_UINT16(val);
}
case MONO_TYPE_U4: {
- uint32_t val = p_var->operator unsigned int();
+ uint32_t val = p_var.operator unsigned int();
return BOX_UINT32(val);
}
case MONO_TYPE_U8: {
- uint64_t val = p_var->operator uint64_t();
+ uint64_t val = p_var.operator uint64_t();
return BOX_UINT64(val);
}
-
case MONO_TYPE_R4: {
- float val = p_var->operator float();
+ float val = p_var.operator float();
return BOX_FLOAT(val);
}
case MONO_TYPE_R8: {
- double val = p_var->operator double();
+ double val = p_var.operator double();
return BOX_DOUBLE(val);
}
-
- case MONO_TYPE_STRING: {
- if (p_var->get_type() == Variant::NIL)
- return nullptr; // Otherwise, Variant -> String would return the string "Null"
- return (MonoObject *)mono_string_from_godot(p_var->operator String());
- } break;
-
case MONO_TYPE_VALUETYPE: {
GDMonoClass *vtclass = p_type.type_class;
- if (vtclass == CACHED_CLASS(Vector2)) {
- GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_var->operator ::Vector2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from);
- }
-
- if (vtclass == CACHED_CLASS(Vector2i)) {
- GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var->operator ::Vector2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from);
- }
-
- if (vtclass == CACHED_CLASS(Rect2)) {
- GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var->operator ::Rect2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from);
- }
-
- if (vtclass == CACHED_CLASS(Rect2i)) {
- GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var->operator ::Rect2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from);
- }
-
- if (vtclass == CACHED_CLASS(Transform2D)) {
- GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var->operator ::Transform2D());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from);
- }
-
- if (vtclass == CACHED_CLASS(Vector3)) {
- GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_var->operator ::Vector3());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from);
- }
-
- if (vtclass == CACHED_CLASS(Vector3i)) {
- GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var->operator ::Vector3i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from);
- }
-
- if (vtclass == CACHED_CLASS(Basis)) {
- GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var->operator ::Basis());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from);
- }
-
- if (vtclass == CACHED_CLASS(Quat)) {
- GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_var->operator ::Quat());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quat), &from);
- }
-
- if (vtclass == CACHED_CLASS(Transform)) {
- GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_var->operator ::Transform());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform), &from);
- }
-
- if (vtclass == CACHED_CLASS(AABB)) {
- GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_var->operator ::AABB());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(AABB), &from);
- }
-
- if (vtclass == CACHED_CLASS(Color)) {
- GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_var->operator ::Color());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Color), &from);
- }
+#define RETURN_CHECK_FOR_STRUCT(m_struct) \
+ if (vtclass == CACHED_CLASS(m_struct)) { \
+ GDMonoMarshal::M_##m_struct from = MARSHALLED_OUT(m_struct, p_var.operator ::m_struct()); \
+ return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(m_struct), &from); \
+ }
- if (vtclass == CACHED_CLASS(Plane)) {
- GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_var->operator ::Plane());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Plane), &from);
- }
+ RETURN_CHECK_FOR_STRUCT(Vector2);
+ RETURN_CHECK_FOR_STRUCT(Vector2i);
+ RETURN_CHECK_FOR_STRUCT(Rect2);
+ RETURN_CHECK_FOR_STRUCT(Rect2i);
+ RETURN_CHECK_FOR_STRUCT(Transform2D);
+ RETURN_CHECK_FOR_STRUCT(Vector3);
+ RETURN_CHECK_FOR_STRUCT(Vector3i);
+ RETURN_CHECK_FOR_STRUCT(Basis);
+ RETURN_CHECK_FOR_STRUCT(Quat);
+ RETURN_CHECK_FOR_STRUCT(Transform);
+ RETURN_CHECK_FOR_STRUCT(AABB);
+ RETURN_CHECK_FOR_STRUCT(Color);
+ RETURN_CHECK_FOR_STRUCT(Plane);
+
+#undef RETURN_CHECK_FOR_STRUCT
if (vtclass == CACHED_CLASS(Callable)) {
- GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var->operator Callable());
+ GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var.operator Callable());
return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Callable), &from);
}
if (vtclass == CACHED_CLASS(SignalInfo)) {
- GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var->operator Signal());
+ GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var.operator Signal());
return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(SignalInfo), &from);
}
@@ -497,306 +903,84 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty
MonoClass *enum_baseclass = mono_class_from_mono_type(enum_basetype);
switch (mono_type_get_type(enum_basetype)) {
case MONO_TYPE_BOOLEAN: {
- MonoBoolean val = p_var->operator bool();
+ MonoBoolean val = p_var.operator bool();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_CHAR: {
- uint16_t val = p_var->operator unsigned short();
+ uint16_t val = p_var.operator unsigned short();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_I1: {
- int8_t val = p_var->operator signed char();
+ int8_t val = p_var.operator signed char();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_I2: {
- int16_t val = p_var->operator signed short();
+ int16_t val = p_var.operator signed short();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_I4: {
- int32_t val = p_var->operator signed int();
+ int32_t val = p_var.operator signed int();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_I8: {
- int64_t val = p_var->operator int64_t();
+ int64_t val = p_var.operator int64_t();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_U1: {
- uint8_t val = p_var->operator unsigned char();
+ uint8_t val = p_var.operator unsigned char();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_U2: {
- uint16_t val = p_var->operator unsigned short();
+ uint16_t val = p_var.operator unsigned short();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_U4: {
- uint32_t val = p_var->operator unsigned int();
+ uint32_t val = p_var.operator unsigned int();
return BOX_ENUM(enum_baseclass, val);
}
case MONO_TYPE_U8: {
- uint64_t val = p_var->operator uint64_t();
+ uint64_t val = p_var.operator uint64_t();
return BOX_ENUM(enum_baseclass, val);
}
default: {
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to a managed enum value of unmarshallable base type.");
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to enum value of unsupported base type: '" +
+ GDMonoClass::get_full_name(enum_baseclass) + "'.");
}
}
}
- } break;
-
- case MONO_TYPE_ARRAY:
- case MONO_TYPE_SZARRAY: {
- MonoArrayType *array_type = mono_type_get_array_type(p_type.type_class->get_mono_type());
-
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject))
- return (MonoObject *)Array_to_mono_array(p_var->operator Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t))
- return (MonoObject *)PackedByteArray_to_mono_array(p_var->operator PackedByteArray());
-
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t))
- return (MonoObject *)PackedInt32Array_to_mono_array(p_var->operator PackedInt32Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t))
- return (MonoObject *)PackedInt64Array_to_mono_array(p_var->operator PackedInt64Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(float))
- return (MonoObject *)PackedFloat32Array_to_mono_array(p_var->operator PackedFloat32Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(double))
- return (MonoObject *)PackedFloat64Array_to_mono_array(p_var->operator PackedFloat64Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(String))
- return (MonoObject *)PackedStringArray_to_mono_array(p_var->operator PackedStringArray());
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2))
- return (MonoObject *)PackedVector2Array_to_mono_array(p_var->operator PackedVector2Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3))
- return (MonoObject *)PackedVector3Array_to_mono_array(p_var->operator PackedVector3Array());
-
- if (array_type->eklass == CACHED_CLASS_RAW(Color))
- return (MonoObject *)PackedColorArray_to_mono_array(p_var->operator PackedColorArray());
-
- GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(array_type->eklass);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class))
- return (MonoObject *)Array_to_mono_array(p_var->operator Array(), array_type_class);
-
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to a managed array of unmarshallable element type.");
- } break;
-
- case MONO_TYPE_CLASS: {
- GDMonoClass *type_class = p_type.type_class;
-
- // GodotObject
- if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) {
- return GDMonoUtils::unmanaged_get_managed(p_var->operator Object *());
- }
-
- if (CACHED_CLASS(StringName) == type_class) {
- return GDMonoUtils::create_managed_from(p_var->operator StringName());
- }
-
- if (CACHED_CLASS(NodePath) == type_class) {
- return GDMonoUtils::create_managed_from(p_var->operator NodePath());
- }
-
- if (CACHED_CLASS(RID) == type_class) {
- return GDMonoUtils::create_managed_from(p_var->operator RID());
- }
-
- // Godot.Collections.Dictionary or IDictionary
- if (CACHED_CLASS(Dictionary) == type_class || CACHED_CLASS(System_Collections_IDictionary) == type_class) {
- return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), CACHED_CLASS(Dictionary));
- }
-
- // Godot.Collections.Array or ICollection or IEnumerable
- if (CACHED_CLASS(Array) == type_class ||
- CACHED_CLASS(System_Collections_ICollection) == type_class ||
- CACHED_CLASS(System_Collections_IEnumerable) == type_class) {
- return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
- }
- } break;
- case MONO_TYPE_OBJECT: {
- // Variant
- switch (p_var->get_type()) {
- case Variant::BOOL: {
- MonoBoolean val = p_var->operator bool();
- return BOX_BOOLEAN(val);
- }
- case Variant::INT: {
- int32_t val = p_var->operator signed int();
- return BOX_INT32(val);
- }
- case Variant::FLOAT: {
-#ifdef REAL_T_IS_DOUBLE
- double val = p_var->operator double();
- return BOX_DOUBLE(val);
-#else
- float val = p_var->operator float();
- return BOX_FLOAT(val);
-#endif
- }
- case Variant::STRING:
- return (MonoObject *)mono_string_from_godot(p_var->operator String());
- case Variant::VECTOR2: {
- GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_var->operator ::Vector2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from);
- }
- case Variant::VECTOR2I: {
- GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var->operator ::Vector2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from);
- }
- case Variant::RECT2: {
- GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var->operator ::Rect2());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from);
- }
- case Variant::RECT2I: {
- GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var->operator ::Rect2i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from);
- }
- case Variant::VECTOR3: {
- GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_var->operator ::Vector3());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from);
- }
- case Variant::VECTOR3I: {
- GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var->operator ::Vector3i());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from);
- }
- case Variant::TRANSFORM2D: {
- GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var->operator ::Transform2D());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from);
- }
- case Variant::PLANE: {
- GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_var->operator ::Plane());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Plane), &from);
- }
- case Variant::QUAT: {
- GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_var->operator ::Quat());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quat), &from);
- }
- case Variant::AABB: {
- GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_var->operator ::AABB());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(AABB), &from);
- }
- case Variant::BASIS: {
- GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var->operator ::Basis());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from);
- }
- case Variant::TRANSFORM: {
- GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_var->operator ::Transform());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform), &from);
- }
- case Variant::COLOR: {
- GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_var->operator ::Color());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Color), &from);
- }
- case Variant::STRING_NAME:
- return GDMonoUtils::create_managed_from(p_var->operator StringName());
- case Variant::NODE_PATH:
- return GDMonoUtils::create_managed_from(p_var->operator NodePath());
- case Variant::_RID:
- return GDMonoUtils::create_managed_from(p_var->operator RID());
- case Variant::OBJECT:
- return GDMonoUtils::unmanaged_get_managed(p_var->operator Object *());
- case Variant::CALLABLE: {
- GDMonoMarshal::M_Callable from = GDMonoMarshal::callable_to_managed(p_var->operator Callable());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Callable), &from);
- }
- case Variant::SIGNAL: {
- GDMonoMarshal::M_SignalInfo from = GDMonoMarshal::signal_info_to_managed(p_var->operator Signal());
- return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(SignalInfo), &from);
- }
- case Variant::DICTIONARY:
- return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), CACHED_CLASS(Dictionary));
- case Variant::ARRAY:
- return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
- case Variant::PACKED_BYTE_ARRAY:
- return (MonoObject *)PackedByteArray_to_mono_array(p_var->operator PackedByteArray());
- case Variant::PACKED_INT32_ARRAY:
- return (MonoObject *)PackedInt32Array_to_mono_array(p_var->operator PackedInt32Array());
- case Variant::PACKED_INT64_ARRAY:
- return (MonoObject *)PackedInt64Array_to_mono_array(p_var->operator PackedInt64Array());
- case Variant::PACKED_FLOAT32_ARRAY:
- return (MonoObject *)PackedFloat32Array_to_mono_array(p_var->operator PackedFloat32Array());
- case Variant::PACKED_FLOAT64_ARRAY:
- return (MonoObject *)PackedFloat64Array_to_mono_array(p_var->operator PackedFloat64Array());
- case Variant::PACKED_STRING_ARRAY:
- return (MonoObject *)PackedStringArray_to_mono_array(p_var->operator PackedStringArray());
- case Variant::PACKED_VECTOR2_ARRAY:
- return (MonoObject *)PackedVector2Array_to_mono_array(p_var->operator PackedVector2Array());
- case Variant::PACKED_VECTOR3_ARRAY:
- return (MonoObject *)PackedVector3Array_to_mono_array(p_var->operator PackedVector3Array());
- case Variant::PACKED_COLOR_ARRAY:
- return (MonoObject *)PackedColorArray_to_mono_array(p_var->operator PackedColorArray());
- default:
- return nullptr;
- }
- break;
- case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
-
- // Godot.Collections.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
- return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), p_type.type_class);
- }
-
- // Godot.Collections.Array<T>
- if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
- return GDMonoUtils::create_managed_from(p_var->operator Array(), p_type.type_class);
- }
-
- // System.Collections.Generic.Dictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_system_generic_dictionary(reftype)) {
- MonoReflectionType *key_reftype = nullptr;
- MonoReflectionType *value_reftype = nullptr;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- return Dictionary_to_system_generic_dict(p_var->operator Dictionary(), p_type.type_class, key_reftype, value_reftype);
- }
-
- // System.Collections.Generic.List<T>
- if (GDMonoUtils::Marshal::type_is_system_generic_list(reftype)) {
- MonoReflectionType *elem_reftype = nullptr;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- return Array_to_system_generic_list(p_var->operator Array(), p_type.type_class, elem_reftype);
- }
-
- // IDictionary<TKey, TValue>
- if (GDMonoUtils::Marshal::type_is_generic_idictionary(reftype)) {
- MonoReflectionType *key_reftype;
- MonoReflectionType *value_reftype;
- GDMonoUtils::Marshal::dictionary_get_key_value_types(reftype, &key_reftype, &value_reftype);
- GDMonoClass *godot_dict_class = GDMonoUtils::Marshal::make_generic_dictionary_type(key_reftype, value_reftype);
-
- return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), godot_dict_class);
- }
-
- // ICollection<T> or IEnumerable<T>
- if (GDMonoUtils::Marshal::type_is_generic_icollection(reftype) || GDMonoUtils::Marshal::type_is_generic_ienumerable(reftype)) {
- MonoReflectionType *elem_reftype;
- GDMonoUtils::Marshal::array_get_element_type(reftype, &elem_reftype);
- GDMonoClass *godot_array_class = GDMonoUtils::Marshal::make_generic_array_type(elem_reftype);
- return GDMonoUtils::create_managed_from(p_var->operator Array(), godot_array_class);
- }
- } break;
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported value type: '" +
+ p_type.type_class->get_full_name() + "'.");
} break;
+ case MONO_TYPE_STRING:
+ return (MonoObject *)variant_to_mono_string(p_var);
+ case MONO_TYPE_ARRAY:
+ case MONO_TYPE_SZARRAY:
+ return (MonoObject *)variant_to_mono_array(p_var, p_type.type_class);
+ case MONO_TYPE_CLASS:
+ return variant_to_mono_object_of_class(p_var, p_type.type_class);
+ case MONO_TYPE_GENERICINST:
+ return variant_to_mono_object_of_genericinst(p_var, p_type.type_class);
+ case MONO_TYPE_OBJECT:
+ return variant_to_mono_object(p_var);
}
- ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to an unmarshallable managed type. Name: '" +
- p_type.type_class->get_name() + "' Encoding: " + itos(p_type.type_encoding) + ".");
+ ERR_FAIL_V_MSG(nullptr, "Attempted to convert Variant to unsupported type with encoding: " +
+ itos(p_type.type_encoding) + ".");
}
Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type, bool p_fail_with_err = true) {
-
ERR_FAIL_COND_V(!p_type.type_class, Variant());
+#ifdef DEBUG_ENABLED
+ CRASH_COND_MSG(p_type.type_encoding == MONO_TYPE_OBJECT, "Type of object should be known.");
+#endif
+
switch (p_type.type_encoding) {
case MONO_TYPE_BOOLEAN:
return (bool)unbox<MonoBoolean>(p_obj);
-
case MONO_TYPE_CHAR:
return unbox<uint16_t>(p_obj);
-
case MONO_TYPE_I1:
return unbox<int8_t>(p_obj);
case MONO_TYPE_I2:
@@ -805,7 +989,6 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type
return unbox<int32_t>(p_obj);
case MONO_TYPE_I8:
return unbox<int64_t>(p_obj);
-
case MONO_TYPE_U1:
return unbox<uint8_t>(p_obj);
case MONO_TYPE_U2:
@@ -814,107 +997,131 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type
return unbox<uint32_t>(p_obj);
case MONO_TYPE_U8:
return unbox<uint64_t>(p_obj);
-
case MONO_TYPE_R4:
return unbox<float>(p_obj);
case MONO_TYPE_R8:
return unbox<double>(p_obj);
-
- case MONO_TYPE_STRING: {
- if (p_obj == nullptr)
- return Variant(); // NIL
- return mono_string_to_godot_not_null((MonoString *)p_obj);
- } break;
-
case MONO_TYPE_VALUETYPE: {
GDMonoClass *vtclass = p_type.type_class;
- if (vtclass == CACHED_CLASS(Vector2))
+ if (vtclass == CACHED_CLASS(Vector2)) {
return MARSHALLED_IN(Vector2, unbox_addr<GDMonoMarshal::M_Vector2>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Vector2i))
+ if (vtclass == CACHED_CLASS(Vector2i)) {
return MARSHALLED_IN(Vector2i, unbox_addr<GDMonoMarshal::M_Vector2i>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Rect2))
+ if (vtclass == CACHED_CLASS(Rect2)) {
return MARSHALLED_IN(Rect2, unbox_addr<GDMonoMarshal::M_Rect2>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Rect2i))
+ if (vtclass == CACHED_CLASS(Rect2i)) {
return MARSHALLED_IN(Rect2i, unbox_addr<GDMonoMarshal::M_Rect2i>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Transform2D))
+ if (vtclass == CACHED_CLASS(Transform2D)) {
return MARSHALLED_IN(Transform2D, unbox_addr<GDMonoMarshal::M_Transform2D>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Vector3))
+ if (vtclass == CACHED_CLASS(Vector3)) {
return MARSHALLED_IN(Vector3, unbox_addr<GDMonoMarshal::M_Vector3>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Vector3i))
+ if (vtclass == CACHED_CLASS(Vector3i)) {
return MARSHALLED_IN(Vector3i, unbox_addr<GDMonoMarshal::M_Vector3i>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Basis))
+ if (vtclass == CACHED_CLASS(Basis)) {
return MARSHALLED_IN(Basis, unbox_addr<GDMonoMarshal::M_Basis>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Quat))
+ if (vtclass == CACHED_CLASS(Quat)) {
return MARSHALLED_IN(Quat, unbox_addr<GDMonoMarshal::M_Quat>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Transform))
+ if (vtclass == CACHED_CLASS(Transform)) {
return MARSHALLED_IN(Transform, unbox_addr<GDMonoMarshal::M_Transform>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(AABB))
+ if (vtclass == CACHED_CLASS(AABB)) {
return MARSHALLED_IN(AABB, unbox_addr<GDMonoMarshal::M_AABB>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Color))
+ if (vtclass == CACHED_CLASS(Color)) {
return MARSHALLED_IN(Color, unbox_addr<GDMonoMarshal::M_Color>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Plane))
+ if (vtclass == CACHED_CLASS(Plane)) {
return MARSHALLED_IN(Plane, unbox_addr<GDMonoMarshal::M_Plane>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(Callable))
+ if (vtclass == CACHED_CLASS(Callable)) {
return managed_to_callable(unbox<GDMonoMarshal::M_Callable>(p_obj));
+ }
- if (vtclass == CACHED_CLASS(SignalInfo))
+ if (vtclass == CACHED_CLASS(SignalInfo)) {
return managed_to_signal_info(unbox<GDMonoMarshal::M_SignalInfo>(p_obj));
+ }
- if (mono_class_is_enum(vtclass->get_mono_ptr()))
+ if (mono_class_is_enum(vtclass->get_mono_ptr())) {
return unbox<int32_t>(p_obj);
+ }
+ } break;
+ case MONO_TYPE_STRING: {
+ if (p_obj == nullptr) {
+ return Variant(); // NIL
+ }
+ return mono_string_to_godot_not_null((MonoString *)p_obj);
} break;
-
case MONO_TYPE_ARRAY:
case MONO_TYPE_SZARRAY: {
MonoArrayType *array_type = mono_type_get_array_type(p_type.type_class->get_mono_type());
- if (array_type->eklass == CACHED_CLASS_RAW(MonoObject))
+ if (array_type->eklass == CACHED_CLASS_RAW(MonoObject)) {
return mono_array_to_Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(uint8_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(uint8_t)) {
return mono_array_to_PackedByteArray((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(int32_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(int32_t)) {
return mono_array_to_PackedInt32Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(int64_t))
+ if (array_type->eklass == CACHED_CLASS_RAW(int64_t)) {
return mono_array_to_PackedInt64Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(float))
+ if (array_type->eklass == CACHED_CLASS_RAW(float)) {
return mono_array_to_PackedFloat32Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(double))
+ if (array_type->eklass == CACHED_CLASS_RAW(double)) {
return mono_array_to_PackedFloat64Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(String))
+ if (array_type->eklass == CACHED_CLASS_RAW(String)) {
return mono_array_to_PackedStringArray((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Vector2))
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector2)) {
return mono_array_to_PackedVector2Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Vector3))
+ if (array_type->eklass == CACHED_CLASS_RAW(Vector3)) {
return mono_array_to_PackedVector3Array((MonoArray *)p_obj);
+ }
- if (array_type->eklass == CACHED_CLASS_RAW(Color))
+ if (array_type->eklass == CACHED_CLASS_RAW(Color)) {
return mono_array_to_PackedColorArray((MonoArray *)p_obj);
+ }
GDMonoClass *array_type_class = GDMono::get_singleton()->get_class(array_type->eklass);
- if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class))
+ if (CACHED_CLASS(GodotObject)->is_assignable_from(array_type_class)) {
return mono_array_to_Array((MonoArray *)p_obj);
+ }
if (p_fail_with_err) {
ERR_FAIL_V_MSG(Variant(), "Attempted to convert a managed array of unmarshallable element type to Variant.");
@@ -922,7 +1129,6 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type
return Variant();
}
} break;
-
case MONO_TYPE_CLASS: {
GDMonoClass *type_class = p_type.type_class;
@@ -967,7 +1173,6 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type
return ptr ? Variant(*ptr) : Variant();
}
} break;
-
case MONO_TYPE_GENERICINST: {
MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
@@ -1013,8 +1218,9 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type
}
Variant mono_object_to_variant(MonoObject *p_obj) {
- if (!p_obj)
+ if (!p_obj) {
return Variant();
+ }
ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj));
@@ -1022,31 +1228,38 @@ Variant mono_object_to_variant(MonoObject *p_obj) {
}
Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type) {
- if (!p_obj)
+ if (!p_obj) {
return Variant();
+ }
return mono_object_to_variant_impl(p_obj, p_type);
}
Variant mono_object_to_variant_no_err(MonoObject *p_obj, const ManagedType &p_type) {
- if (!p_obj)
+ if (!p_obj) {
return Variant();
+ }
return mono_object_to_variant_impl(p_obj, p_type, /* fail_with_err: */ false);
}
String mono_object_to_variant_string(MonoObject *p_obj, MonoException **r_exc) {
+ if (p_obj == nullptr) {
+ return String("null");
+ }
+
ManagedType type = ManagedType::from_class(mono_object_get_class(p_obj));
Variant var = GDMonoMarshal::mono_object_to_variant_no_err(p_obj, type);
- if (var.get_type() == Variant::NIL && p_obj != nullptr) {
+ if (var.get_type() == Variant::NIL) { // `&& p_obj != nullptr` but omitted because always true
// Cannot convert MonoObject* to Variant; fallback to 'ToString()'.
MonoException *exc = nullptr;
MonoString *mono_str = GDMonoUtils::object_to_string(p_obj, &exc);
if (exc) {
- if (r_exc)
+ if (r_exc) {
*r_exc = exc;
+ }
return String();
}
@@ -1101,9 +1314,10 @@ Dictionary system_generic_dict_to_Dictionary(MonoObject *p_obj, [[maybe_unused]]
}
MonoObject *Array_to_system_generic_list(const Array &p_array, GDMonoClass *p_class, MonoReflectionType *p_elem_reftype) {
- GDMonoClass *elem_class = ManagedType::from_reftype(p_elem_reftype).type_class;
+ MonoType *elem_type = mono_reflection_type_get_type(p_elem_reftype);
+ MonoClass *elem_class = mono_class_from_mono_type(elem_type);
- String ctor_desc = ":.ctor(System.Collections.Generic.IEnumerable`1<" + elem_class->get_type_desc() + ">)";
+ String ctor_desc = ":.ctor(System.Collections.Generic.IEnumerable`1<" + GDMonoUtils::get_type_desc(elem_type) + ">)";
GDMonoMethod *ctor = p_class->get_method_with_desc(ctor_desc, true);
CRASH_COND(ctor == nullptr);
@@ -1142,9 +1356,9 @@ MonoArray *Array_to_mono_array(const Array &p_array) {
return ret;
}
-MonoArray *Array_to_mono_array(const Array &p_array, GDMonoClass *p_array_type_class) {
+MonoArray *Array_to_mono_array(const Array &p_array, MonoClass *p_array_type_class) {
int length = p_array.size();
- MonoArray *ret = mono_array_new(mono_domain_get(), p_array_type_class->get_mono_ptr(), length);
+ MonoArray *ret = mono_array_new(mono_domain_get(), p_array_type_class, length);
for (int i = 0; i < length; i++) {
MonoObject *boxed = variant_to_mono_object(p_array[i]);
@@ -1156,8 +1370,9 @@ MonoArray *Array_to_mono_array(const Array &p_array, GDMonoClass *p_array_type_c
Array mono_array_to_Array(MonoArray *p_array) {
Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
@@ -1175,22 +1390,23 @@ MonoArray *PackedInt32Array_to_mono_array(const PackedInt32Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(int32_t), length);
- int32_t *dst = (int32_t *)mono_array_addr(ret, int32_t, 0);
- memcpy(dst, src, length);
+ int32_t *dst = mono_array_addr(ret, int32_t, 0);
+ memcpy(dst, src, length * sizeof(int32_t));
return ret;
}
PackedInt32Array mono_array_to_PackedInt32Array(MonoArray *p_array) {
PackedInt32Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
int32_t *dst = ret.ptrw();
- const int32_t *src = (const int32_t *)mono_array_addr(p_array, int32_t, 0);
- memcpy(dst, src, length);
+ const int32_t *src = mono_array_addr(p_array, int32_t, 0);
+ memcpy(dst, src, length * sizeof(int32_t));
return ret;
}
@@ -1201,22 +1417,23 @@ MonoArray *PackedInt64Array_to_mono_array(const PackedInt64Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(int64_t), length);
- int64_t *dst = (int64_t *)mono_array_addr(ret, int64_t, 0);
- memcpy(dst, src, length);
+ int64_t *dst = mono_array_addr(ret, int64_t, 0);
+ memcpy(dst, src, length * sizeof(int64_t));
return ret;
}
PackedInt64Array mono_array_to_PackedInt64Array(MonoArray *p_array) {
PackedInt64Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
int64_t *dst = ret.ptrw();
- const int64_t *src = (const int64_t *)mono_array_addr(p_array, int64_t, 0);
- memcpy(dst, src, length);
+ const int64_t *src = mono_array_addr(p_array, int64_t, 0);
+ memcpy(dst, src, length * sizeof(int64_t));
return ret;
}
@@ -1227,22 +1444,23 @@ MonoArray *PackedByteArray_to_mono_array(const PackedByteArray &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), length);
- uint8_t *dst = (uint8_t *)mono_array_addr(ret, uint8_t, 0);
- memcpy(dst, src, length);
+ uint8_t *dst = mono_array_addr(ret, uint8_t, 0);
+ memcpy(dst, src, length * sizeof(uint8_t));
return ret;
}
PackedByteArray mono_array_to_PackedByteArray(MonoArray *p_array) {
PackedByteArray ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
uint8_t *dst = ret.ptrw();
- const uint8_t *src = (const uint8_t *)mono_array_addr(p_array, uint8_t, 0);
- memcpy(dst, src, length);
+ const uint8_t *src = mono_array_addr(p_array, uint8_t, 0);
+ memcpy(dst, src, length * sizeof(uint8_t));
return ret;
}
@@ -1253,22 +1471,23 @@ MonoArray *PackedFloat32Array_to_mono_array(const PackedFloat32Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(float), length);
- float *dst = (float *)mono_array_addr(ret, float, 0);
- memcpy(dst, src, length);
+ float *dst = mono_array_addr(ret, float, 0);
+ memcpy(dst, src, length * sizeof(float));
return ret;
}
PackedFloat32Array mono_array_to_PackedFloat32Array(MonoArray *p_array) {
PackedFloat32Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
float *dst = ret.ptrw();
- const float *src = (const float *)mono_array_addr(p_array, float, 0);
- memcpy(dst, src, length);
+ const float *src = mono_array_addr(p_array, float, 0);
+ memcpy(dst, src, length * sizeof(float));
return ret;
}
@@ -1279,22 +1498,23 @@ MonoArray *PackedFloat64Array_to_mono_array(const PackedFloat64Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(double), length);
- double *dst = (double *)mono_array_addr(ret, double, 0);
- memcpy(dst, src, length);
+ double *dst = mono_array_addr(ret, double, 0);
+ memcpy(dst, src, length * sizeof(double));
return ret;
}
PackedFloat64Array mono_array_to_PackedFloat64Array(MonoArray *p_array) {
PackedFloat64Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
double *dst = ret.ptrw();
- const double *src = (const double *)mono_array_addr(p_array, double, 0);
- memcpy(dst, src, length);
+ const double *src = mono_array_addr(p_array, double, 0);
+ memcpy(dst, src, length * sizeof(double));
return ret;
}
@@ -1315,8 +1535,9 @@ MonoArray *PackedStringArray_to_mono_array(const PackedStringArray &p_array) {
PackedStringArray mono_array_to_PackedStringArray(MonoArray *p_array) {
PackedStringArray ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
String *w = ret.ptrw();
@@ -1336,8 +1557,8 @@ MonoArray *PackedColorArray_to_mono_array(const PackedColorArray &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Color), length);
if constexpr (InteropLayout::MATCHES_Color) {
- Color *dst = (Color *)mono_array_addr(ret, Color, 0);
- memcpy(dst, src, length);
+ Color *dst = mono_array_addr(ret, Color, 0);
+ memcpy(dst, src, length * sizeof(Color));
} else {
for (int i = 0; i < length; i++) {
M_Color *raw = (M_Color *)mono_array_addr_with_size(ret, sizeof(M_Color), i);
@@ -1350,15 +1571,16 @@ MonoArray *PackedColorArray_to_mono_array(const PackedColorArray &p_array) {
PackedColorArray mono_array_to_PackedColorArray(MonoArray *p_array) {
PackedColorArray ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
Color *dst = ret.ptrw();
if constexpr (InteropLayout::MATCHES_Color) {
- const Color *src = (const Color *)mono_array_addr(p_array, Color, 0);
- memcpy(dst, src, length);
+ const Color *src = mono_array_addr(p_array, Color, 0);
+ memcpy(dst, src, length * sizeof(Color));
} else {
for (int i = 0; i < length; i++) {
dst[i] = MARSHALLED_IN(Color, (M_Color *)mono_array_addr_with_size(p_array, sizeof(M_Color), i));
@@ -1375,8 +1597,8 @@ MonoArray *PackedVector2Array_to_mono_array(const PackedVector2Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Vector2), length);
if constexpr (InteropLayout::MATCHES_Vector2) {
- Vector2 *dst = (Vector2 *)mono_array_addr(ret, Vector2, 0);
- memcpy(dst, src, length);
+ Vector2 *dst = mono_array_addr(ret, Vector2, 0);
+ memcpy(dst, src, length * sizeof(Vector2));
} else {
for (int i = 0; i < length; i++) {
M_Vector2 *raw = (M_Vector2 *)mono_array_addr_with_size(ret, sizeof(M_Vector2), i);
@@ -1389,15 +1611,16 @@ MonoArray *PackedVector2Array_to_mono_array(const PackedVector2Array &p_array) {
PackedVector2Array mono_array_to_PackedVector2Array(MonoArray *p_array) {
PackedVector2Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
Vector2 *dst = ret.ptrw();
if constexpr (InteropLayout::MATCHES_Vector2) {
- const Vector2 *src = (const Vector2 *)mono_array_addr(p_array, Vector2, 0);
- memcpy(dst, src, length);
+ const Vector2 *src = mono_array_addr(p_array, Vector2, 0);
+ memcpy(dst, src, length * sizeof(Vector2));
} else {
for (int i = 0; i < length; i++) {
dst[i] = MARSHALLED_IN(Vector2, (M_Vector2 *)mono_array_addr_with_size(p_array, sizeof(M_Vector2), i));
@@ -1414,8 +1637,8 @@ MonoArray *PackedVector3Array_to_mono_array(const PackedVector3Array &p_array) {
MonoArray *ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(Vector3), length);
if constexpr (InteropLayout::MATCHES_Vector3) {
- Vector3 *dst = (Vector3 *)mono_array_addr(ret, Vector3, 0);
- memcpy(dst, src, length);
+ Vector3 *dst = mono_array_addr(ret, Vector3, 0);
+ memcpy(dst, src, length * sizeof(Vector3));
} else {
for (int i = 0; i < length; i++) {
M_Vector3 *raw = (M_Vector3 *)mono_array_addr_with_size(ret, sizeof(M_Vector3), i);
@@ -1428,15 +1651,16 @@ MonoArray *PackedVector3Array_to_mono_array(const PackedVector3Array &p_array) {
PackedVector3Array mono_array_to_PackedVector3Array(MonoArray *p_array) {
PackedVector3Array ret;
- if (!p_array)
+ if (!p_array) {
return ret;
+ }
int length = mono_array_length(p_array);
ret.resize(length);
Vector3 *dst = ret.ptrw();
if constexpr (InteropLayout::MATCHES_Vector3) {
- const Vector3 *src = (const Vector3 *)mono_array_addr(p_array, Vector3, 0);
- memcpy(dst, src, length);
+ const Vector3 *src = mono_array_addr(p_array, Vector3, 0);
+ memcpy(dst, src, length * sizeof(Vector3));
} else {
for (int i = 0; i < length; i++) {
dst[i] = MARSHALLED_IN(Vector3, (M_Vector3 *)mono_array_addr_with_size(p_array, sizeof(M_Vector3), i));
@@ -1453,8 +1677,8 @@ Callable managed_to_callable(const M_Callable &p_managed_callable) {
return Callable(managed_callable);
} else {
Object *target = p_managed_callable.target ?
- unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_callable.target)) :
- nullptr;
+ unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_callable.target)) :
+ nullptr;
StringName *method_ptr = unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(p_managed_callable.method_string_name));
StringName method = method_ptr ? *method_ptr : StringName();
return Callable(target, method);
@@ -1499,8 +1723,8 @@ M_Callable callable_to_managed(const Callable &p_callable) {
Signal managed_to_signal_info(const M_SignalInfo &p_managed_signal) {
Object *owner = p_managed_signal.owner ?
- unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_signal.owner)) :
- nullptr;
+ unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_managed_signal.owner)) :
+ nullptr;
StringName *name_ptr = unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(p_managed_signal.name_string_name));
StringName name = name_ptr ? *name_ptr : StringName();
return Signal(owner, name);
@@ -1512,5 +1736,4 @@ M_SignalInfo signal_info_to_managed(const Signal &p_signal) {
MonoObject *name_string_name_managed = GDMonoUtils::create_managed_from(p_signal.get_name());
return { owner_managed, name_string_name_managed };
}
-
} // namespace GDMonoMarshal
diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h
index f2d887e6d6..7d0036a1d8 100644
--- a/modules/mono/mono_gd/gd_mono_marshal.h
+++ b/modules/mono/mono_gd/gd_mono_marshal.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef GDMONOMARSHAL_H
#define GDMONOMARSHAL_H
-#include "core/variant.h"
+#include "core/variant/variant.h"
#include "../managed_callable.h"
#include "gd_mono.h"
@@ -66,53 +66,64 @@ T *unbox_addr(MonoObject *p_obj) {
Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_variant = nullptr);
bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type);
-bool try_get_dictionary_key_value_types(const ManagedType &p_dictionary_type, ManagedType &r_key_type, ManagedType &r_value_type);
// String
-String mono_to_utf8_string(MonoString *p_mono_string);
-String mono_to_utf16_string(MonoString *p_mono_string);
-
_FORCE_INLINE_ String mono_string_to_godot_not_null(MonoString *p_mono_string) {
- if (sizeof(CharType) == 2)
- return mono_to_utf16_string(p_mono_string);
-
- return mono_to_utf8_string(p_mono_string);
+ char32_t *utf32 = (char32_t *)mono_string_to_utf32(p_mono_string);
+ String ret = String(utf32);
+ mono_free(utf32);
+ return ret;
}
_FORCE_INLINE_ String mono_string_to_godot(MonoString *p_mono_string) {
- if (p_mono_string == nullptr)
+ if (p_mono_string == nullptr) {
return String();
+ }
return mono_string_to_godot_not_null(p_mono_string);
}
-_FORCE_INLINE_ MonoString *mono_from_utf8_string(const String &p_string) {
- return mono_string_new(mono_domain_get(), p_string.utf8().get_data());
-}
-
-_FORCE_INLINE_ MonoString *mono_from_utf16_string(const String &p_string) {
- return mono_string_from_utf16((mono_unichar2 *)p_string.c_str());
-}
-
_FORCE_INLINE_ MonoString *mono_string_from_godot(const String &p_string) {
- if (sizeof(CharType) == 2)
- return mono_from_utf16_string(p_string);
-
- return mono_from_utf8_string(p_string);
+ return mono_string_from_utf32((mono_unichar4 *)(p_string.get_data()));
}
// Variant
-MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_type);
-MonoObject *variant_to_mono_object(const Variant *p_var);
+size_t variant_get_managed_unboxed_size(const ManagedType &p_type);
+void *variant_to_managed_unboxed(const Variant &p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset);
+MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_type);
-_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant &p_var) {
- return variant_to_mono_object(&p_var);
-}
+MonoObject *variant_to_mono_object(const Variant &p_var);
+MonoArray *variant_to_mono_array(const Variant &p_var, GDMonoClass *p_type_class);
+MonoObject *variant_to_mono_object_of_class(const Variant &p_var, GDMonoClass *p_type_class);
+MonoObject *variant_to_mono_object_of_genericinst(const Variant &p_var, GDMonoClass *p_type_class);
+MonoString *variant_to_mono_string(const Variant &p_var);
-_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_type) {
- return variant_to_mono_object(&p_var, p_type);
+// These overloads were added to avoid passing a `const Variant *` to the `const Variant &`
+// parameter. That would result in the `Variant(bool)` copy constructor being called as
+// pointers are implicitly converted to bool. Implicit conversions are f-ing evil.
+
+_FORCE_INLINE_ void *variant_to_managed_unboxed(const Variant *p_var, const ManagedType &p_type, void *r_buffer, unsigned int &r_offset) {
+ return variant_to_managed_unboxed(*p_var, p_type, r_buffer, r_offset);
+}
+_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_type) {
+ return variant_to_mono_object(*p_var, p_type);
+}
+_FORCE_INLINE_ MonoObject *variant_to_mono_object(const Variant *p_var) {
+ return variant_to_mono_object(*p_var);
+}
+_FORCE_INLINE_ MonoArray *variant_to_mono_array(const Variant *p_var, GDMonoClass *p_type_class) {
+ return variant_to_mono_array(*p_var, p_type_class);
+}
+_FORCE_INLINE_ MonoObject *variant_to_mono_object_of_class(const Variant *p_var, GDMonoClass *p_type_class) {
+ return variant_to_mono_object_of_class(*p_var, p_type_class);
+}
+_FORCE_INLINE_ MonoObject *variant_to_mono_object_of_genericinst(const Variant *p_var, GDMonoClass *p_type_class) {
+ return variant_to_mono_object_of_genericinst(*p_var, p_type_class);
+}
+_FORCE_INLINE_ MonoString *variant_to_mono_string(const Variant *p_var) {
+ return variant_to_mono_string(*p_var);
}
Variant mono_object_to_variant(MonoObject *p_obj);
@@ -134,7 +145,7 @@ Array system_generic_list_to_Array(MonoObject *p_obj, GDMonoClass *p_class, Mono
// Array
MonoArray *Array_to_mono_array(const Array &p_array);
-MonoArray *Array_to_mono_array(const Array &p_array, GDMonoClass *p_array_type_class);
+MonoArray *Array_to_mono_array(const Array &p_array, MonoClass *p_array_type_class);
Array mono_array_to_Array(MonoArray *p_array);
// PackedInt32Array
@@ -285,7 +296,6 @@ static_assert(MATCHES_Vector2 && MATCHES_Rect2 && MATCHES_Transform2D && MATCHES
MATCHES_Plane && MATCHES_Vector2i && MATCHES_Rect2i && MATCHES_Vector3i);
/* clang-format on */
#endif
-
} // namespace InteropLayout
#pragma pack(push, 1)
@@ -531,7 +541,6 @@ DECL_TYPE_MARSHAL_TEMPLATES(Plane)
#define MARSHALLED_IN(m_type, m_from_ptr) (GDMonoMarshal::marshalled_in_##m_type(m_from_ptr))
#define MARSHALLED_OUT(m_type, m_from) (GDMonoMarshal::marshalled_out_##m_type(m_from))
-
} // namespace GDMonoMarshal
#endif // GDMONOMARSHAL_H
diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp
index 432aa74a6f..67aabcde10 100644
--- a/modules/mono/mono_gd/gd_mono_method.cpp
+++ b/modules/mono/mono_gd/gd_mono_method.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -75,6 +75,10 @@ void GDMonoMethod::_update_signature(MonoMethodSignature *p_method_sig) {
// clear the cache
method_info_fetched = false;
method_info = MethodInfo();
+
+ for (int i = 0; i < params_count; i++) {
+ params_buffer_size += GDMonoMarshal::variant_get_managed_unboxed_size(param_types[i]);
+ }
}
GDMonoClass *GDMonoMethod::get_enclosing_class() const {
@@ -107,14 +111,15 @@ MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params,
MonoObject *ret;
if (params_count > 0) {
- MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), params_count);
+ void **params = (void **)alloca(params_count * sizeof(void *));
+ uint8_t *buffer = (uint8_t *)alloca(params_buffer_size);
+ unsigned int offset = 0;
for (int i = 0; i < params_count; i++) {
- MonoObject *boxed_param = GDMonoMarshal::variant_to_mono_object(p_params[i], param_types[i]);
- mono_array_setref(params, i, boxed_param);
+ params[i] = GDMonoMarshal::variant_to_managed_unboxed(p_params[i], param_types[i], buffer + offset, offset);
}
- ret = GDMonoUtils::runtime_invoke_array(mono_method, p_object, params, &exc);
+ ret = GDMonoUtils::runtime_invoke(mono_method, p_object, params, &exc);
} else {
ret = GDMonoUtils::runtime_invoke(mono_method, p_object, nullptr, &exc);
}
@@ -155,11 +160,13 @@ MonoObject *GDMonoMethod::invoke_raw(MonoObject *p_object, void **p_params, Mono
bool GDMonoMethod::has_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, false);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return false;
+ }
return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}
@@ -167,11 +174,13 @@ bool GDMonoMethod::has_attribute(GDMonoClass *p_attr_class) {
MonoObject *GDMonoMethod::get_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, nullptr);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return nullptr;
+ }
return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}
@@ -245,14 +254,14 @@ void GDMonoMethod::get_parameter_types(Vector<ManagedType> &types) const {
}
const MethodInfo &GDMonoMethod::get_method_info() {
-
if (!method_info_fetched) {
method_info.name = name;
bool nil_is_variant = false;
method_info.return_val = PropertyInfo(GDMonoMarshal::managed_to_variant_type(return_type, &nil_is_variant), "");
- if (method_info.return_val.type == Variant::NIL && nil_is_variant)
+ if (method_info.return_val.type == Variant::NIL && nil_is_variant) {
method_info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
Vector<StringName> names;
get_parameter_names(names);
@@ -260,8 +269,9 @@ const MethodInfo &GDMonoMethod::get_method_info() {
for (int i = 0; i < params_count; ++i) {
nil_is_variant = false;
PropertyInfo arg_info = PropertyInfo(GDMonoMarshal::managed_to_variant_type(param_types[i], &nil_is_variant), names[i]);
- if (arg_info.type == Variant::NIL && nil_is_variant)
+ if (arg_info.type == Variant::NIL && nil_is_variant) {
arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
+ }
method_info.arguments.push_back(arg_info);
}
@@ -274,16 +284,8 @@ const MethodInfo &GDMonoMethod::get_method_info() {
return method_info;
}
-GDMonoMethod::GDMonoMethod(StringName p_name, MonoMethod *p_method) {
- name = p_name;
-
- mono_method = p_method;
-
- method_info_fetched = false;
-
- attrs_fetched = false;
- attributes = nullptr;
-
+GDMonoMethod::GDMonoMethod(StringName p_name, MonoMethod *p_method) :
+ name(p_name), mono_method(p_method) {
_update_signature();
}
diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h
index 54b2eba3e8..c08ffe904b 100644
--- a/modules/mono/mono_gd/gd_mono_method.h
+++ b/modules/mono/mono_gd/gd_mono_method.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,18 +36,18 @@
#include "i_mono_class_member.h"
class GDMonoMethod : public IMonoClassMember {
-
StringName name;
- int params_count;
+ uint16_t params_count;
+ unsigned int params_buffer_size = 0;
ManagedType return_type;
Vector<ManagedType> param_types;
- bool method_info_fetched;
+ bool method_info_fetched = false;
MethodInfo method_info;
- bool attrs_fetched;
- MonoCustomAttrInfo *attributes;
+ bool attrs_fetched = false;
+ MonoCustomAttrInfo *attributes = nullptr;
void _update_signature();
void _update_signature(MonoMethodSignature *p_method_sig);
@@ -73,7 +73,7 @@ public:
_FORCE_INLINE_ MonoMethod *get_mono_ptr() const { return mono_method; }
- _FORCE_INLINE_ int get_parameters_count() const { return params_count; }
+ _FORCE_INLINE_ uint16_t get_parameters_count() const { return params_count; }
_FORCE_INLINE_ ManagedType get_return_type() const { return return_type; }
MonoObject *invoke(MonoObject *p_object, const Variant **p_params, MonoException **r_exc = nullptr) const;
diff --git a/modules/mono/mono_gd/gd_mono_method_thunk.h b/modules/mono/mono_gd/gd_mono_method_thunk.h
index 0e05e974e9..091d26df1d 100644
--- a/modules/mono/mono_gd/gd_mono_method_thunk.h
+++ b/modules/mono/mono_gd/gd_mono_method_thunk.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -47,10 +47,9 @@
template <class... ParamTypes>
struct GDMonoMethodThunk {
-
typedef void(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **);
- M mono_method_thunk;
+ M mono_method_thunk = nullptr;
public:
_FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) {
@@ -81,9 +80,7 @@ public:
mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr());
}
- GDMonoMethodThunk() :
- mono_method_thunk(nullptr) {
- }
+ GDMonoMethodThunk() {}
explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) {
set_from_method(p_mono_method);
@@ -92,10 +89,9 @@ public:
template <class R, class... ParamTypes>
struct GDMonoMethodThunkR {
-
typedef R(GD_MONO_STDCALL *M)(ParamTypes... p_args, MonoException **);
- M mono_method_thunk;
+ M mono_method_thunk = nullptr;
public:
_FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) {
@@ -127,9 +123,7 @@ public:
mono_method_thunk = (M)mono_method_get_unmanaged_thunk(p_mono_method->get_mono_ptr());
}
- GDMonoMethodThunkR() :
- mono_method_thunk(nullptr) {
- }
+ GDMonoMethodThunkR() {}
explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) {
#ifdef DEBUG_ENABLED
@@ -247,8 +241,7 @@ struct VariadicInvokeMonoMethodR<1, R, P1> {
template <class... ParamTypes>
struct GDMonoMethodThunk {
-
- GDMonoMethod *mono_method;
+ GDMonoMethod *mono_method = nullptr;
public:
_FORCE_INLINE_ void invoke(ParamTypes... p_args, MonoException **r_exc) {
@@ -277,9 +270,7 @@ public:
mono_method = p_mono_method;
}
- GDMonoMethodThunk() :
- mono_method(nullptr) {
- }
+ GDMonoMethodThunk() {}
explicit GDMonoMethodThunk(GDMonoMethod *p_mono_method) {
set_from_method(p_mono_method);
@@ -288,8 +279,7 @@ public:
template <class R, class... ParamTypes>
struct GDMonoMethodThunkR {
-
- GDMonoMethod *mono_method;
+ GDMonoMethod *mono_method = nullptr;
public:
_FORCE_INLINE_ R invoke(ParamTypes... p_args, MonoException **r_exc) {
@@ -318,9 +308,7 @@ public:
mono_method = p_mono_method;
}
- GDMonoMethodThunkR() :
- mono_method(nullptr) {
- }
+ GDMonoMethodThunkR() {}
explicit GDMonoMethodThunkR(GDMonoMethod *p_mono_method) {
set_from_method(p_mono_method);
diff --git a/modules/mono/mono_gd/gd_mono_property.cpp b/modules/mono/mono_gd/gd_mono_property.cpp
index c3e7598f2d..dc3d225082 100644
--- a/modules/mono/mono_gd/gd_mono_property.cpp
+++ b/modules/mono/mono_gd/gd_mono_property.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -77,15 +77,17 @@ GDMonoProperty::~GDMonoProperty() {
bool GDMonoProperty::is_static() {
MonoMethod *prop_method = mono_property_get_get_method(mono_property);
- if (prop_method == nullptr)
+ if (prop_method == nullptr) {
prop_method = mono_property_get_set_method(mono_property);
+ }
return mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_STATIC;
}
IMonoClassMember::Visibility GDMonoProperty::get_visibility() {
MonoMethod *prop_method = mono_property_get_get_method(mono_property);
- if (prop_method == nullptr)
+ if (prop_method == nullptr) {
prop_method = mono_property_get_set_method(mono_property);
+ }
switch (mono_method_get_flags(prop_method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK) {
case MONO_METHOD_ATTR_PRIVATE:
@@ -106,11 +108,13 @@ IMonoClassMember::Visibility GDMonoProperty::get_visibility() {
bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, false);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return false;
+ }
return mono_custom_attrs_has_attr(attributes, p_attr_class->get_mono_ptr());
}
@@ -118,11 +122,13 @@ bool GDMonoProperty::has_attribute(GDMonoClass *p_attr_class) {
MonoObject *GDMonoProperty::get_attribute(GDMonoClass *p_attr_class) {
ERR_FAIL_NULL_V(p_attr_class, nullptr);
- if (!attrs_fetched)
+ if (!attrs_fetched) {
fetch_attributes();
+ }
- if (!attributes)
+ if (!attributes) {
return nullptr;
+ }
return mono_custom_attrs_get_attr(attributes, p_attr_class->get_mono_ptr());
}
@@ -143,10 +149,9 @@ 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_setref(params, 0, p_value);
+ void *params[1] = { p_value };
MonoException *exc = nullptr;
- GDMonoUtils::runtime_invoke_array(prop_method, p_object, params, &exc);
+ GDMonoUtils::runtime_invoke(prop_method, p_object, params, &exc);
if (exc) {
if (r_exc) {
*r_exc = exc;
diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h
index 4653758a86..af7a2c02e5 100644
--- a/modules/mono/mono_gd/gd_mono_property.h
+++ b/modules/mono/mono_gd/gd_mono_property.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,6 @@
#include "i_mono_class_member.h"
class GDMonoProperty : public IMonoClassMember {
-
GDMonoClass *owner;
MonoProperty *mono_property;
diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp
index f9d492dabb..6e0a263c7f 100644
--- a/modules/mono/mono_gd/gd_mono_utils.cpp
+++ b/modules/mono/mono_gd/gd_mono_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,11 +35,10 @@
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
+#include "core/object/reference.h"
#include "core/os/dir_access.h"
#include "core/os/mutex.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
-#include "core/reference.h"
#ifdef TOOLS_ENABLED
#include "editor/debugger/editor_debugger_node.h"
@@ -51,14 +50,13 @@
#include "gd_mono_cache.h"
#include "gd_mono_class.h"
#include "gd_mono_marshal.h"
-#include "gd_mono_method_thunk.h"
namespace GDMonoUtils {
MonoObject *unmanaged_get_managed(Object *unmanaged) {
-
- if (!unmanaged)
+ if (!unmanaged) {
return nullptr;
+ }
if (unmanaged->get_script_instance()) {
CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(unmanaged->get_script_instance());
@@ -91,8 +89,9 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) {
MonoObject *target = gchandle.get_target();
- if (target)
+ if (target) {
return target;
+ }
CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
@@ -197,8 +196,9 @@ GDMonoClass *get_object_class(MonoObject *p_object) {
GDMonoClass *type_get_proxy_class(const StringName &p_type) {
String class_name = p_type;
- if (class_name[0] == '_')
+ if (class_name[0] == '_') {
class_name = class_name.substr(1, class_name.length());
+ }
GDMonoClass *klass = GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, class_name);
@@ -221,11 +221,14 @@ GDMonoClass *get_class_native_base(GDMonoClass *p_class) {
do {
const GDMonoAssembly *assembly = klass->get_assembly();
- if (assembly == GDMono::get_singleton()->get_core_api_assembly())
+
+ if (assembly == GDMono::get_singleton()->get_core_api_assembly()) {
return klass;
+ }
#ifdef TOOLS_ENABLED
- if (assembly == GDMono::get_singleton()->get_editor_api_assembly())
+ if (assembly == GDMono::get_singleton()->get_editor_api_assembly()) {
return klass;
+ }
#endif
} while ((klass = klass->get_parent_class()) != nullptr);
@@ -386,14 +389,6 @@ String get_exception_name_and_message(MonoException *p_exc) {
return res;
}
-void set_exception_message(MonoException *p_exc, String message) {
- MonoClass *klass = mono_object_get_class((MonoObject *)p_exc);
- MonoProperty *prop = mono_class_get_property_from_name(klass, "Message");
- MonoString *msg = GDMonoMarshal::mono_string_from_godot(message);
- void *params[1] = { msg };
- property_set_value(prop, (MonoObject *)p_exc, params, nullptr);
-}
-
void debug_print_unhandled_exception(MonoException *p_exc) {
print_unhandled_exception(p_exc);
debug_send_unhandled_exception_error(p_exc);
@@ -411,8 +406,9 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) {
}
static thread_local bool _recursion_flag_ = false;
- if (_recursion_flag_)
+ if (_recursion_flag_) {
return;
+ }
_recursion_flag_ = true;
SCOPE_EXIT { _recursion_flag_ = false; };
@@ -442,8 +438,9 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) {
Vector<ScriptLanguage::StackInfo> _si;
if (stack_trace != nullptr) {
_si = CSharpLanguage::get_singleton()->stack_trace_get_info(stack_trace);
- for (int i = _si.size() - 1; i >= 0; i--)
+ for (int i = _si.size() - 1; i >= 0; i--) {
si.insert(0, _si[i]);
+ }
}
exc_msg += (exc_msg.length() > 0 ? " ---> " : "") + GDMonoUtils::get_exception_name_and_message(p_exc);
@@ -453,8 +450,9 @@ void debug_send_unhandled_exception_error(MonoException *p_exc) {
CRASH_COND(inner_exc_prop == nullptr);
MonoObject *inner_exc = inner_exc_prop->get_value((MonoObject *)p_exc);
- if (inner_exc != nullptr)
+ if (inner_exc != nullptr) {
si.insert(0, separator);
+ }
p_exc = (MonoException *)inner_exc;
}
@@ -482,6 +480,7 @@ void set_pending_exception(MonoException *p_exc) {
#else
if (get_runtime_invoke_count() == 0) {
debug_unhandled_exception(p_exc);
+ return;
}
if (!mono_runtime_set_pending_exception(p_exc, false)) {
@@ -500,13 +499,6 @@ MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, M
return ret;
}
-MonoObject *runtime_invoke_array(MonoMethod *p_method, void *p_obj, MonoArray *p_params, MonoException **r_exc) {
- GD_MONO_BEGIN_RUNTIME_INVOKE;
- MonoObject *ret = mono_runtime_invoke_array(p_method, p_obj, p_params, (MonoObject **)r_exc);
- GD_MONO_END_RUNTIME_INVOKE;
- return ret;
-}
-
MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc) {
GD_MONO_BEGIN_RUNTIME_INVOKE;
MonoString *ret = mono_object_to_string(p_obj, (MonoObject **)r_exc);
@@ -564,9 +556,10 @@ namespace Marshal {
#ifdef MONO_GLUE_ENABLED
#ifdef TOOLS_ENABLED
-#define NO_GLUE_RET(m_ret) \
- { \
- if (!GDMonoCache::cached_data.godot_api_cache_updated) return m_ret; \
+#define NO_GLUE_RET(m_ret) \
+ { \
+ if (!GDMonoCache::cached_data.godot_api_cache_updated) \
+ return m_ret; \
}
#else
#define NO_GLUE_RET(m_ret) \
@@ -660,11 +653,9 @@ GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, Mon
UNHANDLED_EXCEPTION(exc);
return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype)));
}
-
} // namespace Marshal
-ScopeThreadAttach::ScopeThreadAttach() :
- mono_thread(nullptr) {
+ScopeThreadAttach::ScopeThreadAttach() {
if (likely(GDMono::get_singleton()->is_runtime_initialized()) && unlikely(!mono_domain_get())) {
mono_thread = GDMonoUtils::attach_current_thread();
}
@@ -681,5 +672,4 @@ StringName get_native_godot_class_name(GDMonoClass *p_class) {
StringName *ptr = GDMonoMarshal::unbox<StringName *>(CACHED_FIELD(StringName, ptr)->get_value(native_name_obj));
return ptr ? *ptr : StringName();
}
-
} // namespace GDMonoUtils
diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h
index e3011ade5d..9e024418e1 100644
--- a/modules/mono/mono_gd/gd_mono_utils.h
+++ b/modules/mono/mono_gd/gd_mono_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,15 +36,19 @@
#include "../mono_gc_handle.h"
#include "../utils/macros.h"
#include "gd_mono_header.h"
+#ifdef JAVASCRIPT_ENABLED
+#include "gd_mono_wasm_m2n.h"
+#endif
-#include "core/object.h"
-#include "core/reference.h"
+#include "core/object/class_db.h"
+#include "core/object/reference.h"
#define UNHANDLED_EXCEPTION(m_exc) \
if (unlikely(m_exc != nullptr)) { \
GDMonoUtils::debug_unhandled_exception(m_exc); \
GD_UNREACHABLE(); \
- }
+ } else \
+ ((void)0)
namespace GDMonoUtils {
@@ -63,7 +67,6 @@ void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoRefl
GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype);
GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype);
-
} // namespace Marshal
_FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) {
@@ -84,10 +87,6 @@ void detach_current_thread(MonoThread *p_mono_thread);
MonoThread *get_current_thread();
bool is_thread_attached();
-_FORCE_INLINE_ bool is_main_thread() {
- return mono_domain_get() != nullptr && mono_thread_get_main() == mono_thread_current();
-}
-
uint32_t new_strong_gchandle(MonoObject *p_object);
uint32_t new_strong_gchandle_pinned(MonoObject *p_object);
uint32_t new_weak_gchandle(MonoObject *p_object);
@@ -115,7 +114,6 @@ String get_type_desc(MonoType *p_type);
String get_type_desc(MonoReflectionType *p_reftype);
String get_exception_name_and_message(MonoException *p_exc);
-void set_exception_message(MonoException *p_exc, String message);
void debug_print_unhandled_exception(MonoException *p_exc);
void debug_send_unhandled_exception_error(MonoException *p_exc);
@@ -134,12 +132,12 @@ extern thread_local int current_invoke_count;
_FORCE_INLINE_ int get_runtime_invoke_count() {
return current_invoke_count;
}
+
_FORCE_INLINE_ int &get_runtime_invoke_count_ref() {
return current_invoke_count;
}
MonoObject *runtime_invoke(MonoMethod *p_method, void *p_obj, void **p_params, MonoException **r_exc);
-MonoObject *runtime_invoke_array(MonoMethod *p_method, void *p_obj, MonoArray *p_params, MonoException **r_exc);
MonoString *object_to_string(MonoObject *p_obj, MonoException **r_exc);
@@ -155,31 +153,50 @@ struct ScopeThreadAttach {
~ScopeThreadAttach();
private:
- MonoThread *mono_thread;
+ MonoThread *mono_thread = nullptr;
};
StringName get_native_godot_class_name(GDMonoClass *p_class);
+template <typename... P>
+void add_internal_call(const char *p_name, void (*p_func)(P...)) {
+#ifdef JAVASCRIPT_ENABLED
+ GDMonoWasmM2n::ICallTrampolines<P...>::add();
+#endif
+ mono_add_internal_call(p_name, (void *)p_func);
+}
+
+template <typename R, typename... P>
+void add_internal_call(const char *p_name, R (*p_func)(P...)) {
+#ifdef JAVASCRIPT_ENABLED
+ GDMonoWasmM2n::ICallTrampolinesR<R, P...>::add();
+#endif
+ mono_add_internal_call(p_name, (void *)p_func);
+}
} // namespace GDMonoUtils
#define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoUtils::get_native_godot_class_name(m_class))
#define GD_MONO_BEGIN_RUNTIME_INVOKE \
int &_runtime_invoke_count_ref = GDMonoUtils::get_runtime_invoke_count_ref(); \
- _runtime_invoke_count_ref += 1;
+ _runtime_invoke_count_ref += 1; \
+ ((void)0)
-#define GD_MONO_END_RUNTIME_INVOKE \
- _runtime_invoke_count_ref -= 1;
+#define GD_MONO_END_RUNTIME_INVOKE \
+ _runtime_invoke_count_ref -= 1; \
+ ((void)0)
#define GD_MONO_SCOPE_THREAD_ATTACH \
GDMonoUtils::ScopeThreadAttach __gdmono__scope__thread__attach__; \
- (void)__gdmono__scope__thread__attach__;
+ (void)__gdmono__scope__thread__attach__; \
+ ((void)0)
#ifdef DEBUG_ENABLED
-#define GD_MONO_ASSERT_THREAD_ATTACHED \
- { CRASH_COND(!GDMonoUtils::is_thread_attached()); }
+#define GD_MONO_ASSERT_THREAD_ATTACHED \
+ CRASH_COND(!GDMonoUtils::is_thread_attached()); \
+ ((void)0)
#else
-#define GD_MONO_ASSERT_THREAD_ATTACHED
+#define GD_MONO_ASSERT_THREAD_ATTACHED ((void)0)
#endif
#endif // GD_MONOUTILS_H
diff --git a/modules/mono/glue/gd_glue.h b/modules/mono/mono_gd/gd_mono_wasm_m2n.cpp
index 3ad6058205..a477c55456 100644
--- a/modules/mono/glue/gd_glue.h
+++ b/modules/mono/mono_gd/gd_mono_wasm_m2n.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* gd_glue.h */
+/* gd_mono_wasm_m2n.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,59 +28,52 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef GD_GLUE_H
-#define GD_GLUE_H
+#include "gd_mono_wasm_m2n.h"
-#ifdef MONO_GLUE_ENABLED
+#ifdef JAVASCRIPT_ENABLED
-#include "../mono_gd/gd_mono_marshal.h"
+#include "core/templates/oa_hash_map.h"
-MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects);
+typedef mono_bool (*GodotMonoM2nIcallTrampolineDispatch)(const char *cookie, void *target_func, Mono_InterpMethodArguments *margs);
-MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type);
+// This extern function is implemented in our patched version of Mono
+MONO_API void godot_mono_register_m2n_icall_trampoline_dispatch_hook(GodotMonoM2nIcallTrampolineDispatch hook);
-int godot_icall_GD_hash(MonoObject *p_var);
+namespace GDMonoWasmM2n {
-MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id);
+struct HashMapCookieComparator {
+ static bool compare(const char *p_lhs, const char *p_rhs) {
+ return strcmp(p_lhs, p_rhs) == 0;
+ }
+};
-void godot_icall_GD_print(MonoArray *p_what);
+// The default hasher supports 'const char *' C Strings, but we need a custom comparator
+OAHashMap<const char *, TrampolineFunc, HashMapHasherDefault, HashMapCookieComparator> trampolines;
-void godot_icall_GD_printerr(MonoArray *p_what);
+void set_trampoline(const char *cookies, GDMonoWasmM2n::TrampolineFunc trampoline_func) {
+ trampolines.set(cookies, trampoline_func);
+}
-void godot_icall_GD_printraw(MonoArray *p_what);
+mono_bool trampoline_dispatch_hook(const char *cookie, void *target_func, Mono_InterpMethodArguments *margs) {
+ TrampolineFunc *trampoline_func = trampolines.lookup_ptr(cookie);
-void godot_icall_GD_prints(MonoArray *p_what);
+ if (!trampoline_func) {
+ return false;
+ }
-void godot_icall_GD_printt(MonoArray *p_what);
+ (*trampoline_func)(target_func, margs);
+ return true;
+}
-float godot_icall_GD_randf();
+bool initialized = false;
-uint32_t godot_icall_GD_randi();
+void lazy_initialize() {
+ // Doesn't need to be thread safe
+ if (!initialized) {
+ initialized = true;
+ godot_mono_register_m2n_icall_trampoline_dispatch_hook(&trampoline_dispatch_hook);
+ }
+}
+} // namespace GDMonoWasmM2n
-void godot_icall_GD_randomize();
-
-double godot_icall_GD_rand_range(double from, double to);
-
-uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed);
-
-void godot_icall_GD_seed(uint64_t p_seed);
-
-MonoString *godot_icall_GD_str(MonoArray *p_what);
-
-MonoObject *godot_icall_GD_str2var(MonoString *p_str);
-
-MonoBoolean godot_icall_GD_type_exists(StringName *p_type);
-
-MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects);
-
-MonoString *godot_icall_GD_var2str(MonoObject *p_var);
-
-MonoObject *godot_icall_DefaultGodotTaskScheduler();
-
-// Register internal calls
-
-void godot_register_gd_icalls();
-
-#endif // MONO_GLUE_ENABLED
-
-#endif // GD_GLUE_H
+#endif
diff --git a/modules/mono/mono_gd/gd_mono_wasm_m2n.h b/modules/mono/mono_gd/gd_mono_wasm_m2n.h
new file mode 100644
index 0000000000..159a2ed7b6
--- /dev/null
+++ b/modules/mono/mono_gd/gd_mono_wasm_m2n.h
@@ -0,0 +1,263 @@
+/*************************************************************************/
+/* gd_mono_wasm_m2n.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GD_MONO_WASM_M2N_H
+#define GD_MONO_WASM_M2N_H
+
+#ifdef JAVASCRIPT_ENABLED
+
+#include "core/string/ustring.h"
+#include "core/typedefs.h"
+
+#include <mono/metadata/loader.h>
+#include <mono/utils/mono-publib.h>
+#include <stdexcept>
+#include <type_traits>
+
+extern "C" {
+
+struct Mono_InterpMethodArguments {
+ size_t ilen;
+ void **iargs;
+ size_t flen;
+ double *fargs;
+ void **retval;
+ size_t is_float_ret;
+ //#ifdef TARGET_WASM
+ void *sig;
+ //#endif
+};
+} // extern "C"
+
+namespace GDMonoWasmM2n {
+
+template <typename T, size_t Size>
+struct array {
+ T elems[Size];
+};
+
+template <typename T>
+constexpr char get_m2n_cookie_impl() {
+#define M2N_REG_COOKIE(m_type, m_cookie) \
+ if constexpr (std::is_same_v<m_type, T>) { \
+ return m_cookie; \
+ }
+
+ M2N_REG_COOKIE(MonoBoolean, 'I');
+ M2N_REG_COOKIE(int8_t, 'I');
+ M2N_REG_COOKIE(uint8_t, 'I');
+ M2N_REG_COOKIE(int16_t, 'I');
+ M2N_REG_COOKIE(uint16_t, 'I');
+ M2N_REG_COOKIE(int32_t, 'I');
+ M2N_REG_COOKIE(uint32_t, 'I');
+ M2N_REG_COOKIE(int64_t, 'L');
+ M2N_REG_COOKIE(uint64_t, 'L');
+ M2N_REG_COOKIE(float, 'F');
+ M2N_REG_COOKIE(double, 'D');
+
+ if constexpr (std::is_pointer_v<T>) {
+ if constexpr (sizeof(void *) == 4) {
+ return 'I';
+ } else {
+ return 'L';
+ }
+ }
+
+ if constexpr (std::is_void_v<T>) {
+ return 'V';
+ }
+
+ return 'X';
+
+#undef M2N_REG_COOKIE
+}
+
+template <typename T>
+constexpr char get_m2n_cookie() {
+ constexpr char cookie = get_m2n_cookie_impl<T>();
+ static_assert(cookie != 'X', "Type not supported in internal call signature.");
+ return cookie;
+}
+
+template <typename... T>
+constexpr array<const char, sizeof...(T) + 2> get_m2n_cookies() {
+ return array<const char, sizeof...(T) + 2>{ 'V', get_m2n_cookie<T>()..., '\0' };
+}
+
+template <typename R, typename... T>
+constexpr array<const char, sizeof...(T) + 2> get_m2n_cookies_r() {
+ return array<const char, sizeof...(T) + 2>{ get_m2n_cookie<R>(), get_m2n_cookie<T>()..., '\0' };
+}
+
+template <typename T>
+constexpr size_t calc_m2n_index(size_t &r_int_idx, size_t &r_float_idx) {
+ constexpr char cookie = get_m2n_cookie<T>();
+
+ static_assert(cookie == 'I' || cookie == 'L' || cookie == 'F' || cookie == 'D');
+
+ if constexpr (cookie == 'I' || cookie == 'L') {
+ size_t ret = r_int_idx;
+ r_int_idx += cookie == 'I' ? 1 : 2;
+ return ret;
+ } else {
+ size_t ret = r_float_idx;
+ r_float_idx += cookie == 'F' ? 1 : 2;
+ return ret;
+ }
+}
+
+template <typename... P>
+constexpr array<size_t, sizeof...(P)> get_indices_for_type() {
+ size_t int_idx = 0;
+ size_t float_idx = 0;
+ return array<size_t, sizeof...(P)>{ calc_m2n_index<P>(int_idx, float_idx)... };
+}
+
+constexpr size_t fidx(size_t p_x) {
+ if constexpr (sizeof(void *) == 4) {
+ return p_x * 2;
+ } else {
+ return p_x;
+ }
+}
+
+template <typename T>
+T m2n_arg_cast(Mono_InterpMethodArguments *p_margs, size_t p_idx) {
+ constexpr char cookie = get_m2n_cookie<T>();
+
+ static_assert(cookie == 'I' || cookie == 'L' || cookie == 'F' || cookie == 'D');
+
+ if constexpr (cookie == 'I') {
+ return (T)(size_t)p_margs->iargs[p_idx];
+ } else if constexpr (cookie == 'L') {
+ static_assert(std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t> ||
+ (sizeof(void *) == 8 && std::is_pointer_v<T>),
+ "Invalid type for cookie 'L'.");
+
+ union {
+ T l;
+ struct {
+ int32_t lo;
+ int32_t hi;
+ } pair;
+ } p;
+
+ p.pair.lo = (int32_t)(size_t)p_margs->iargs[p_idx];
+ p.pair.hi = (int32_t)(size_t)p_margs->iargs[p_idx + 1];
+
+ return p.l;
+ } else if constexpr (cookie == 'F') {
+ return *reinterpret_cast<float *>(&p_margs->fargs[fidx(p_idx)]);
+ } else if constexpr (cookie == 'D') {
+ return (T)(size_t)p_margs->fargs[p_idx];
+ }
+}
+
+template <typename... P, size_t... Is>
+void m2n_trampoline_with_idx_seq(void *p_target_func, Mono_InterpMethodArguments *p_margs, IndexSequence<Is...>) {
+ constexpr array<size_t, sizeof...(P)> indices = get_indices_for_type<P...>();
+ typedef void (*Func)(P...);
+ Func func = (Func)p_target_func;
+ func(m2n_arg_cast<P>(p_margs, indices.elems[Is])...);
+}
+
+template <typename R, typename... P, size_t... Is>
+void m2n_trampoline_with_idx_seq_r(void *p_target_func, Mono_InterpMethodArguments *p_margs, IndexSequence<Is...>) {
+ constexpr array<size_t, sizeof...(P)> indices = get_indices_for_type<P...>();
+ typedef R (*Func)(P...);
+ Func func = (Func)p_target_func;
+ R res = func(m2n_arg_cast<P>(p_margs, indices.elems[Is])...);
+ *reinterpret_cast<R *>(p_margs->retval) = res;
+}
+
+inline void m2n_trampoline_with_idx_seq_0(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
+ typedef void (*Func)();
+ Func func = (Func)p_target_func;
+ func();
+}
+
+template <typename R>
+void m2n_trampoline_with_idx_seq_r0(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
+ typedef R (*Func)();
+ Func func = (Func)p_target_func;
+ R res = func();
+ *reinterpret_cast<R *>(p_margs->retval) = res;
+}
+
+template <typename... P>
+void m2n_trampoline(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
+ if constexpr (sizeof...(P) == 0) {
+ m2n_trampoline_with_idx_seq_0(p_target_func, p_margs);
+ } else {
+ m2n_trampoline_with_idx_seq<P...>(p_target_func, p_margs, BuildIndexSequence<sizeof...(P)>{});
+ }
+}
+
+template <typename R, typename... P>
+void m2n_trampoline_r(void *p_target_func, Mono_InterpMethodArguments *p_margs) {
+ if constexpr (sizeof...(P) == 0) {
+ m2n_trampoline_with_idx_seq_r0<R>(p_target_func, p_margs);
+ } else {
+ m2n_trampoline_with_idx_seq_r<R, P...>(p_target_func, p_margs, BuildIndexSequence<sizeof...(P)>{});
+ }
+}
+
+typedef void (*TrampolineFunc)(void *p_target_func, Mono_InterpMethodArguments *p_margs);
+
+void set_trampoline(const char *cookies, TrampolineFunc trampoline_func);
+
+void lazy_initialize();
+
+template <typename... P>
+struct ICallTrampolines {
+ static constexpr auto cookies = get_m2n_cookies<P...>();
+
+ static void add() {
+ lazy_initialize();
+ set_trampoline(cookies.elems, &m2n_trampoline<P...>);
+ }
+};
+
+template <typename R, typename... P>
+struct ICallTrampolinesR {
+ static constexpr auto cookies = get_m2n_cookies_r<R, P...>();
+
+ static void add() {
+ lazy_initialize();
+ set_trampoline(cookies.elems, &m2n_trampoline_r<R, P...>);
+ }
+};
+
+void initialize();
+} // namespace GDMonoWasmM2n
+
+#endif
+
+#endif // GD_MONO_WASM_M2N_H
diff --git a/modules/mono/mono_gd/i_mono_class_member.h b/modules/mono/mono_gd/i_mono_class_member.h
index 2e8e01c80e..36e14ba27c 100644
--- a/modules/mono/mono_gd/i_mono_class_member.h
+++ b/modules/mono/mono_gd/i_mono_class_member.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mono/mono_gd/managed_type.cpp b/modules/mono/mono_gd/managed_type.cpp
index 3e971efece..0acfafe841 100644
--- a/modules/mono/mono_gd/managed_type.cpp
+++ b/modules/mono/mono_gd/managed_type.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/mono/mono_gd/managed_type.h b/modules/mono/mono_gd/managed_type.h
index 84d1837853..0456a9a864 100644
--- a/modules/mono/mono_gd/managed_type.h
+++ b/modules/mono/mono_gd/managed_type.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,18 +36,15 @@
#include "gd_mono_header.h"
struct ManagedType {
- int type_encoding;
- GDMonoClass *type_class;
+ int type_encoding = 0;
+ GDMonoClass *type_class = nullptr;
static ManagedType from_class(GDMonoClass *p_class);
static ManagedType from_class(MonoClass *p_mono_class);
static ManagedType from_type(MonoType *p_mono_type);
static ManagedType from_reftype(MonoReflectionType *p_mono_reftype);
- ManagedType() :
- type_encoding(0),
- type_class(nullptr) {
- }
+ ManagedType() {}
ManagedType(int p_type_encoding, GDMonoClass *p_type_class) :
type_encoding(p_type_encoding),
diff --git a/modules/mono/mono_gd/support/android_support.cpp b/modules/mono/mono_gd/support/android_support.cpp
index 8bcdeec9dd..59e1385e7e 100755..100644
--- a/modules/mono/mono_gd/support/android_support.cpp
+++ b/modules/mono/mono_gd/support/android_support.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -44,7 +44,7 @@
#endif
#include "core/os/os.h"
-#include "core/ustring.h"
+#include "core/string/ustring.h"
#include "platform/android/java_godot_wrapper.h"
#include "platform/android/os_android.h"
#include "platform/android/thread_jandroid.h"
@@ -134,7 +134,7 @@ String determine_app_native_lib_dir() {
}
String get_app_native_lib_dir() {
- if (app_native_lib_dir_cache.empty())
+ if (app_native_lib_dir_cache.is_empty())
app_native_lib_dir_cache = determine_app_native_lib_dir();
return app_native_lib_dir_cache;
}
@@ -355,8 +355,8 @@ MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) {
}
void register_internal_calls() {
- mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_init_cert_store", (void *)_gd_mono_init_cert_store);
- mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_android_cert_store_lookup", (void *)_gd_mono_android_cert_store_lookup);
+ GDMonoUtils::add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_init_cert_store", _gd_mono_init_cert_store);
+ GDMonoUtils::add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_android_cert_store_lookup", _gd_mono_android_cert_store_lookup);
}
void initialize() {
@@ -387,7 +387,6 @@ void cleanup() {
certStore = nullptr;
}
}
-
} // namespace support
} // namespace android
} // namespace gdmono
diff --git a/modules/mono/mono_gd/support/android_support.h b/modules/mono/mono_gd/support/android_support.h
index dc2e6c95ed..0c5dd2764c 100755
--- a/modules/mono/mono_gd/support/android_support.h
+++ b/modules/mono/mono_gd/support/android_support.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,7 @@
#if defined(ANDROID_ENABLED)
-#include "core/ustring.h"
+#include "core/string/ustring.h"
namespace gdmono {
namespace android {
@@ -45,7 +45,6 @@ void initialize();
void cleanup();
void register_internal_calls();
-
} // namespace support
} // namespace android
} // namespace gdmono
diff --git a/modules/mono/mono_gd/support/ios_support.h b/modules/mono/mono_gd/support/ios_support.h
index e28af120e3..28a8806d0e 100755
--- a/modules/mono/mono_gd/support/ios_support.h
+++ b/modules/mono/mono_gd/support/ios_support.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,7 @@
#if defined(IPHONE_ENABLED)
-#include "core/ustring.h"
+#include "core/string/ustring.h"
namespace gdmono {
namespace ios {
@@ -41,7 +41,6 @@ namespace support {
void initialize();
void cleanup();
-
} // namespace support
} // namespace ios
} // namespace gdmono
diff --git a/modules/mono/mono_gd/support/ios_support.mm b/modules/mono/mono_gd/support/ios_support.mm
index e3d1a647fd..cdee04edcf 100755..100644
--- a/modules/mono/mono_gd/support/ios_support.mm
+++ b/modules/mono/mono_gd/support/ios_support.mm
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -72,7 +72,6 @@ void initialize() {
void cleanup() {
}
-
} // namespace support
} // namespace ios
} // namespace gdmono
@@ -131,8 +130,7 @@ GD_PINVOKE_EXPORT void *xamarin_timezone_get_data(const char *p_name, uint32_t *
NSTimeZone *tz = nil;
if (p_name) {
NSString *n = [[NSString alloc] initWithUTF8String:p_name];
- tz = [[[NSTimeZone alloc] initWithName:n] autorelease];
- [n release];
+ tz = [[NSTimeZone alloc] initWithName:n];
} else {
tz = [NSTimeZone localTimeZone];
}
diff --git a/modules/mono/register_types.cpp b/modules/mono/register_types.cpp
index 94431e7c30..80eb47bfd4 100644
--- a/modules/mono/register_types.cpp
+++ b/modules/mono/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "register_types.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "csharp_script.h"
@@ -62,8 +62,9 @@ void register_mono_types() {
void unregister_mono_types() {
ScriptServer::unregister_language(script_language_cs);
- if (script_language_cs)
+ if (script_language_cs) {
memdelete(script_language_cs);
+ }
ResourceLoader::remove_resource_format_loader(resource_loader_cs);
resource_loader_cs.unref();
@@ -71,6 +72,7 @@ void unregister_mono_types() {
ResourceSaver::remove_resource_format_saver(resource_saver_cs);
resource_saver_cs.unref();
- if (_godotsharp)
+ if (_godotsharp) {
memdelete(_godotsharp);
+ }
}
diff --git a/modules/mono/register_types.h b/modules/mono/register_types.h
index 7fd0d24eb0..1a2ff004b5 100644
--- a/modules/mono/register_types.h
+++ b/modules/mono/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,5 +28,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
+#ifndef MONO_REGISTER_TYPES_H
+#define MONO_REGISTER_TYPES_H
+
void register_mono_types();
void unregister_mono_types();
+
+#endif // MONO_REGISTER_TYPES_H
diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp
index e77a2e98f2..3aaf726fc8 100644
--- a/modules/mono/signal_awaiter_utils.cpp
+++ b/modules/mono/signal_awaiter_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -48,21 +48,16 @@ Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signa
}
bool SignalAwaiterCallable::compare_equal(const CallableCustom *p_a, const CallableCustom *p_b) {
+ // Only called if both instances are of type SignalAwaiterCallable. Static cast is safe.
const SignalAwaiterCallable *a = static_cast<const SignalAwaiterCallable *>(p_a);
const SignalAwaiterCallable *b = static_cast<const SignalAwaiterCallable *>(p_b);
-
- if (a->target_id != b->target_id)
- return false;
-
- if (a->signal != b->signal)
- return false;
-
- return true;
+ return a->awaiter_handle.handle == b->awaiter_handle.handle;
}
bool SignalAwaiterCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
- if (compare_equal(p_a, p_b))
+ if (compare_equal(p_a, p_b)) {
return false;
+ }
return p_a < p_b;
}
@@ -77,7 +72,6 @@ String SignalAwaiterCallable::get_as_text() const {
String class_name = base->get_class();
Ref<Script> script = base->get_script();
if (script.is_valid() && script->get_path().is_resource_file()) {
-
class_name += "(" + script->get_path().get_file() + ")";
}
return class_name + "::SignalAwaiterMiddleman::" + String(signal);
@@ -107,11 +101,15 @@ void SignalAwaiterCallable::call(const Variant **p_arguments, int p_argcount, Va
"Resumed after await, but class instance is gone.");
#endif
- MonoArray *signal_args = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), p_argcount);
+ MonoArray *signal_args = nullptr;
+
+ if (p_argcount > 0) {
+ signal_args = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), p_argcount);
- for (int i = 0; i < p_argcount; i++) {
- MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_arguments[i]);
- mono_array_setref(signal_args, i, boxed);
+ for (int i = 0; i < p_argcount; i++) {
+ MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_arguments[i]);
+ mono_array_setref(signal_args, i, boxed);
+ }
}
MonoObject *awaiter = awaiter_handle.get_target();
@@ -146,18 +144,21 @@ bool EventSignalCallable::compare_equal(const CallableCustom *p_a, const Callabl
const EventSignalCallable *a = static_cast<const EventSignalCallable *>(p_a);
const EventSignalCallable *b = static_cast<const EventSignalCallable *>(p_b);
- if (a->owner != b->owner)
+ if (a->owner != b->owner) {
return false;
+ }
- if (a->event_signal != b->event_signal)
+ if (a->event_signal != b->event_signal) {
return false;
+ }
return true;
}
bool EventSignalCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
- if (compare_equal(p_a, p_b))
+ if (compare_equal(p_a, p_b)) {
return false;
+ }
return p_a < p_b;
}
diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h
index c550315a23..4c77f8cfed 100644
--- a/modules/mono/signal_awaiter_utils.h
+++ b/modules/mono/signal_awaiter_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef SIGNAL_AWAITER_UTILS_H
#define SIGNAL_AWAITER_UTILS_H
-#include "core/reference.h"
+#include "core/object/reference.h"
#include "csharp_script.h"
#include "mono_gc_handle.h"
diff --git a/modules/mono/utils/macros.h b/modules/mono/utils/macros.h
index 8650d6cc09..4a220d89c8 100644
--- a/modules/mono/utils/macros.h
+++ b/modules/mono/utils/macros.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -46,7 +46,7 @@
#define GD_UNREACHABLE() \
CRASH_NOW(); \
do { \
- } while (true);
+ } while (true)
#endif
namespace gdmono {
@@ -64,10 +64,9 @@ public:
template <typename F>
ScopeExit<F> operator+(F p_exit_func) { return ScopeExit<F>(p_exit_func); }
};
-
} // namespace gdmono
#define SCOPE_EXIT \
- auto GD_UNIQUE_NAME(gd_scope_exit) = gdmono::ScopeExitAux() + [=]()
+ auto GD_UNIQUE_NAME(gd_scope_exit) = gdmono::ScopeExitAux() + [=]() -> void
#endif // UTIL_MACROS_H
diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp
index 8f0ad8ba5e..bb1265e959 100644
--- a/modules/mono/utils/mono_reg_utils.cpp
+++ b/modules/mono/utils/mono_reg_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -58,7 +58,6 @@ REGSAM _get_bitness_sam() {
}
LONG _RegOpenKey(HKEY hKey, LPCWSTR lpSubKey, PHKEY phkResult) {
-
LONG res = RegOpenKeyExW(hKey, lpSubKey, 0, KEY_READ, phkResult);
if (res != ERROR_SUCCESS)
@@ -68,18 +67,16 @@ LONG _RegOpenKey(HKEY hKey, LPCWSTR lpSubKey, PHKEY phkResult) {
}
LONG _RegKeyQueryString(HKEY hKey, const String &p_value_name, String &r_value) {
-
Vector<WCHAR> buffer;
buffer.resize(512);
DWORD dwBufferSize = buffer.size();
- LONG res = RegQueryValueExW(hKey, p_value_name.c_str(), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
+ LONG res = RegQueryValueExW(hKey, (LPCWSTR)(p_value_name.utf16().get_data()), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
if (res == ERROR_MORE_DATA) {
// dwBufferSize now contains the actual size
- Vector<WCHAR> buffer;
buffer.resize(dwBufferSize);
- res = RegQueryValueExW(hKey, p_value_name.c_str(), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
+ res = RegQueryValueExW(hKey, (LPCWSTR)(p_value_name.utf16().get_data()), 0, nullptr, (LPBYTE)buffer.ptr(), &dwBufferSize);
}
if (res == ERROR_SUCCESS) {
@@ -92,9 +89,8 @@ LONG _RegKeyQueryString(HKEY hKey, const String &p_value_name, String &r_value)
}
LONG _find_mono_in_reg(const String &p_subkey, MonoRegInfo &r_info, bool p_old_reg = false) {
-
HKEY hKey;
- LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, p_subkey.c_str(), &hKey);
+ LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey);
if (res != ERROR_SUCCESS)
goto cleanup;
@@ -128,11 +124,10 @@ cleanup:
}
LONG _find_mono_in_reg_old(const String &p_subkey, MonoRegInfo &r_info) {
-
String default_clr;
HKEY hKey;
- LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, p_subkey.c_str(), &hKey);
+ LONG res = _RegOpenKey(HKEY_LOCAL_MACHINE, (LPCWSTR)(p_subkey.utf16().get_data()), &hKey);
if (res != ERROR_SUCCESS)
goto cleanup;
@@ -150,7 +145,6 @@ cleanup:
}
MonoRegInfo find_mono() {
-
MonoRegInfo info;
if (_find_mono_in_reg("Software\\Mono", info) == ERROR_SUCCESS)
@@ -163,7 +157,6 @@ MonoRegInfo find_mono() {
}
String find_msbuild_tools_path() {
-
String msbuild_tools_path;
// Try to find 15.0 with vswhere
@@ -180,7 +173,7 @@ String find_msbuild_tools_path() {
String output;
int exit_code;
- OS::get_singleton()->execute(vswhere_path, vswhere_args, true, nullptr, &output, &exit_code);
+ OS::get_singleton()->execute(vswhere_path, vswhere_args, &output, &exit_code);
if (exit_code == 0) {
Vector<String> lines = output.split("\n");
@@ -195,7 +188,7 @@ String find_msbuild_tools_path() {
if (key == "installationPath") {
String val = line.substr(sep_idx + 1, line.length()).strip_edges();
- ERR_BREAK(val.empty());
+ ERR_BREAK(val.is_empty());
if (!val.ends_with("\\")) {
val += "\\";
diff --git a/modules/mono/utils/mono_reg_utils.h b/modules/mono/utils/mono_reg_utils.h
index f844a7233a..0e617761ea 100644
--- a/modules/mono/utils/mono_reg_utils.h
+++ b/modules/mono/utils/mono_reg_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,10 +33,9 @@
#ifdef WINDOWS_ENABLED
-#include "core/ustring.h"
+#include "core/string/ustring.h"
struct MonoRegInfo {
-
String version;
String install_root_dir;
String assembly_dir;
diff --git a/modules/mono/utils/osx_utils.cpp b/modules/mono/utils/osx_utils.cpp
index 8fadf3c109..f4216c8129 100644
--- a/modules/mono/utils/osx_utils.cpp
+++ b/modules/mono/utils/osx_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,31 +32,27 @@
#ifdef OSX_ENABLED
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
bool osx_is_app_bundle_installed(const String &p_bundle_id) {
-
- CFURLRef app_url = nullptr;
CFStringRef bundle_id = CFStringCreateWithCString(nullptr, p_bundle_id.utf8(), kCFStringEncodingUTF8);
- OSStatus result = LSFindApplicationForInfo(kLSUnknownCreator, bundle_id, nullptr, nullptr, &app_url);
+ CFArrayRef result = LSCopyApplicationURLsForBundleIdentifier(bundle_id, nullptr);
CFRelease(bundle_id);
- if (app_url)
- CFRelease(app_url);
-
- switch (result) {
- case noErr:
+ if (result) {
+ if (CFArrayGetCount(result) > 0) {
+ CFRelease(result);
return true;
- case kLSApplicationNotFoundErr:
- break;
- default:
- break;
+ } else {
+ CFRelease(result);
+ return false;
+ }
+ } else {
+ return false;
}
-
- return false;
}
#endif
diff --git a/modules/mono/utils/osx_utils.h b/modules/mono/utils/osx_utils.h
index 55002702f8..6704f19077 100644
--- a/modules/mono/utils/osx_utils.h
+++ b/modules/mono/utils/osx_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "core/ustring.h"
+#include "core/string/ustring.h"
#ifndef OSX_UTILS_H
#define OSX_UTILS_H
diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp
index 973375a471..93d44628ac 100644
--- a/modules/mono/utils/path_utils.cpp
+++ b/modules/mono/utils/path_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,10 +30,10 @@
#include "path_utils.h"
+#include "core/config/project_settings.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#ifdef WINDOWS_ENABLED
#include <windows.h>
@@ -50,52 +50,30 @@
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
- Vector<String> env_path = OS::get_singleton()->get_environment("PATH").split(ENV_PATH_SEP, false);
-
- if (env_path.empty())
- return String();
-
- for (int i = 0; i < env_path.size(); i++) {
- String p = path::join(env_path[i], p_name);
-
-#ifdef WINDOWS_ENABLED
- for (int j = 0; j < exts.size(); j++) {
- String p2 = p + exts[j].to_lower(); // lowercase to reduce risk of case mismatch warning
-
- if (FileAccess::exists(p2))
- return p2;
- }
-#else
- if (FileAccess::exists(p))
- return p;
-#endif
- }
-
- return String();
-}
-
String cwd() {
#ifdef WINDOWS_ENABLED
const DWORD expected_size = ::GetCurrentDirectoryW(0, nullptr);
- String buffer;
+ Char16String buffer;
buffer.resize((int)expected_size);
- if (::GetCurrentDirectoryW(expected_size, buffer.ptrw()) == 0)
+ if (::GetCurrentDirectoryW(expected_size, (wchar_t *)buffer.ptrw()) == 0)
return ".";
- return buffer.simplify_path();
+ String result;
+ if (result.parse_utf16(buffer.ptr())) {
+ return ".";
+ }
+ return result.simplify_path();
#else
char buffer[PATH_MAX];
- if (::getcwd(buffer, sizeof(buffer)) == nullptr)
+ if (::getcwd(buffer, sizeof(buffer)) == nullptr) {
return ".";
+ }
String result;
- if (result.parse_utf8(buffer))
+ if (result.parse_utf8(buffer)) {
return ".";
+ }
return result.simplify_path();
#endif
@@ -112,7 +90,7 @@ String abspath(const String &p_path) {
String realpath(const String &p_path) {
#ifdef WINDOWS_ENABLED
// Open file without read/write access
- HANDLE hFile = ::CreateFileW(p_path.c_str(), 0,
+ HANDLE hFile = ::CreateFileW((LPCWSTR)(p_path.utf16().get_data()), 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
@@ -126,34 +104,43 @@ String realpath(const String &p_path) {
return p_path;
}
- String buffer;
+ Char16String buffer;
buffer.resize((int)expected_size);
- ::GetFinalPathNameByHandleW(hFile, buffer.ptrw(), expected_size, FILE_NAME_NORMALIZED);
+ ::GetFinalPathNameByHandleW(hFile, (wchar_t *)buffer.ptrw(), expected_size, FILE_NAME_NORMALIZED);
::CloseHandle(hFile);
- return buffer.simplify_path();
+
+ String result;
+ if (result.parse_utf16(buffer.ptr())) {
+ return p_path;
+ }
+
+ return result.simplify_path();
#elif UNIX_ENABLED
char *resolved_path = ::realpath(p_path.utf8().get_data(), nullptr);
- if (!resolved_path)
+ if (!resolved_path) {
return p_path;
+ }
String result;
bool parse_ok = result.parse_utf8(resolved_path);
::free(resolved_path);
- if (parse_ok)
+ if (parse_ok) {
return p_path;
+ }
return result.simplify_path();
#endif
}
String join(const String &p_a, const String &p_b) {
- if (p_a.empty())
+ if (p_a.is_empty()) {
return p_b;
+ }
- const CharType a_last = p_a[p_a.length() - 1];
+ const char32_t 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;
@@ -178,8 +165,9 @@ String relative_to_impl(const String &p_path, const String &p_relative_to) {
} else {
String base_dir = p_relative_to.get_base_dir();
- if (base_dir.length() <= 2 && (base_dir.empty() || base_dir.ends_with(":")))
+ if (base_dir.length() <= 2 && (base_dir.is_empty() || base_dir.ends_with(":"))) {
return p_path;
+ }
return String("..").plus_file(relative_to_impl(p_path, base_dir));
}
@@ -206,5 +194,4 @@ String relative_to(const String &p_path, const String &p_relative_to) {
return relative_to_impl(path_abs_norm, relative_to_abs_norm);
}
-
} // namespace path
diff --git a/modules/mono/utils/path_utils.h b/modules/mono/utils/path_utils.h
index 9965f58b0a..82b8f95f49 100644
--- a/modules/mono/utils/path_utils.h
+++ b/modules/mono/utils/path_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef PATH_UTILS_H
#define PATH_UTILS_H
-#include "core/string_builder.h"
-#include "core/ustring.h"
+#include "core/string/string_builder.h"
+#include "core/string/ustring.h"
namespace path {
@@ -40,8 +40,6 @@ 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);
-String find_executable(const String &p_name);
-
/// Returns a normalized absolute path to the current working directory
String cwd();
@@ -58,7 +56,6 @@ String abspath(const String &p_path);
String realpath(const String &p_path);
String relative_to(const String &p_path, const String &p_relative_to);
-
} // namespace path
#endif // PATH_UTILS_H
diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp
index 67b264d803..43de77005e 100644
--- a/modules/mono/utils/string_utils.cpp
+++ b/modules/mono/utils/string_utils.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -38,16 +38,18 @@
namespace {
int sfind(const String &p_text, int p_from) {
- if (p_from < 0)
+ if (p_from < 0) {
return -1;
+ }
int src_len = 2;
int len = p_text.length();
- if (len == 0)
+ if (len == 0) {
return -1;
+ }
- const CharType *src = p_text.c_str();
+ const char32_t *src = p_text.get_data();
for (int i = p_from; i <= (len - src_len); i++) {
bool found = true;
@@ -62,7 +64,7 @@ int sfind(const String &p_text, int p_from) {
found = src[read_pos] == '%';
break;
case 1: {
- CharType c = src[read_pos];
+ char32_t c = src[read_pos];
found = src[read_pos] == 's' || (c >= '0' && c <= '4');
break;
}
@@ -75,8 +77,9 @@ int sfind(const String &p_text, int p_from) {
}
}
- if (found)
+ if (found) {
return i;
+ }
}
return -1;
@@ -84,8 +87,9 @@ int sfind(const String &p_text, int p_from) {
} // namespace
String sformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
- if (p_text.length() < 2)
+ if (p_text.length() < 2) {
return p_text;
+ }
Array args;
@@ -116,7 +120,7 @@ String sformat(const String &p_text, const Variant &p1, const Variant &p2, const
int result = 0;
while ((result = sfind(p_text, search_from)) >= 0) {
- CharType c = p_text[result + 1];
+ char32_t c = p_text[result + 1];
int req_index = (c == 's' ? findex++ : c - '0');
@@ -132,7 +136,6 @@ String sformat(const String &p_text, const Variant &p1, const Variant &p2, const
#ifdef TOOLS_ENABLED
bool is_csharp_keyword(const String &p_name) {
-
// Reserved keywords
return p_name == "abstract" || p_name == "as" || p_name == "base" || p_name == "bool" ||
diff --git a/modules/mono/utils/string_utils.h b/modules/mono/utils/string_utils.h
index 0318fec592..3290cb38b9 100644
--- a/modules/mono/utils/string_utils.h
+++ b/modules/mono/utils/string_utils.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef STRING_FORMAT_H
#define STRING_FORMAT_H
-#include "core/ustring.h"
-#include "core/variant.h"
+#include "core/string/ustring.h"
+#include "core/variant/variant.h"
#include <stdarg.h>
diff --git a/modules/ogg/SCsub b/modules/ogg/SCsub
index e768fb4ae8..e415d92498 100644
--- a/modules/ogg/SCsub
+++ b/modules/ogg/SCsub
@@ -9,6 +9,9 @@ Import("env_modules")
env_ogg = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_libogg"]:
thirdparty_dir = "#thirdparty/libogg/"
thirdparty_sources = [
@@ -21,7 +24,16 @@ if env["builtin_libogg"]:
env_thirdparty = env_ogg.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_ogg.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_ogg.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/ogg/register_types.cpp b/modules/ogg/register_types.cpp
index 73c691397c..b23ea65378 100644
--- a/modules/ogg/register_types.cpp
+++ b/modules/ogg/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/ogg/register_types.h b/modules/ogg/register_types.h
index 849d27bb06..49d5ed9c80 100644
--- a/modules/ogg/register_types.h
+++ b/modules/ogg/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/opensimplex/SCsub b/modules/opensimplex/SCsub
index 52d8b145ef..86d77c3dfb 100644
--- a/modules/opensimplex/SCsub
+++ b/modules/opensimplex/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_opensimplex = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
thirdparty_dir = "#thirdparty/misc/"
thirdparty_sources = [
"open-simplex-noise.c",
@@ -16,7 +19,15 @@ env_opensimplex.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_opensimplex.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_opensimplex.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_opensimplex.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml
index c06f3096de..7df261d2ba 100644
--- a/modules/opensimplex/doc_classes/NoiseTexture.xml
+++ b/modules/opensimplex/doc_classes/NoiseTexture.xml
@@ -5,7 +5,7 @@
</brief_description>
<description>
Uses an [OpenSimplexNoise] to fill the texture data. You can specify the texture size but keep in mind that larger textures will take longer to generate and seamless noise only works with square sized textures.
- NoiseTexture can also generate normalmap textures.
+ NoiseTexture can also generate normal map textures.
The class uses [Thread]s to generate the texture data internally, so [method Texture2D.get_data] may return [code]null[/code] if the generation process has not completed yet. In that case, you need to wait for the texture to be generated before accessing the data:
[codeblock]
var texture = preload("res://noise.tres")
@@ -18,7 +18,7 @@
<methods>
</methods>
<members>
- <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap" default="false">
+ <member name="as_normal_map" type="bool" setter="set_as_normal_map" getter="is_normal_map" 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" default="8.0">
diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
index d89828037f..dcda5c2324 100644
--- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
+++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
@@ -24,7 +24,7 @@
<tutorials>
</tutorials>
<methods>
- <method name="get_image">
+ <method name="get_image" qualifiers="const">
<return type="Image">
</return>
<argument index="0" name="width" type="int">
@@ -32,10 +32,10 @@
<argument index="1" name="height" type="int">
</argument>
<description>
- Generate a noise image with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters.
+ Generate a noise image in [constant Image.FORMAT_L8] format with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters.
</description>
</method>
- <method name="get_noise_1d">
+ <method name="get_noise_1d" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="x" type="float">
@@ -45,7 +45,7 @@
[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">
+ <method name="get_noise_2d" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="x" type="float">
@@ -56,7 +56,7 @@
Returns the 2D noise value [code][-1,1][/code] at the given position.
</description>
</method>
- <method name="get_noise_2dv">
+ <method name="get_noise_2dv" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="pos" type="Vector2">
@@ -65,7 +65,7 @@
Returns the 2D noise value [code][-1,1][/code] at the given position.
</description>
</method>
- <method name="get_noise_3d">
+ <method name="get_noise_3d" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="x" type="float">
@@ -78,7 +78,7 @@
Returns the 3D noise value [code][-1,1][/code] at the given position.
</description>
</method>
- <method name="get_noise_3dv">
+ <method name="get_noise_3dv" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="pos" type="Vector3">
@@ -87,7 +87,7 @@
Returns the 3D noise value [code][-1,1][/code] at the given position.
</description>
</method>
- <method name="get_noise_4d">
+ <method name="get_noise_4d" qualifiers="const">
<return type="float">
</return>
<argument index="0" name="x" type="float">
@@ -102,13 +102,13 @@
Returns the 4D noise value [code][-1,1][/code] at the given position.
</description>
</method>
- <method name="get_seamless_image">
+ <method name="get_seamless_image" qualifiers="const">
<return type="Image">
</return>
<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] × [code]size[/code]).
+ Generate a tileable noise image in [constant Image.FORMAT_L8] format, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] × [code]size[/code]).
</description>
</method>
</methods>
diff --git a/modules/opensimplex/icons/NoiseTexture.svg b/modules/opensimplex/icons/NoiseTexture.svg
index 5908c2b2d4..479684cde2 100644
--- a/modules/opensimplex/icons/NoiseTexture.svg
+++ b/modules/opensimplex/icons/NoiseTexture.svg
@@ -1,3 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m2 1c-.55228 0-1 .44772-1 1v12c0 .55228.44772 1 1 1h12c.55228 0 1-.44772 1-1v-12c0-.55228-.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.cpp b/modules/opensimplex/noise_texture.cpp
index 2018f90e9f..1d75e46747 100644
--- a/modules/opensimplex/noise_texture.cpp
+++ b/modules/opensimplex/noise_texture.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,7 +40,7 @@ NoiseTexture::NoiseTexture() {
size = Vector2i(512, 512);
seamless = false;
- as_normalmap = false;
+ as_normal_map = false;
bump_strength = 8.0;
noise = Ref<OpenSimplexNoise>();
@@ -59,7 +59,6 @@ NoiseTexture::~NoiseTexture() {
}
void NoiseTexture::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_width", "width"), &NoiseTexture::set_width);
ClassDB::bind_method(D_METHOD("set_height", "height"), &NoiseTexture::set_height);
@@ -69,8 +68,8 @@ void NoiseTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_seamless", "seamless"), &NoiseTexture::set_seamless);
ClassDB::bind_method(D_METHOD("get_seamless"), &NoiseTexture::get_seamless);
- ClassDB::bind_method(D_METHOD("set_as_normalmap", "as_normalmap"), &NoiseTexture::set_as_normalmap);
- ClassDB::bind_method(D_METHOD("is_normalmap"), &NoiseTexture::is_normalmap);
+ ClassDB::bind_method(D_METHOD("set_as_normal_map", "as_normal_map"), &NoiseTexture::set_as_normal_map);
+ ClassDB::bind_method(D_METHOD("is_normal_map"), &NoiseTexture::is_normal_map);
ClassDB::bind_method(D_METHOD("set_bump_strength", "bump_strength"), &NoiseTexture::set_bump_strength);
ClassDB::bind_method(D_METHOD("get_bump_strength"), &NoiseTexture::get_bump_strength);
@@ -82,15 +81,14 @@ void NoiseTexture::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_width", "get_width");
ADD_PROPERTY(PropertyInfo(Variant::INT, "height", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_height", "get_height");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "seamless"), "set_seamless", "get_seamless");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normalmap"), "set_as_normalmap", "is_normalmap");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normal_map"), "set_as_normal_map", "is_normal_map");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bump_strength", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater"), "set_bump_strength", "get_bump_strength");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"), "set_noise", "get_noise");
}
void NoiseTexture::_validate_property(PropertyInfo &property) const {
-
if (property.name == "bump_strength") {
- if (!as_normalmap) {
+ if (!as_normal_map) {
property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
}
}
@@ -110,7 +108,6 @@ void NoiseTexture::_set_texture_data(const Ref<Image> &p_image) {
}
void NoiseTexture::_thread_done(const Ref<Image> &p_image) {
-
_set_texture_data(p_image);
Thread::wait_to_finish(noise_thread);
memdelete(noise_thread);
@@ -127,16 +124,15 @@ void NoiseTexture::_thread_function(void *p_ud) {
}
void NoiseTexture::_queue_update() {
-
- if (update_queued)
+ if (update_queued) {
return;
+ }
update_queued = true;
call_deferred("_update_texture");
}
Ref<Image> NoiseTexture::_generate_texture() {
-
// Prevent memdelete due to unref() on other thread.
Ref<OpenSimplexNoise> ref_noise = noise;
@@ -152,8 +148,8 @@ Ref<Image> NoiseTexture::_generate_texture() {
image = ref_noise->get_image(size.x, size.y);
}
- if (as_normalmap) {
- image->bumpmap_to_normalmap(bump_strength);
+ if (as_normal_map) {
+ image->bump_map_to_normal_map(bump_strength);
}
return image;
@@ -169,7 +165,6 @@ void NoiseTexture::_update_texture() {
use_thread = false;
#endif
if (use_thread) {
-
if (!noise_thread) {
noise_thread = Thread::create(_thread_function, this);
regen_queued = false;
@@ -185,8 +180,9 @@ void NoiseTexture::_update_texture() {
}
void NoiseTexture::set_noise(Ref<OpenSimplexNoise> p_noise) {
- if (p_noise == noise)
+ if (p_noise == noise) {
return;
+ }
if (noise.is_valid()) {
noise->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NoiseTexture::_queue_update));
}
@@ -202,19 +198,25 @@ Ref<OpenSimplexNoise> NoiseTexture::get_noise() {
}
void NoiseTexture::set_width(int p_width) {
- if (p_width == size.x) return;
+ if (p_width == size.x) {
+ return;
+ }
size.x = p_width;
_queue_update();
}
void NoiseTexture::set_height(int p_height) {
- if (p_height == size.y) return;
+ if (p_height == size.y) {
+ return;
+ }
size.y = p_height;
_queue_update();
}
void NoiseTexture::set_seamless(bool p_seamless) {
- if (p_seamless == seamless) return;
+ if (p_seamless == seamless) {
+ return;
+ }
seamless = p_seamless;
_queue_update();
}
@@ -223,37 +225,38 @@ bool NoiseTexture::get_seamless() {
return seamless;
}
-void NoiseTexture::set_as_normalmap(bool p_as_normalmap) {
- if (p_as_normalmap == as_normalmap) return;
- as_normalmap = p_as_normalmap;
+void NoiseTexture::set_as_normal_map(bool p_as_normal_map) {
+ if (p_as_normal_map == as_normal_map) {
+ return;
+ }
+ as_normal_map = p_as_normal_map;
_queue_update();
_change_notify();
}
-bool NoiseTexture::is_normalmap() {
- return as_normalmap;
+bool NoiseTexture::is_normal_map() {
+ return as_normal_map;
}
void NoiseTexture::set_bump_strength(float p_bump_strength) {
-
- if (p_bump_strength == bump_strength) return;
+ if (p_bump_strength == bump_strength) {
+ return;
+ }
bump_strength = p_bump_strength;
- if (as_normalmap)
+ if (as_normal_map) {
_queue_update();
+ }
}
float NoiseTexture::get_bump_strength() {
-
return bump_strength;
}
int NoiseTexture::get_width() const {
-
return size.x;
}
int NoiseTexture::get_height() const {
-
return size.y;
}
@@ -266,6 +269,5 @@ RID NoiseTexture::get_rid() const {
}
Ref<Image> NoiseTexture::get_data() const {
-
return data;
}
diff --git a/modules/opensimplex/noise_texture.h b/modules/opensimplex/noise_texture.h
index b1d7d3fac9..9f6e2cbf43 100644
--- a/modules/opensimplex/noise_texture.h
+++ b/modules/opensimplex/noise_texture.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,8 +33,8 @@
#include "open_simplex_noise.h"
-#include "core/image.h"
-#include "core/reference.h"
+#include "core/io/image.h"
+#include "core/object/reference.h"
#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
#include "editor/property_editor.h"
@@ -57,7 +57,7 @@ private:
Ref<OpenSimplexNoise> noise;
Vector2i size;
bool seamless;
- bool as_normalmap;
+ bool as_normal_map;
float bump_strength;
void _thread_done(const Ref<Image> &p_image);
@@ -70,7 +70,7 @@ private:
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
void set_noise(Ref<OpenSimplexNoise> p_noise);
@@ -82,19 +82,19 @@ public:
void set_seamless(bool p_seamless);
bool get_seamless();
- void set_as_normalmap(bool p_as_normalmap);
- bool is_normalmap();
+ void set_as_normal_map(bool p_as_normal_map);
+ bool is_normal_map();
void set_bump_strength(float p_bump_strength);
float get_bump_strength();
- int get_width() const;
- int get_height() const;
+ int get_width() const override;
+ int get_height() const override;
- virtual RID get_rid() const;
- virtual bool has_alpha() const { return false; }
+ virtual RID get_rid() const override;
+ virtual bool has_alpha() const override { return false; }
- virtual Ref<Image> get_data() const;
+ virtual Ref<Image> get_data() const override;
NoiseTexture();
virtual ~NoiseTexture();
diff --git a/modules/opensimplex/open_simplex_noise.cpp b/modules/opensimplex/open_simplex_noise.cpp
index 238faa4130..e4e2e0613a 100644
--- a/modules/opensimplex/open_simplex_noise.cpp
+++ b/modules/opensimplex/open_simplex_noise.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "core/core_string_names.h"
OpenSimplexNoise::OpenSimplexNoise() {
-
seed = 0;
persistence = 0.5;
octaves = 3;
@@ -53,9 +52,9 @@ void OpenSimplexNoise::_init_seeds() {
}
void OpenSimplexNoise::set_seed(int p_seed) {
-
- if (seed == p_seed)
+ if (seed == p_seed) {
return;
+ }
seed = p_seed;
@@ -64,13 +63,14 @@ void OpenSimplexNoise::set_seed(int p_seed) {
emit_changed();
}
-int OpenSimplexNoise::get_seed() {
-
+int OpenSimplexNoise::get_seed() const {
return seed;
}
void OpenSimplexNoise::set_octaves(int p_octaves) {
- if (p_octaves == octaves) return;
+ if (p_octaves == octaves) {
+ return;
+ }
ERR_FAIL_COND_MSG(p_octaves > MAX_OCTAVES, vformat("The number of OpenSimplexNoise octaves is limited to %d; ignoring the new value.", MAX_OCTAVES));
@@ -79,56 +79,55 @@ void OpenSimplexNoise::set_octaves(int p_octaves) {
}
void OpenSimplexNoise::set_period(float p_period) {
- if (p_period == period) return;
+ if (p_period == period) {
+ return;
+ }
period = p_period;
emit_changed();
}
void OpenSimplexNoise::set_persistence(float p_persistence) {
- if (p_persistence == persistence) return;
+ if (p_persistence == persistence) {
+ return;
+ }
persistence = p_persistence;
emit_changed();
}
void OpenSimplexNoise::set_lacunarity(float p_lacunarity) {
- if (p_lacunarity == lacunarity) return;
+ if (p_lacunarity == lacunarity) {
+ return;
+ }
lacunarity = p_lacunarity;
emit_changed();
}
-Ref<Image> OpenSimplexNoise::get_image(int p_width, int p_height) {
-
+Ref<Image> OpenSimplexNoise::get_image(int p_width, int p_height) const {
Vector<uint8_t> data;
- data.resize(p_width * p_height * 4);
+ data.resize(p_width * p_height);
uint8_t *wd8 = data.ptrw();
for (int i = 0; i < p_height; i++) {
for (int j = 0; j < p_width; j++) {
- float v = get_noise_2d(i, j);
+ float v = get_noise_2d(j, i);
v = v * 0.5 + 0.5; // Normalize [0..1]
- uint8_t value = uint8_t(CLAMP(v * 255.0, 0, 255));
- wd8[(i * p_width + j) * 4 + 0] = value;
- wd8[(i * p_width + j) * 4 + 1] = value;
- wd8[(i * p_width + j) * 4 + 2] = value;
- wd8[(i * p_width + j) * 4 + 3] = 255;
+ wd8[(i * p_width + j)] = uint8_t(CLAMP(v * 255.0, 0, 255));
}
}
- Ref<Image> image = memnew(Image(p_width, p_height, false, Image::FORMAT_RGBA8, data));
+ Ref<Image> image = memnew(Image(p_width, p_height, false, Image::FORMAT_L8, data));
return image;
}
-Ref<Image> OpenSimplexNoise::get_seamless_image(int p_size) {
-
+Ref<Image> OpenSimplexNoise::get_seamless_image(int p_size) const {
Vector<uint8_t> data;
- data.resize(p_size * p_size * 4);
+ data.resize(p_size * p_size);
uint8_t *wd8 = data.ptrw();
for (int i = 0; i < p_size; i++) {
for (int j = 0; j < p_size; j++) {
-
float ii = (float)i / (float)p_size;
float jj = (float)j / (float)p_size;
@@ -144,20 +143,15 @@ Ref<Image> OpenSimplexNoise::get_seamless_image(int p_size) {
float v = get_noise_4d(x, y, z, w);
v = v * 0.5 + 0.5; // Normalize [0..1]
- uint8_t value = uint8_t(CLAMP(v * 255.0, 0, 255));
- wd8[(i * p_size + j) * 4 + 0] = value;
- wd8[(i * p_size + j) * 4 + 1] = value;
- wd8[(i * p_size + j) * 4 + 2] = value;
- wd8[(i * p_size + j) * 4 + 3] = 255;
+ wd8[(i * p_size + j)] = uint8_t(CLAMP(v * 255.0, 0, 255));
}
}
- Ref<Image> image = memnew(Image(p_size, p_size, false, Image::FORMAT_RGBA8, data));
+ Ref<Image> image = memnew(Image(p_size, p_size, false, Image::FORMAT_L8, data));
return image;
}
void OpenSimplexNoise::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("get_seed"), &OpenSimplexNoise::get_seed);
ClassDB::bind_method(D_METHOD("set_seed", "seed"), &OpenSimplexNoise::set_seed);
@@ -191,13 +185,11 @@ void OpenSimplexNoise::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lacunarity", PROPERTY_HINT_RANGE, "0.1,4.0,0.01"), "set_lacunarity", "get_lacunarity");
}
-float OpenSimplexNoise::get_noise_1d(float x) {
-
+float OpenSimplexNoise::get_noise_1d(float x) const {
return get_noise_2d(x, 1.0);
}
-float OpenSimplexNoise::get_noise_2d(float x, float y) {
-
+float OpenSimplexNoise::get_noise_2d(float x, float y) const {
x /= period;
y /= period;
@@ -217,8 +209,7 @@ float OpenSimplexNoise::get_noise_2d(float x, float y) {
return sum / max;
}
-float OpenSimplexNoise::get_noise_3d(float x, float y, float z) {
-
+float OpenSimplexNoise::get_noise_3d(float x, float y, float z) const {
x /= period;
y /= period;
z /= period;
@@ -240,8 +231,7 @@ float OpenSimplexNoise::get_noise_3d(float x, float y, float z) {
return sum / max;
}
-float OpenSimplexNoise::get_noise_4d(float x, float y, float z, float w) {
-
+float OpenSimplexNoise::get_noise_4d(float x, float y, float z, float w) const {
x /= period;
y /= period;
z /= period;
diff --git a/modules/opensimplex/open_simplex_noise.h b/modules/opensimplex/open_simplex_noise.h
index dce62bc1f9..f18dd4d798 100644
--- a/modules/opensimplex/open_simplex_noise.h
+++ b/modules/opensimplex/open_simplex_noise.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,21 +31,21 @@
#ifndef OPEN_SIMPLEX_NOISE_H
#define OPEN_SIMPLEX_NOISE_H
-#include "core/image.h"
-#include "core/reference.h"
+#include "core/io/image.h"
+#include "core/object/reference.h"
#include "scene/resources/texture.h"
#include "thirdparty/misc/open-simplex-noise.h"
-// The maximum number of octaves allowed. Note that these are statically allocated.
-// Higher values become exponentially slower, so this shouldn't be set too high
-// to avoid freezing the editor for long periods of time.
-#define MAX_OCTAVES 9
-
class OpenSimplexNoise : public Resource {
GDCLASS(OpenSimplexNoise, Resource);
OBJ_SAVE_TYPE(OpenSimplexNoise);
+ // The maximum number of octaves allowed. Note that these are statically allocated.
+ // Higher values become exponentially slower, so this shouldn't be set too high
+ // to avoid freezing the editor for long periods of time.
+ static const int MAX_OCTAVES = 9;
+
osn_context contexts[MAX_OCTAVES];
int seed;
@@ -61,7 +61,7 @@ public:
void _init_seeds();
void set_seed(int seed);
- int get_seed();
+ int get_seed() const;
void set_octaves(int p_octaves);
int get_octaves() const { return octaves; }
@@ -75,22 +75,22 @@ public:
void set_lacunarity(float p_lacunarity);
float get_lacunarity() const { return lacunarity; }
- Ref<Image> get_image(int p_width, int p_height);
- Ref<Image> get_seamless_image(int p_size);
+ Ref<Image> get_image(int p_width, int p_height) const;
+ Ref<Image> get_seamless_image(int p_size) const;
- float get_noise_1d(float x);
- float get_noise_2d(float x, float y);
- float get_noise_3d(float x, float y, float z);
- float get_noise_4d(float x, float y, float z, float w);
+ float get_noise_1d(float x) const;
+ float get_noise_2d(float x, float y) const;
+ float get_noise_3d(float x, float y, float z) const;
+ float get_noise_4d(float x, float y, float z, float w) const;
- _FORCE_INLINE_ float _get_octave_noise_2d(int octave, float x, float y) { return open_simplex_noise2(&(contexts[octave]), x, y); }
- _FORCE_INLINE_ float _get_octave_noise_3d(int octave, float x, float y, float z) { return open_simplex_noise3(&(contexts[octave]), x, y, z); }
- _FORCE_INLINE_ float _get_octave_noise_4d(int octave, float x, float y, float z, float w) { return open_simplex_noise4(&(contexts[octave]), x, y, z, w); }
+ _FORCE_INLINE_ float _get_octave_noise_2d(int octave, float x, float y) const { return open_simplex_noise2(&(contexts[octave]), x, y); }
+ _FORCE_INLINE_ float _get_octave_noise_3d(int octave, float x, float y, float z) const { return open_simplex_noise3(&(contexts[octave]), x, y, z); }
+ _FORCE_INLINE_ float _get_octave_noise_4d(int octave, float x, float y, float z, float w) const { return open_simplex_noise4(&(contexts[octave]), x, y, z, w); }
// Convenience
- _FORCE_INLINE_ float get_noise_2dv(Vector2 v) { return get_noise_2d(v.x, v.y); }
- _FORCE_INLINE_ float get_noise_3dv(Vector3 v) { return get_noise_3d(v.x, v.y, v.z); }
+ _FORCE_INLINE_ float get_noise_2dv(const Vector2 &v) const { return get_noise_2d(v.x, v.y); }
+ _FORCE_INLINE_ float get_noise_3dv(const Vector3 &v) const { return get_noise_3d(v.x, v.y, v.z); }
protected:
static void _bind_methods();
diff --git a/modules/opensimplex/register_types.cpp b/modules/opensimplex/register_types.cpp
index 6fae1fe415..e9735a2cc8 100644
--- a/modules/opensimplex/register_types.cpp
+++ b/modules/opensimplex/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "open_simplex_noise.h"
void register_opensimplex_types() {
-
ClassDB::register_class<OpenSimplexNoise>();
ClassDB::register_class<NoiseTexture>();
}
diff --git a/modules/opensimplex/register_types.h b/modules/opensimplex/register_types.h
index 51c6815eae..d72e37e3a3 100644
--- a/modules/opensimplex/register_types.h
+++ b/modules/opensimplex/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/opus/SCsub b/modules/opus/SCsub
index e51590d808..1437cd86df 100644
--- a/modules/opus/SCsub
+++ b/modules/opus/SCsub
@@ -10,6 +10,10 @@ Import("env_modules")
env_opus = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
+# Thirdparty source files
if env["builtin_opus"]:
thirdparty_dir = "#thirdparty/opus/"
@@ -227,10 +231,22 @@ if env["builtin_opus"]:
env_opus.Append(CPPDEFINES=["OPUS_ARM_OPT"])
elif "arch" in env and env["arch"] == "arm64":
env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"])
+ elif env["platform"] == "osx":
+ if "arch" in env and env["arch"] == "arm64":
+ env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"])
env_thirdparty = env_opus.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_opus.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Module files
-env_opus.add_source_files(env.modules_sources, "register_types.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/opus/config.py b/modules/opus/config.py
index d22f9454ed..9ff7b2dece 100644
--- a/modules/opus/config.py
+++ b/modules/opus/config.py
@@ -1,5 +1,5 @@
def can_build(env, platform):
- return True
+ return env.module_check_dependencies("opus", ["ogg"])
def configure(env):
diff --git a/modules/opus/register_types.cpp b/modules/opus/register_types.cpp
index a4329e142c..02874a9a4b 100644
--- a/modules/opus/register_types.cpp
+++ b/modules/opus/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/opus/register_types.h b/modules/opus/register_types.h
index ad6e083c82..af889cf809 100644
--- a/modules/opus/register_types.h
+++ b/modules/opus/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/pvr/SCsub b/modules/pvr/SCsub
index e0baf851f1..36052cffed 100644
--- a/modules/pvr/SCsub
+++ b/modules/pvr/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_pvr = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
# Not unbundled so far since not widespread as shared library
thirdparty_dir = "#thirdparty/pvrtccompressor/"
thirdparty_sources = [
@@ -21,7 +24,15 @@ env_pvr.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_pvr.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
# Godot source files
-env_pvr.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_pvr.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/pvr/image_compress_pvrtc.cpp b/modules/pvr/image_compress_pvrtc.cpp
new file mode 100644
index 0000000000..d2d8976694
--- /dev/null
+++ b/modules/pvr/image_compress_pvrtc.cpp
@@ -0,0 +1,84 @@
+/*************************************************************************/
+/* image_compress_pvrtc.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "image_compress_pvrtc.h"
+
+#include "core/io/image.h"
+#include "core/object/reference.h"
+
+#include <PvrTcEncoder.h>
+#include <RgbaBitmap.h>
+
+static void _compress_pvrtc1_4bpp(Image *p_img) {
+ Ref<Image> img = p_img->duplicate();
+
+ bool make_mipmaps = false;
+ if (!img->is_size_po2() || img->get_width() != img->get_height()) {
+ make_mipmaps = img->has_mipmaps();
+ img->resize_to_po2(true);
+ }
+ img->convert(Image::FORMAT_RGBA8);
+ if (!img->has_mipmaps() && make_mipmaps) {
+ img->generate_mipmaps();
+ }
+
+ bool use_alpha = img->detect_alpha();
+
+ Ref<Image> new_img;
+ new_img.instance();
+ new_img->create(img->get_width(), img->get_height(), img->has_mipmaps(), use_alpha ? Image::FORMAT_PVRTC1_4A : Image::FORMAT_PVRTC1_4);
+
+ Vector<uint8_t> data = new_img->get_data();
+ {
+ uint8_t *wr = data.ptrw();
+ const uint8_t *r = img->get_data().ptr();
+
+ for (int i = 0; i <= new_img->get_mipmap_count(); i++) {
+ int ofs, size, w, h;
+ img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
+ Javelin::RgbaBitmap bm(w, h);
+ void *dst = (void *)bm.GetData();
+ copymem(dst, &r[ofs], size);
+ Javelin::ColorRgba<unsigned char> *dp = bm.GetData();
+ for (int j = 0; j < size / 4; j++) {
+ // Red and blue colors are swapped.
+ SWAP(dp[j].r, dp[j].b);
+ }
+ new_img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
+ Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs], bm);
+ }
+ }
+
+ p_img->create(new_img->get_width(), new_img->get_height(), new_img->has_mipmaps(), new_img->get_format(), data);
+}
+
+void _register_pvrtc_compress_func() {
+ Image::_image_compress_pvrtc1_4bpp_func = _compress_pvrtc1_4bpp;
+}
diff --git a/modules/pvr/image_compress_pvrtc.h b/modules/pvr/image_compress_pvrtc.h
new file mode 100644
index 0000000000..985076ce4d
--- /dev/null
+++ b/modules/pvr/image_compress_pvrtc.h
@@ -0,0 +1,36 @@
+/*************************************************************************/
+/* image_compress_pvrtc.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 IMAGE_COMPRESS_PVRTC_H
+#define IMAGE_COMPRESS_PVRTC_H
+
+void _register_pvrtc_compress_func();
+
+#endif // IMAGE_COMPRESS_PVRTC_H
diff --git a/modules/pvr/register_types.cpp b/modules/pvr/register_types.cpp
index 5f900a0256..aeac564c93 100644
--- a/modules/pvr/register_types.cpp
+++ b/modules/pvr/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,18 +30,19 @@
#include "register_types.h"
+#include "image_compress_pvrtc.h"
#include "texture_loader_pvr.h"
static Ref<ResourceFormatPVR> resource_loader_pvr;
void register_pvr_types() {
-
resource_loader_pvr.instance();
ResourceLoader::add_resource_format_loader(resource_loader_pvr);
+
+ _register_pvrtc_compress_func();
}
void unregister_pvr_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_pvr);
resource_loader_pvr.unref();
}
diff --git a/modules/pvr/register_types.h b/modules/pvr/register_types.h
index 8318996a46..74fcfe2ce4 100644
--- a/modules/pvr/register_types.h
+++ b/modules/pvr/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp
index a8e8a9a2f1..70a3c8b5a9 100644
--- a/modules/pvr/texture_loader_pvr.cpp
+++ b/modules/pvr/texture_loader_pvr.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,16 +29,12 @@
/*************************************************************************/
#include "texture_loader_pvr.h"
-#include "PvrTcEncoder.h"
-#include "RgbaBitmap.h"
+
#include "core/os/file_access.h"
-#include <string.h>
-#include <new>
static void _pvrtc_decompress(Image *p_img);
enum PVRFLags {
-
PVR_HAS_MIPMAPS = 0x00000100,
PVR_TWIDDLED = 0x00000200,
PVR_NORMAL_MAP = 0x00000400,
@@ -48,25 +44,26 @@ enum PVRFLags {
PVR_VOLUME_TEXTURES = 0x00004000,
PVR_HAS_ALPHA = 0x00008000,
PVR_VFLIP = 0x00010000
-
};
RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
- if (r_error)
+ if (r_error) {
*r_error = ERR_CANT_OPEN;
+ }
Error err;
FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
- if (!f)
+ if (!f) {
return RES();
+ }
FileAccessRef faref(f);
ERR_FAIL_COND_V(err, RES());
- if (r_error)
+ if (r_error) {
*r_error = ERR_FILE_CORRUPT;
+ }
uint32_t hsize = f->get_32();
@@ -109,11 +106,14 @@ RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path,
Image::Format format = Image::FORMAT_MAX;
switch (flags & 0xFF) {
-
case 0x18:
- case 0xC: format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC2A : Image::FORMAT_PVRTC2; break;
+ case 0xC:
+ format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC1_2A : Image::FORMAT_PVRTC1_2;
+ break;
case 0x19:
- case 0xD: format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC4A : Image::FORMAT_PVRTC4; break;
+ case 0xD:
+ format = (flags & PVR_HAS_ALPHA) ? Image::FORMAT_PVRTC1_4A : Image::FORMAT_PVRTC1_4;
+ break;
case 0x16:
format = Image::FORMAT_L8;
break;
@@ -153,79 +153,35 @@ RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path,
}
Ref<Image> image = memnew(Image(width, height, mipmaps, format, data));
- ERR_FAIL_COND_V(image->empty(), RES());
+ ERR_FAIL_COND_V(image->is_empty(), RES());
Ref<ImageTexture> texture = memnew(ImageTexture);
texture->create_from_image(image);
- if (r_error)
+ if (r_error) {
*r_error = OK;
+ }
return texture;
}
void ResourceFormatPVR::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("pvr");
}
-bool ResourceFormatPVR::handles_type(const String &p_type) const {
+bool ResourceFormatPVR::handles_type(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "Texture2D");
}
-String ResourceFormatPVR::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower() == "pvr")
+String ResourceFormatPVR::get_resource_type(const String &p_path) const {
+ if (p_path.get_extension().to_lower() == "pvr") {
return "Texture2D";
- return "";
-}
-
-static void _compress_pvrtc4(Image *p_img) {
-
- Ref<Image> img = p_img->duplicate();
-
- bool make_mipmaps = false;
- if (!img->is_size_po2() || img->get_width() != img->get_height()) {
- make_mipmaps = img->has_mipmaps();
- img->resize_to_po2(true);
}
- img->convert(Image::FORMAT_RGBA8);
- if (!img->has_mipmaps() && make_mipmaps)
- img->generate_mipmaps();
-
- bool use_alpha = img->detect_alpha();
-
- Ref<Image> new_img;
- new_img.instance();
- new_img->create(img->get_width(), img->get_height(), img->has_mipmaps(), use_alpha ? Image::FORMAT_PVRTC4A : Image::FORMAT_PVRTC4);
-
- Vector<uint8_t> data = new_img->get_data();
- {
- uint8_t *wr = data.ptrw();
- const uint8_t *r = img->get_data().ptr();
-
- for (int i = 0; i <= new_img->get_mipmap_count(); i++) {
-
- int ofs, size, w, h;
- img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
- Javelin::RgbaBitmap bm(w, h);
- for (int j = 0; j < size / 4; j++) {
- Javelin::ColorRgba<unsigned char> *dp = bm.GetData();
- /* red and Green colors are swapped. */
- new (dp) Javelin::ColorRgba<unsigned char>(r[ofs + 4 * j + 2], r[ofs + 4 * j + 1], r[ofs + 4 * j], r[ofs + 4 * j + 3]);
- }
- new_img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
- Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs], bm);
- }
- }
-
- p_img->create(new_img->get_width(), new_img->get_height(), new_img->has_mipmaps(), new_img->get_format(), data);
+ return "";
}
ResourceFormatPVR::ResourceFormatPVR() {
-
Image::_image_decompress_pvrtc = _pvrtc_decompress;
- Image::_image_compress_pvrtc4_func = _compress_pvrtc4;
- Image::_image_compress_pvrtc2_func = _compress_pvrtc4;
}
/////////////////////////////////////////////////////////
@@ -255,31 +211,28 @@ struct PVRTCBlock {
};
_FORCE_INLINE_ bool is_po2(uint32_t p_input) {
-
- if (p_input == 0)
- return 0;
+ if (p_input == 0) {
+ return false;
+ }
uint32_t minus1 = p_input - 1;
- return ((p_input | minus1) == (p_input ^ minus1)) ? 1 : 0;
+ return ((p_input | minus1) == (p_input ^ minus1)) ? true : false;
}
static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) {
-
uint32_t raw_bits[2];
raw_bits[0] = p_block->data[1] & (0xFFFE);
raw_bits[1] = p_block->data[1] >> 16;
for (int i = 0; i < 2; i++) {
-
if (raw_bits[i] & (1 << 15)) {
-
p_ab_colors[i][0] = (raw_bits[i] >> 10) & 0x1F;
p_ab_colors[i][1] = (raw_bits[i] >> 5) & 0x1F;
p_ab_colors[i][2] = raw_bits[i] & 0x1F;
- if (i == 0)
+ if (i == 0) {
p_ab_colors[0][2] |= p_ab_colors[0][2] >> 4;
+ }
p_ab_colors[i][3] = 0xF;
} else {
-
p_ab_colors[i][0] = (raw_bits[i] >> (8 - 1)) & 0x1E;
p_ab_colors[i][1] = (raw_bits[i] >> (4 - 1)) & 0x1E;
@@ -288,10 +241,11 @@ static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) {
p_ab_colors[i][2] = (raw_bits[i] & 0xF) << 1;
- if (i == 0)
+ if (i == 0) {
p_ab_colors[0][2] |= p_ab_colors[0][2] >> 3;
- else
+ } else {
p_ab_colors[0][2] |= p_ab_colors[0][2] >> 4;
+ }
p_ab_colors[i][3] = (raw_bits[i] >> 11) & 0xE;
}
@@ -299,15 +253,12 @@ static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) {
}
static void unpack_modulations(const PVRTCBlock *p_block, const int p_2bit, int p_modulation[8][16], int p_modulation_modes[8][16], int p_x, int p_y) {
-
int block_mod_mode = p_block->data[1] & 1;
uint32_t modulation_bits = p_block->data[0];
if (p_2bit && block_mod_mode) {
-
for (int y = 0; y < BLK_Y_SIZE; y++) {
for (int x = 0; x < BLK_X_2BPP; x++) {
-
p_modulation_modes[y + p_y][x + p_x] = block_mod_mode;
if (((x ^ y) & 1) == 0) {
@@ -318,15 +269,15 @@ static void unpack_modulations(const PVRTCBlock *p_block, const int p_2bit, int
}
} else if (p_2bit) {
-
for (int y = 0; y < BLK_Y_SIZE; y++) {
for (int x = 0; x < BLK_X_2BPP; x++) {
p_modulation_modes[y + p_y][x + p_x] = block_mod_mode;
- if (modulation_bits & 1)
+ if (modulation_bits & 1) {
p_modulation[y + p_y][x + p_x] = 0x3;
- else
+ } else {
p_modulation[y + p_y][x + p_x] = 0x0;
+ }
modulation_bits >>= 1;
}
@@ -361,10 +312,11 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con
v = (y & 0x3) | ((~y & 0x2) << 1);
- if (p_2bit)
+ if (p_2bit) {
u = (x & 0x7) | ((~x & 0x4) << 1);
- else
+ } else {
u = (x & 0x3) | ((~x & 0x2) << 1);
+ }
v = v - BLK_Y_SIZE / 2;
@@ -420,19 +372,20 @@ static void get_modulation_value(int x, int y, const int p_2bit, const int p_mod
y = (y & 0x3) | ((~y & 0x2) << 1);
- if (p_2bit)
+ if (p_2bit) {
x = (x & 0x7) | ((~x & 0x4) << 1);
- else
+ } else {
x = (x & 0x3) | ((~x & 0x2) << 1);
+ }
*p_dopt = 0;
if (p_modulation_modes[y][x] == 0) {
mod_val = rep_vals0[p_modulation[y][x]];
} else if (p_2bit) {
- if (((x ^ y) & 1) == 0)
+ if (((x ^ y) & 1) == 0) {
mod_val = rep_vals0[p_modulation[y][x]];
- else if (p_modulation_modes[y][x] == 1) {
+ } else if (p_modulation_modes[y][x] == 1) {
mod_val = (rep_vals0[p_modulation[y - 1][x]] +
rep_vals0[p_modulation[y + 1][x]] +
rep_vals0[p_modulation[y][x - 1]] +
@@ -459,7 +412,6 @@ static void get_modulation_value(int x, int y, const int p_2bit, const int p_mod
static int disable_twiddling = 0;
static uint32_t twiddle_uv(uint32_t p_height, uint32_t p_width, uint32_t p_y, uint32_t p_x) {
-
uint32_t twiddled;
uint32_t min_dimension;
@@ -484,8 +436,9 @@ static uint32_t twiddle_uv(uint32_t p_height, uint32_t p_width, uint32_t p_y, ui
max_value = p_y;
}
- if (disable_twiddling)
+ if (disable_twiddling) {
return (p_y * p_width + p_x);
+ }
scr_bit_pos = 1;
dst_bit_pos = 1;
@@ -545,17 +498,17 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
int r_result[4];
- if (p_2bit)
+ if (p_2bit) {
x_block_size = BLK_X_2BPP;
- else
+ } else {
x_block_size = BLK_X_4BPP;
+ }
block_width = MAX(2, p_width / x_block_size);
block_height = MAX(2, p_height / BLK_Y_SIZE);
for (y = 0; y < p_height; y++) {
for (x = 0; x < p_width; x++) {
-
block_x = (x - x_block_size / 2);
blk_y = (y - BLK_Y_SIZE / 2);
@@ -620,8 +573,9 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
r_result[i] >>= 3;
}
- if (DoPT)
+ if (DoPT) {
r_result[3] = 0;
+ }
u_pos = (x + y * p_width) << 2;
p_dst[u_pos + 0] = (uint8_t)r_result[0];
@@ -633,10 +587,9 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
}
static void _pvrtc_decompress(Image *p_img) {
+ ERR_FAIL_COND(p_img->get_format() != Image::FORMAT_PVRTC1_2 && p_img->get_format() != Image::FORMAT_PVRTC1_2A && p_img->get_format() != Image::FORMAT_PVRTC1_4 && p_img->get_format() != Image::FORMAT_PVRTC1_4A);
- ERR_FAIL_COND(p_img->get_format() != Image::FORMAT_PVRTC2 && p_img->get_format() != Image::FORMAT_PVRTC2A && p_img->get_format() != Image::FORMAT_PVRTC4 && p_img->get_format() != Image::FORMAT_PVRTC4A);
-
- bool _2bit = (p_img->get_format() == Image::FORMAT_PVRTC2 || p_img->get_format() == Image::FORMAT_PVRTC2A);
+ bool _2bit = (p_img->get_format() == Image::FORMAT_PVRTC1_2 || p_img->get_format() == Image::FORMAT_PVRTC1_2A);
Vector<uint8_t> data = p_img->get_data();
const uint8_t *r = data.ptr();
@@ -649,6 +602,7 @@ static void _pvrtc_decompress(Image *p_img) {
bool make_mipmaps = p_img->has_mipmaps();
p_img->create(p_img->get_width(), p_img->get_height(), false, Image::FORMAT_RGBA8, newdata);
- if (make_mipmaps)
+ if (make_mipmaps) {
p_img->generate_mipmaps();
+ }
}
diff --git a/modules/pvr/texture_loader_pvr.h b/modules/pvr/texture_loader_pvr.h
index 07ef129689..da425c3237 100644
--- a/modules/pvr/texture_loader_pvr.h
+++ b/modules/pvr/texture_loader_pvr.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/regex/SCsub b/modules/regex/SCsub
index 753650adcb..deb9db7591 100644
--- a/modules/regex/SCsub
+++ b/modules/regex/SCsub
@@ -5,9 +5,13 @@ Import("env_modules")
env_regex = env_modules.Clone()
+# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_pcre2"]:
thirdparty_dir = "#thirdparty/pcre2/src/"
- thirdparty_flags = ["PCRE2_STATIC", "HAVE_CONFIG_H"]
+ thirdparty_flags = ["PCRE2_STATIC", "HAVE_CONFIG_H", "SUPPORT_UNICODE"]
if env["builtin_pcre2_with_jit"]:
thirdparty_flags.append("SUPPORT_JIT")
@@ -52,11 +56,21 @@ if env["builtin_pcre2"]:
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(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", width)])
+ env_pcre2.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
pcre2_builtin("16")
pcre2_builtin("32")
+
+# Godot source files
+
+module_obj = []
+
env_regex.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", 0)])
-env_regex.add_source_files(env.modules_sources, "*.cpp")
+env_regex.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml
index 3130c53331..b21f5d1e7a 100644
--- a/modules/regex/doc_classes/RegEx.xml
+++ b/modules/regex/doc_classes/RegEx.xml
@@ -11,7 +11,7 @@
regex.compile("\\w-(\\d+)")
[/codeblock]
The search pattern must be escaped first for GDScript before it is escaped for the expression. For example, [code]compile("\\d+")[/code] would be read by RegEx as [code]\d+[/code]. Similarly, [code]compile("\"(?:\\\\.|[^\"])*\"")[/code] would be read as [code]"(?:\\.|[^"])*"[/code].
- Using [method search] you can find the pattern within the given text. If a pattern is found, [RegExMatch] is returned and you can retrieve details of the results using functions such as [method RegExMatch.get_string] and [method RegExMatch.get_start].
+ Using [method search], you can find the pattern within the given text. If a pattern is found, [RegExMatch] is returned and you can retrieve details of the results using methods such as [method RegExMatch.get_string] and [method RegExMatch.get_start].
[codeblock]
var regex = RegEx.new()
regex.compile("\\w-(\\d+)")
@@ -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 will 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 methods 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()
@@ -32,8 +32,16 @@
[codeblock]
for result in regex.search_all("d01, d03, d0c, x3f and x42"):
print(result.get_string("digit"))
- # Would print 01 03 3f 42
- # Note that d0c would not match
+ # Would print 01 03 0 3f 42
+ [/codeblock]
+ [b]Example of splitting a string using a RegEx:[/b]
+ [codeblock]
+ var regex = RegEx.new()
+ regex.compile("\\S+") # Negated whitespace character class.
+ var results = []
+ for result in regex.search_all("One Two \n\tThree"):
+ results.push_back(result.get_string())
+ # The `results` array now contains "One", "Two", "Three".
[/codeblock]
[b]Note:[/b] Godot's regex implementation is based on the [url=https://www.pcre.org/]PCRE2[/url] library. You can view the full pattern reference [url=https://www.pcre.org/current/doc/html/pcre2pattern.html]here[/url].
[b]Tip:[/b] You can use [url=https://regexr.com/]Regexr[/url] to test regular expressions online.
diff --git a/modules/regex/doc_classes/RegExMatch.xml b/modules/regex/doc_classes/RegExMatch.xml
index 151e881b6f..a45de60aef 100644
--- a/modules/regex/doc_classes/RegExMatch.xml
+++ b/modules/regex/doc_classes/RegExMatch.xml
@@ -49,7 +49,7 @@
</methods>
<members>
<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.
+ A dictionary of named groups and its corresponding group number. Only groups 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" default="[ ]">
An [Array] of the match and its capturing groups.
diff --git a/modules/regex/regex.cpp b/modules/regex/regex.cpp
index 25cc580591..fe8136ef35 100644
--- a/modules/regex/regex.cpp
+++ b/modules/regex/regex.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,48 +36,43 @@ extern "C" {
}
static void *_regex_malloc(PCRE2_SIZE size, void *user) {
-
return memalloc(size);
}
static void _regex_free(void *ptr, void *user) {
-
memfree(ptr);
}
int RegExMatch::_find(const Variant &p_name) const {
-
if (p_name.is_num()) {
-
int i = (int)p_name;
- if (i >= data.size())
+ if (i >= data.size()) {
return -1;
+ }
return i;
} else if (p_name.get_type() == Variant::STRING) {
-
const Map<String, int>::Element *found = names.find((String)p_name);
- if (found)
+ if (found) {
return found->value();
+ }
}
return -1;
}
String RegExMatch::get_subject() const {
-
return subject;
}
int RegExMatch::get_group_count() const {
-
- if (data.size() == 0)
+ if (data.size() == 0) {
return 0;
+ }
return data.size() - 1;
}
Dictionary RegExMatch::get_names() const {
-
Dictionary result;
for (const Map<String, int>::Element *i = names.front(); i != nullptr; i = i->next()) {
@@ -88,13 +83,11 @@ Dictionary RegExMatch::get_names() const {
}
Array RegExMatch::get_strings() const {
-
Array result;
int size = data.size();
for (int i = 0; i < size; i++) {
-
int start = data[i].start;
if (start == -1) {
@@ -111,16 +104,17 @@ Array RegExMatch::get_strings() const {
}
String RegExMatch::get_string(const Variant &p_name) const {
-
int id = _find(p_name);
- if (id < 0)
+ if (id < 0) {
return String();
+ }
int start = data[id].start;
- if (start == -1)
+ if (start == -1) {
return String();
+ }
int length = data[id].end - start;
@@ -128,27 +122,26 @@ String RegExMatch::get_string(const Variant &p_name) const {
}
int RegExMatch::get_start(const Variant &p_name) const {
-
int id = _find(p_name);
- if (id < 0)
+ if (id < 0) {
return -1;
+ }
return data[id].start;
}
int RegExMatch::get_end(const Variant &p_name) const {
-
int id = _find(p_name);
- if (id < 0)
+ if (id < 0) {
return -1;
+ }
return data[id].end;
}
void RegExMatch::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("get_subject"), &RegExMatch::get_subject);
ClassDB::bind_method(D_METHOD("get_group_count"), &RegExMatch::get_group_count);
ClassDB::bind_method(D_METHOD("get_names"), &RegExMatch::get_names);
@@ -163,37 +156,17 @@ void RegExMatch::_bind_methods() {
}
void RegEx::_pattern_info(uint32_t what, void *where) const {
-
- if (sizeof(CharType) == 2) {
-
- pcre2_pattern_info_16((pcre2_code_16 *)code, what, where);
-
- } else {
-
- pcre2_pattern_info_32((pcre2_code_32 *)code, what, where);
- }
+ pcre2_pattern_info_32((pcre2_code_32 *)code, what, where);
}
void RegEx::clear() {
-
- if (sizeof(CharType) == 2) {
-
- if (code) {
- pcre2_code_free_16((pcre2_code_16 *)code);
- code = nullptr;
- }
-
- } else {
-
- if (code) {
- pcre2_code_free_32((pcre2_code_32 *)code);
- code = nullptr;
- }
+ if (code) {
+ pcre2_code_free_32((pcre2_code_32 *)code);
+ code = nullptr;
}
}
Error RegEx::compile(const String &p_pattern) {
-
pattern = p_pattern;
clear();
@@ -201,122 +174,67 @@ Error RegEx::compile(const String &p_pattern) {
PCRE2_SIZE offset;
uint32_t flags = PCRE2_DUPNAMES;
- if (sizeof(CharType) == 2) {
-
- pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
- pcre2_compile_context_16 *cctx = pcre2_compile_context_create_16(gctx);
- PCRE2_SPTR16 p = (PCRE2_SPTR16)pattern.c_str();
+ pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
+ pcre2_compile_context_32 *cctx = pcre2_compile_context_create_32(gctx);
+ PCRE2_SPTR32 p = (PCRE2_SPTR32)pattern.get_data();
- code = pcre2_compile_16(p, pattern.length(), flags, &err, &offset, cctx);
+ code = pcre2_compile_32(p, pattern.length(), flags, &err, &offset, cctx);
- pcre2_compile_context_free_16(cctx);
+ pcre2_compile_context_free_32(cctx);
- if (!code) {
- PCRE2_UCHAR16 buf[256];
- pcre2_get_error_message_16(err, buf, 256);
- String message = String::num(offset) + ": " + String((const CharType *)buf);
- ERR_PRINT(message.utf8());
- return FAILED;
- }
-
- } else {
-
- pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
- pcre2_compile_context_32 *cctx = pcre2_compile_context_create_32(gctx);
- PCRE2_SPTR32 p = (PCRE2_SPTR32)pattern.c_str();
-
- code = pcre2_compile_32(p, pattern.length(), flags, &err, &offset, cctx);
-
- pcre2_compile_context_free_32(cctx);
-
- if (!code) {
- PCRE2_UCHAR32 buf[256];
- pcre2_get_error_message_32(err, buf, 256);
- String message = String::num(offset) + ": " + String((const CharType *)buf);
- ERR_PRINT(message.utf8());
- return FAILED;
- }
+ if (!code) {
+ PCRE2_UCHAR32 buf[256];
+ pcre2_get_error_message_32(err, buf, 256);
+ String message = String::num(offset) + ": " + String((const char32_t *)buf);
+ ERR_PRINT(message.utf8());
+ return FAILED;
}
return OK;
}
Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end) const {
-
ERR_FAIL_COND_V(!is_valid(), nullptr);
Ref<RegExMatch> result = memnew(RegExMatch);
int length = p_subject.length();
- if (p_end >= 0 && p_end < length)
+ if (p_end >= 0 && p_end < length) {
length = p_end;
+ }
- if (sizeof(CharType) == 2) {
-
- pcre2_code_16 *c = (pcre2_code_16 *)code;
- pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
- pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
- PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
-
- pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
-
- int res = pcre2_match_16(c, s, length, p_offset, 0, match, mctx);
-
- if (res < 0) {
- pcre2_match_data_free_16(match);
- return nullptr;
- }
-
- uint32_t size = pcre2_get_ovector_count_16(match);
- PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_16(match);
-
- result->data.resize(size);
-
- for (uint32_t i = 0; i < size; i++) {
-
- result->data.write[i].start = ovector[i * 2];
- result->data.write[i].end = ovector[i * 2 + 1];
- }
-
- pcre2_match_data_free_16(match);
- pcre2_match_context_free_16(mctx);
-
- } else {
-
- pcre2_code_32 *c = (pcre2_code_32 *)code;
- pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
- pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
- PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
-
- pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
+ pcre2_code_32 *c = (pcre2_code_32 *)code;
+ pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
+ pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
+ PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.get_data();
- int res = pcre2_match_32(c, s, length, p_offset, 0, match, mctx);
+ pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
- if (res < 0) {
- pcre2_match_data_free_32(match);
- pcre2_match_context_free_32(mctx);
+ int res = pcre2_match_32(c, s, length, p_offset, 0, match, mctx);
- return nullptr;
- }
-
- uint32_t size = pcre2_get_ovector_count_32(match);
- PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_32(match);
+ if (res < 0) {
+ pcre2_match_data_free_32(match);
+ pcre2_match_context_free_32(mctx);
- result->data.resize(size);
+ return nullptr;
+ }
- for (uint32_t i = 0; i < size; i++) {
+ uint32_t size = pcre2_get_ovector_count_32(match);
+ PCRE2_SIZE *ovector = pcre2_get_ovector_pointer_32(match);
- result->data.write[i].start = ovector[i * 2];
- result->data.write[i].end = ovector[i * 2 + 1];
- }
+ result->data.resize(size);
- pcre2_match_data_free_32(match);
- pcre2_match_context_free_32(mctx);
+ for (uint32_t i = 0; i < size; i++) {
+ result->data.write[i].start = ovector[i * 2];
+ result->data.write[i].end = ovector[i * 2 + 1];
}
+ pcre2_match_data_free_32(match);
+ pcre2_match_context_free_32(mctx);
+
result->subject = p_subject;
uint32_t count;
- const CharType *table;
+ const char32_t *table;
uint32_t entry_size;
_pattern_info(PCRE2_INFO_NAMECOUNT, &count);
@@ -324,13 +242,14 @@ Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end)
_pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
for (uint32_t i = 0; i < count; i++) {
-
- CharType id = table[i * entry_size];
- if (result->data[id].start == -1)
+ char32_t id = table[i * entry_size];
+ if (result->data[id].start == -1) {
continue;
+ }
String name = &table[i * entry_size + 1];
- if (result->names.has(name))
+ if (result->names.has(name)) {
continue;
+ }
result->names.insert(name, id);
}
@@ -339,13 +258,13 @@ Ref<RegExMatch> RegEx::search(const String &p_subject, int p_offset, int p_end)
}
Array RegEx::search_all(const String &p_subject, int p_offset, int p_end) const {
-
int last_end = -1;
Array result;
Ref<RegExMatch> match = search(p_subject, p_offset, p_end);
while (match.is_valid()) {
- if (last_end == match->get_end(0))
+ if (last_end == match->get_end(0)) {
break;
+ }
result.push_back(match);
last_end = match->get_end(0);
match = search(p_subject, match->get_end(0), p_end);
@@ -354,7 +273,6 @@ Array RegEx::search_all(const String &p_subject, int p_offset, int p_end) const
}
String RegEx::sub(const String &p_subject, const String &p_replacement, bool p_all, int p_offset, int p_end) const {
-
ERR_FAIL_COND_V(!is_valid(), String());
// safety_zone is the number of chars we allocate in addition to the number of chars expected in order to
@@ -364,83 +282,55 @@ String RegEx::sub(const String &p_subject, const String &p_replacement, bool p_a
const int safety_zone = 1;
PCRE2_SIZE olength = p_subject.length() + 1; // space for output string and one terminating \0 character
- Vector<CharType> output;
+ Vector<char32_t> output;
output.resize(olength + safety_zone);
uint32_t flags = PCRE2_SUBSTITUTE_OVERFLOW_LENGTH;
- if (p_all)
+ if (p_all) {
flags |= PCRE2_SUBSTITUTE_GLOBAL;
+ }
PCRE2_SIZE length = p_subject.length();
- if (p_end >= 0 && (uint32_t)p_end < length)
+ if (p_end >= 0 && (uint32_t)p_end < length) {
length = p_end;
+ }
- if (sizeof(CharType) == 2) {
-
- pcre2_code_16 *c = (pcre2_code_16 *)code;
- pcre2_general_context_16 *gctx = (pcre2_general_context_16 *)general_ctx;
- pcre2_match_context_16 *mctx = pcre2_match_context_create_16(gctx);
- PCRE2_SPTR16 s = (PCRE2_SPTR16)p_subject.c_str();
- PCRE2_SPTR16 r = (PCRE2_SPTR16)p_replacement.c_str();
- PCRE2_UCHAR16 *o = (PCRE2_UCHAR16 *)output.ptrw();
-
- pcre2_match_data_16 *match = pcre2_match_data_create_from_pattern_16(c, gctx);
-
- int res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
-
- if (res == PCRE2_ERROR_NOMEMORY) {
- output.resize(olength + safety_zone);
- o = (PCRE2_UCHAR16 *)output.ptrw();
- res = pcre2_substitute_16(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
- }
-
- pcre2_match_data_free_16(match);
- pcre2_match_context_free_16(mctx);
-
- if (res < 0)
- return String();
-
- } else {
+ pcre2_code_32 *c = (pcre2_code_32 *)code;
+ pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
+ pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
+ PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.get_data();
+ PCRE2_SPTR32 r = (PCRE2_SPTR32)p_replacement.get_data();
+ PCRE2_UCHAR32 *o = (PCRE2_UCHAR32 *)output.ptrw();
- pcre2_code_32 *c = (pcre2_code_32 *)code;
- pcre2_general_context_32 *gctx = (pcre2_general_context_32 *)general_ctx;
- pcre2_match_context_32 *mctx = pcre2_match_context_create_32(gctx);
- PCRE2_SPTR32 s = (PCRE2_SPTR32)p_subject.c_str();
- PCRE2_SPTR32 r = (PCRE2_SPTR32)p_replacement.c_str();
- PCRE2_UCHAR32 *o = (PCRE2_UCHAR32 *)output.ptrw();
+ pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
- pcre2_match_data_32 *match = pcre2_match_data_create_from_pattern_32(c, gctx);
+ int res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
- int res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
+ if (res == PCRE2_ERROR_NOMEMORY) {
+ output.resize(olength + safety_zone);
+ o = (PCRE2_UCHAR32 *)output.ptrw();
+ res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
+ }
- if (res == PCRE2_ERROR_NOMEMORY) {
- output.resize(olength + safety_zone);
- o = (PCRE2_UCHAR32 *)output.ptrw();
- res = pcre2_substitute_32(c, s, length, p_offset, flags, match, mctx, r, p_replacement.length(), o, &olength);
- }
+ pcre2_match_data_free_32(match);
+ pcre2_match_context_free_32(mctx);
- pcre2_match_data_free_32(match);
- pcre2_match_context_free_32(mctx);
-
- if (res < 0)
- return String();
+ if (res < 0) {
+ return String();
}
return String(output.ptr(), olength);
}
bool RegEx::is_valid() const {
-
return (code != nullptr);
}
String RegEx::get_pattern() const {
-
return pattern;
}
int RegEx::get_group_count() const {
-
ERR_FAIL_COND_V(!is_valid(), 0);
uint32_t count;
@@ -451,13 +341,12 @@ int RegEx::get_group_count() const {
}
Array RegEx::get_names() const {
-
Array result;
ERR_FAIL_COND_V(!is_valid(), result);
uint32_t count;
- const CharType *table;
+ const char32_t *table;
uint32_t entry_size;
_pattern_info(PCRE2_INFO_NAMECOUNT, &count);
@@ -465,7 +354,6 @@ Array RegEx::get_names() const {
_pattern_info(PCRE2_INFO_NAMEENTRYSIZE, &entry_size);
for (uint32_t i = 0; i < count; i++) {
-
String name = &table[i * entry_size + 1];
if (result.find(name) < 0) {
result.append(name);
@@ -476,50 +364,24 @@ Array RegEx::get_names() const {
}
RegEx::RegEx() {
-
- if (sizeof(CharType) == 2) {
-
- general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, nullptr);
-
- } else {
-
- general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
- }
+ general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
code = nullptr;
}
RegEx::RegEx(const String &p_pattern) {
-
- if (sizeof(CharType) == 2) {
-
- general_ctx = pcre2_general_context_create_16(&_regex_malloc, &_regex_free, nullptr);
-
- } else {
-
- general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
- }
+ general_ctx = pcre2_general_context_create_32(&_regex_malloc, &_regex_free, nullptr);
code = nullptr;
compile(p_pattern);
}
RegEx::~RegEx() {
-
- if (sizeof(CharType) == 2) {
-
- if (code)
- pcre2_code_free_16((pcre2_code_16 *)code);
- pcre2_general_context_free_16((pcre2_general_context_16 *)general_ctx);
-
- } else {
-
- if (code)
- pcre2_code_free_32((pcre2_code_32 *)code);
- pcre2_general_context_free_32((pcre2_general_context_32 *)general_ctx);
+ if (code) {
+ pcre2_code_free_32((pcre2_code_32 *)code);
}
+ pcre2_general_context_free_32((pcre2_general_context_32 *)general_ctx);
}
void RegEx::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("clear"), &RegEx::clear);
ClassDB::bind_method(D_METHOD("compile", "pattern"), &RegEx::compile);
ClassDB::bind_method(D_METHOD("search", "subject", "offset", "end"), &RegEx::search, DEFVAL(0), DEFVAL(-1));
diff --git a/modules/regex/regex.h b/modules/regex/regex.h
index a342c17c78..46505855d7 100644
--- a/modules/regex/regex.h
+++ b/modules/regex/regex.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,15 +31,14 @@
#ifndef REGEX_H
#define REGEX_H
-#include "core/array.h"
-#include "core/dictionary.h"
-#include "core/map.h"
-#include "core/reference.h"
-#include "core/ustring.h"
-#include "core/vector.h"
+#include "core/object/reference.h"
+#include "core/string/ustring.h"
+#include "core/templates/map.h"
+#include "core/templates/vector.h"
+#include "core/variant/array.h"
+#include "core/variant/dictionary.h"
class RegExMatch : public Reference {
-
GDCLASS(RegExMatch, Reference);
struct Range {
@@ -70,7 +69,6 @@ public:
};
class RegEx : public Reference {
-
GDCLASS(RegEx, Reference);
void *general_ctx;
@@ -85,7 +83,6 @@ protected:
public:
void clear();
Error compile(const String &p_pattern);
- void _init(const String &p_pattern = "");
Ref<RegExMatch> search(const String &p_subject, int p_offset = 0, int p_end = -1) const;
Array search_all(const String &p_subject, int p_offset = 0, int p_end = -1) const;
diff --git a/modules/regex/register_types.cpp b/modules/regex/register_types.cpp
index 77b19fa8f0..82f3eaf707 100644
--- a/modules/regex/register_types.cpp
+++ b/modules/regex/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,11 +29,10 @@
/*************************************************************************/
#include "register_types.h"
-#include "core/class_db.h"
+#include "core/object/class_db.h"
#include "regex.h"
void register_regex_types() {
-
ClassDB::register_class<RegExMatch>();
ClassDB::register_class<RegEx>();
}
diff --git a/modules/regex/register_types.h b/modules/regex/register_types.h
index cf377cdf5f..fe94cde954 100644
--- a/modules/regex/register_types.h
+++ b/modules/regex/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/regex/tests/test_regex.h b/modules/regex/tests/test_regex.h
new file mode 100644
index 0000000000..c2d303b435
--- /dev/null
+++ b/modules/regex/tests/test_regex.h
@@ -0,0 +1,164 @@
+/*************************************************************************/
+/* test_regex.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEST_REGEX_H
+#define TEST_REGEX_H
+
+#include "core/string/ustring.h"
+#include "modules/regex/regex.h"
+
+#include "tests/test_macros.h"
+
+namespace TestRegEx {
+
+TEST_CASE("[RegEx] Initialization") {
+ const String pattern = "(?<vowel>[aeiou])";
+
+ RegEx re1(pattern);
+ CHECK(re1.is_valid());
+ CHECK(re1.get_pattern() == pattern);
+ CHECK(re1.get_group_count() == 1);
+
+ Array names = re1.get_names();
+ CHECK(names.size() == 1);
+ CHECK(names[0] == "vowel");
+
+ RegEx re2;
+ CHECK(re2.is_valid() == false);
+ CHECK(re2.compile(pattern) == OK);
+ CHECK(re2.is_valid());
+
+ CHECK(re1.get_pattern() == re2.get_pattern());
+ CHECK(re1.get_group_count() == re2.get_group_count());
+
+ names = re2.get_names();
+ CHECK(names.size() == 1);
+ CHECK(names[0] == "vowel");
+}
+
+TEST_CASE("[RegEx] Clearing") {
+ RegEx re("Godot");
+ REQUIRE(re.is_valid());
+ re.clear();
+ CHECK(re.is_valid() == false);
+}
+
+TEST_CASE("[RegEx] Searching") {
+ const String s = "Searching";
+ const String vowels = "[aeiou]{1,2}";
+ const String numerics = "\\d";
+
+ RegEx re(vowels);
+ REQUIRE(re.is_valid());
+
+ Ref<RegExMatch> match = re.search(s);
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == "ea");
+
+ match = re.search(s, 2, 4);
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == "a");
+
+ const Array all_results = re.search_all(s);
+ CHECK(all_results.size() == 2);
+ match = all_results[0];
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == "ea");
+ match = all_results[1];
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == "i");
+
+ CHECK(re.compile(numerics) == OK);
+ CHECK(re.is_valid());
+ CHECK(re.search(s) == nullptr);
+ CHECK(re.search_all(s).size() == 0);
+}
+
+TEST_CASE("[RegEx] Substitution") {
+ String s = "Double all the vowels.";
+
+ RegEx re("(?<vowel>[aeiou])");
+ REQUIRE(re.is_valid());
+ CHECK(re.sub(s, "$0$vowel", true) == "Doouublee aall thee vooweels.");
+}
+
+TEST_CASE("[RegEx] Uninitialized use") {
+ const String s = "Godot";
+
+ RegEx re;
+ ERR_PRINT_OFF;
+ CHECK(re.search(s) == nullptr);
+ CHECK(re.search_all(s).size() == 0);
+ CHECK(re.sub(s, "") == "");
+ CHECK(re.get_group_count() == 0);
+ CHECK(re.get_names().size() == 0);
+ ERR_PRINT_ON
+}
+
+TEST_CASE("[RegEx] Empty Pattern") {
+ const String s = "Godot";
+
+ RegEx re;
+ CHECK(re.compile("") == OK);
+ CHECK(re.is_valid());
+}
+
+TEST_CASE("[RegEx] Invalid offset") {
+ const String s = "Godot";
+
+ RegEx re("o");
+ REQUIRE(re.is_valid());
+ CHECK(re.search(s, -1) == nullptr);
+ CHECK(re.search_all(s, -1).size() == 0);
+ CHECK(re.sub(s, "", true, -1) == "");
+}
+
+TEST_CASE("[RegEx] Invalid end position") {
+ const String s = "Godot";
+
+ RegEx re("o");
+ REQUIRE(re.is_valid());
+ Ref<RegExMatch> match = re.search(s, 0, 10);
+ CHECK(match->get_string(0) == "o");
+
+ const Array all_results = re.search_all(s, 0, 10);
+ CHECK(all_results.size() == 2);
+ match = all_results[0];
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == String("o"));
+ match = all_results[1];
+ REQUIRE(match != nullptr);
+ CHECK(match->get_string(0) == String("o"));
+
+ CHECK(re.sub(s, "", true, 0, 10) == "Gdt");
+}
+} // namespace TestRegEx
+
+#endif // TEST_REGEX_H
diff --git a/modules/register_module_types.h b/modules/register_module_types.h
index acd9fc7c97..2cff8c54c4 100644
--- a/modules/register_module_types.h
+++ b/modules/register_module_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/squish/SCsub b/modules/squish/SCsub
index b31032403f..c9e29911d8 100644
--- a/modules/squish/SCsub
+++ b/modules/squish/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_squish = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_squish"]:
thirdparty_dir = "#thirdparty/squish/"
thirdparty_sources = [
@@ -26,7 +29,16 @@ if env["builtin_squish"]:
env_thirdparty = env_squish.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_squish.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_squish.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp
index bb77f68590..cce08034df 100644
--- a/modules/squish/image_compress_squish.cpp
+++ b/modules/squish/image_compress_squish.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -78,21 +78,21 @@ void image_decompress_squish(Image *p_image) {
}
void image_compress_squish(Image *p_image, float p_lossy_quality, Image::UsedChannels p_channels) {
-
- if (p_image->get_format() >= Image::FORMAT_DXT1)
+ if (p_image->get_format() >= Image::FORMAT_DXT1) {
return; //do not compress, already compressed
+ }
int w = p_image->get_width();
int h = p_image->get_height();
if (p_image->get_format() <= Image::FORMAT_RGBA8) {
-
int squish_comp = squish::kColourRangeFit;
- if (p_lossy_quality > 0.85)
+ if (p_lossy_quality > 0.85) {
squish_comp = squish::kColourIterativeClusterFit;
- else if (p_lossy_quality > 0.75)
+ } else if (p_lossy_quality > 0.75) {
squish_comp = squish::kColourClusterFit;
+ }
Image::Format target_format = Image::FORMAT_RGBA8;
@@ -100,32 +100,26 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::UsedCha
switch (p_channels) {
case Image::USED_CHANNELS_L: {
-
target_format = Image::FORMAT_DXT1;
squish_comp |= squish::kDxt1;
} break;
case Image::USED_CHANNELS_LA: {
-
target_format = Image::FORMAT_DXT5;
squish_comp |= squish::kDxt5;
} break;
case Image::USED_CHANNELS_R: {
-
target_format = Image::FORMAT_RGTC_R;
squish_comp |= squish::kBc4;
} break;
case Image::USED_CHANNELS_RG: {
-
target_format = Image::FORMAT_RGTC_RG;
squish_comp |= squish::kBc5;
} break;
case Image::USED_CHANNELS_RGB: {
-
target_format = Image::FORMAT_DXT1;
squish_comp |= squish::kDxt1;
} break;
case Image::USED_CHANNELS_RGBA: {
-
//TODO, should convert both, then measure which one does a better job
target_format = Image::FORMAT_DXT5;
squish_comp |= squish::kDxt5;
@@ -149,7 +143,6 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::UsedCha
int dst_ofs = 0;
for (int i = 0; i <= mm_count; i++) {
-
int bw = w % 4 != 0 ? w + (4 - w % 4) : w;
int bh = h % 4 != 0 ? h + (4 - h % 4) : h;
diff --git a/modules/squish/image_compress_squish.h b/modules/squish/image_compress_squish.h
index 19e6d57474..301d30fcf1 100644
--- a/modules/squish/image_compress_squish.h
+++ b/modules/squish/image_compress_squish.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,7 @@
#ifndef IMAGE_COMPRESS_SQUISH_H
#define IMAGE_COMPRESS_SQUISH_H
-#include "core/image.h"
+#include "core/io/image.h"
void image_compress_squish(Image *p_image, float p_lossy_quality, Image::UsedChannels p_channels);
void image_decompress_squish(Image *p_image);
diff --git a/modules/squish/register_types.cpp b/modules/squish/register_types.cpp
index 2a0cf82b56..451e9d8e93 100644
--- a/modules/squish/register_types.cpp
+++ b/modules/squish/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,6 @@
#include "image_compress_squish.h"
void register_squish_types() {
-
Image::set_compress_bc_func(image_compress_squish);
Image::_image_decompress_bc = image_decompress_squish;
}
diff --git a/modules/squish/register_types.h b/modules/squish/register_types.h
index ab56c54d4a..0f87d64333 100644
--- a/modules/squish/register_types.h
+++ b/modules/squish/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/stb_vorbis/SCsub b/modules/stb_vorbis/SCsub
index 266c87c802..8fddb23dc8 100644
--- a/modules/stb_vorbis/SCsub
+++ b/modules/stb_vorbis/SCsub
@@ -6,11 +6,22 @@ Import("env_modules")
env_stb_vorbis = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
thirdparty_sources = ["#thirdparty/misc/stb_vorbis.c"]
env_thirdparty = env_stb_vorbis.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_stb_vorbis.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_stb_vorbis.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
index 9609c234ec..4b2be47e74 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "core/os/file_access.h"
void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
-
ERR_FAIL_COND(!active);
int todo = p_frames;
@@ -76,12 +75,10 @@ void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_fra
}
float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() {
-
return vorbis_stream->sample_rate;
}
void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) {
-
active = true;
seek(p_from_pos);
loops = 0;
@@ -89,27 +86,25 @@ void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) {
}
void AudioStreamPlaybackOGGVorbis::stop() {
-
active = false;
}
-bool AudioStreamPlaybackOGGVorbis::is_playing() const {
+bool AudioStreamPlaybackOGGVorbis::is_playing() const {
return active;
}
int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
-
return loops;
}
float AudioStreamPlaybackOGGVorbis::get_playback_position() const {
-
return float(frames_mixed) / vorbis_stream->sample_rate;
}
-void AudioStreamPlaybackOGGVorbis::seek(float p_time) {
- if (!active)
+void AudioStreamPlaybackOGGVorbis::seek(float p_time) {
+ if (!active) {
return;
+ }
if (p_time >= vorbis_stream->get_length()) {
p_time = 0;
@@ -127,10 +122,12 @@ AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {
}
Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
-
Ref<AudioStreamPlaybackOGGVorbis> ovs;
- ERR_FAIL_COND_V(data == nullptr, ovs);
+ ERR_FAIL_COND_V_MSG(data == nullptr, ovs,
+ "This AudioStreamOGGVorbis does not have an audio file assigned "
+ "to it. AudioStreamOGGVorbis should not be created from the "
+ "inspector or with `.new()`. Instead, load an audio file.");
ovs.instance();
ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this);
@@ -142,7 +139,6 @@ Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
int error;
ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc);
if (!ovs->ogg_stream) {
-
memfree(ovs->ogg_alloc.alloc_buffer);
ovs->ogg_alloc.alloc_buffer = nullptr;
ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>());
@@ -152,7 +148,6 @@ Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
}
String AudioStreamOGGVorbis::get_stream_name() const {
-
return ""; //return stream_name;
}
@@ -165,18 +160,18 @@ void AudioStreamOGGVorbis::clear_data() {
}
void AudioStreamOGGVorbis::set_data(const Vector<uint8_t> &p_data) {
-
int src_data_len = p_data.size();
-#define MAX_TEST_MEM (1 << 20)
-
uint32_t alloc_try = 1024;
Vector<char> alloc_mem;
char *w;
stb_vorbis *ogg_stream = nullptr;
stb_vorbis_alloc ogg_alloc;
- while (alloc_try < MAX_TEST_MEM) {
+ // Vorbis comments may be up to UINT32_MAX, but that's arguably pretty rare.
+ // Let's go with 2^30 so we don't risk going out of bounds.
+ const uint32_t MAX_TEST_MEM = 1 << 30;
+ while (alloc_try < MAX_TEST_MEM) {
alloc_mem.resize(alloc_try);
w = alloc_mem.ptrw();
@@ -189,10 +184,8 @@ void AudioStreamOGGVorbis::set_data(const Vector<uint8_t> &p_data) {
ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar, src_data_len, &error, &ogg_alloc);
if (!ogg_stream && error == VORBIS_outofmem) {
-
alloc_try *= 2;
} else {
-
ERR_FAIL_COND(alloc_try == MAX_TEST_MEM);
ERR_FAIL_COND(ogg_stream == nullptr);
@@ -217,10 +210,11 @@ void AudioStreamOGGVorbis::set_data(const Vector<uint8_t> &p_data) {
break;
}
}
+
+ ERR_FAIL_COND_MSG(alloc_try == MAX_TEST_MEM, vformat("Couldn't set vorbis data even with an alloc buffer of %d bytes, report bug.", MAX_TEST_MEM));
}
Vector<uint8_t> AudioStreamOGGVorbis::get_data() const {
-
Vector<uint8_t> vdata;
if (data_len && data) {
@@ -239,7 +233,6 @@ void AudioStreamOGGVorbis::set_loop(bool p_enable) {
}
bool AudioStreamOGGVorbis::has_loop() const {
-
return loop;
}
@@ -252,12 +245,10 @@ float AudioStreamOGGVorbis::get_loop_offset() const {
}
float AudioStreamOGGVorbis::get_length() const {
-
return length;
}
void AudioStreamOGGVorbis::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data);
ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data);
@@ -273,7 +264,6 @@ void AudioStreamOGGVorbis::_bind_methods() {
}
AudioStreamOGGVorbis::AudioStreamOGGVorbis() {
-
data = nullptr;
data_len = 0;
length = 0;
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
index f296e8c19f..efc8fc6c27 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -39,7 +39,6 @@
class AudioStreamOGGVorbis;
class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled {
-
GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled);
stb_vorbis *ogg_stream;
@@ -53,25 +52,24 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled {
Ref<AudioStreamOGGVorbis> vorbis_stream;
protected:
- virtual void _mix_internal(AudioFrame *p_buffer, int p_frames);
- virtual float get_stream_sampling_rate();
+ virtual void _mix_internal(AudioFrame *p_buffer, int p_frames) override;
+ virtual float get_stream_sampling_rate() override;
public:
- virtual void start(float p_from_pos = 0.0);
- virtual void stop();
- virtual bool is_playing() const;
+ virtual void start(float p_from_pos = 0.0) override;
+ virtual void stop() override;
+ virtual bool is_playing() const override;
- virtual int get_loop_count() const; //times it looped
+ virtual int get_loop_count() const override; //times it looped
- virtual float get_playback_position() const;
- virtual void seek(float p_time);
+ virtual float get_playback_position() const override;
+ virtual void seek(float p_time) override;
AudioStreamPlaybackOGGVorbis() {}
~AudioStreamPlaybackOGGVorbis();
};
class AudioStreamOGGVorbis : public AudioStream {
-
GDCLASS(AudioStreamOGGVorbis, AudioStream);
OBJ_SAVE_TYPE(AudioStream); // Saves derived classes with common type so they can be interchanged.
RES_BASE_EXTENSION("oggstr");
@@ -99,13 +97,13 @@ public:
void set_loop_offset(float p_seconds);
float get_loop_offset() const;
- virtual Ref<AudioStreamPlayback> instance_playback();
- virtual String get_stream_name() const;
+ virtual Ref<AudioStreamPlayback> instance_playback() override;
+ virtual String get_stream_name() const override;
void set_data(const Vector<uint8_t> &p_data);
Vector<uint8_t> get_data() const;
- virtual float get_length() const; //if supported, otherwise return 0
+ virtual float get_length() const override; //if supported, otherwise return 0
AudioStreamOGGVorbis();
virtual ~AudioStreamOGGVorbis();
diff --git a/modules/stb_vorbis/register_types.cpp b/modules/stb_vorbis/register_types.cpp
index ac2612bd6a..6f7eb53bc8 100644
--- a/modules/stb_vorbis/register_types.cpp
+++ b/modules/stb_vorbis/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,12 +33,11 @@
#include "audio_stream_ogg_vorbis.h"
#ifdef TOOLS_ENABLED
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "resource_importer_ogg_vorbis.h"
#endif
void register_stb_vorbis_types() {
-
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
Ref<ResourceImporterOGGVorbis> ogg_import;
diff --git a/modules/stb_vorbis/register_types.h b/modules/stb_vorbis/register_types.h
index f5a1dd31bc..d36d87606c 100644
--- a/modules/stb_vorbis/register_types.h
+++ b/modules/stb_vorbis/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
index 13d96541e3..ec1c30783a 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,16 +35,14 @@
#include "scene/resources/texture.h"
String ResourceImporterOGGVorbis::get_importer_name() const {
-
return "ogg_vorbis";
}
String ResourceImporterOGGVorbis::get_visible_name() const {
-
return "OGGVorbis";
}
-void ResourceImporterOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const {
+void ResourceImporterOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("ogg");
}
@@ -53,31 +51,27 @@ String ResourceImporterOGGVorbis::get_save_extension() const {
}
String ResourceImporterOGGVorbis::get_resource_type() const {
-
return "AudioStreamOGGVorbis";
}
bool ResourceImporterOGGVorbis::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
-
return true;
}
int ResourceImporterOGGVorbis::get_preset_count() const {
return 0;
}
-String ResourceImporterOGGVorbis::get_preset_name(int p_idx) const {
+String ResourceImporterOGGVorbis::get_preset_name(int p_idx) const {
return String();
}
void ResourceImporterOGGVorbis::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-
r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "loop"), true));
r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "loop_offset"), 0));
}
Error ResourceImporterOGGVorbis::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
-
bool loop = p_options["loop"];
float loop_offset = p_options["loop_offset"];
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.h b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
index 8d6f71a456..60fe3381fb 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.h
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -38,19 +38,19 @@ class ResourceImporterOGGVorbis : public ResourceImporter {
GDCLASS(ResourceImporterOGGVorbis, ResourceImporter);
public:
- virtual String get_importer_name() const;
- virtual String get_visible_name() const;
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual String get_save_extension() const;
- virtual String get_resource_type() const;
+ virtual String get_importer_name() const override;
+ virtual String get_visible_name() const override;
+ virtual void get_recognized_extensions(List<String> *p_extensions) const override;
+ virtual String get_save_extension() const override;
+ virtual String get_resource_type() const override;
- virtual int get_preset_count() const;
- virtual String get_preset_name(int p_idx) const;
+ virtual int get_preset_count() const override;
+ virtual String get_preset_name(int p_idx) const override;
- virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const;
- virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
+ virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const override;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const override;
- virtual Error import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files = nullptr, Variant *r_metadata = nullptr);
+ virtual Error import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files = nullptr, Variant *r_metadata = nullptr) override;
ResourceImporterOGGVorbis();
};
diff --git a/modules/svg/SCsub b/modules/svg/SCsub
index 0bfba34fe5..c7228a8d0b 100644
--- a/modules/svg/SCsub
+++ b/modules/svg/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_svg = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
thirdparty_dir = "#thirdparty/nanosvg/"
thirdparty_sources = [
"nanosvg.cc",
@@ -16,7 +19,15 @@ env_svg.Prepend(CPPPATH=[thirdparty_dir])
env_thirdparty = env_svg.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_svg.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_svg.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp
index 3c2784f8de..6ce3e4b4b3 100644
--- a/modules/svg/image_loader_svg.cpp
+++ b/modules/svg/image_loader_svg.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,6 +40,7 @@ void SVGRasterizer::rasterize(NSVGimage *p_image, float p_tx, float p_ty, float
SVGRasterizer::SVGRasterizer() {
rasterizer = nsvgCreateRasterizer();
}
+
SVGRasterizer::~SVGRasterizer() {
nsvgDeleteRasterizer(rasterizer);
}
@@ -47,7 +48,6 @@ SVGRasterizer::~SVGRasterizer() {
SVGRasterizer ImageLoaderSVG::rasterizer;
inline void change_nsvg_paint_color(NSVGpaint *p_paint, const uint32_t p_old, const uint32_t p_new) {
-
if (p_paint->type == NSVG_PAINT_COLOR) {
if (p_paint->color << 8 == p_old << 8) {
p_paint->color = (p_paint->color & 0xFF000000) | (p_new & 0x00FFFFFF);
@@ -64,9 +64,7 @@ inline void change_nsvg_paint_color(NSVGpaint *p_paint, const uint32_t p_old, co
}
void ImageLoaderSVG::_convert_colors(NSVGimage *p_svg_image) {
-
for (NSVGshape *shape = p_svg_image->shapes; shape != nullptr; shape = shape->next) {
-
for (int i = 0; i < replace_colors.old_colors.size(); i++) {
change_nsvg_paint_color(&(shape->stroke), replace_colors.old_colors[i], replace_colors.new_colors[i]);
change_nsvg_paint_color(&(shape->fill), replace_colors.old_colors[i], replace_colors.new_colors[i]);
@@ -75,7 +73,6 @@ void ImageLoaderSVG::_convert_colors(NSVGimage *p_svg_image) {
}
void ImageLoaderSVG::set_convert_colors(Dictionary *p_replace_color) {
-
if (p_replace_color) {
Dictionary replace_color = *p_replace_color;
for (int i = 0; i < replace_color.keys().size(); i++) {
@@ -133,7 +130,6 @@ Error ImageLoaderSVG::_create_image(Ref<Image> p_image, const Vector<uint8_t> *p
}
Error ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, const char *p_svg_str, float p_scale, bool upsample, bool convert_colors) {
-
size_t str_len = strlen(p_svg_str);
Vector<uint8_t> src_data;
src_data.resize(str_len + 1);
@@ -144,7 +140,6 @@ Error ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, const char *p
}
Error ImageLoaderSVG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
uint32_t size = f->get_len();
Vector<uint8_t> src_image;
src_image.resize(size + 1);
@@ -156,7 +151,6 @@ Error ImageLoaderSVG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
}
void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("svg");
p_extensions->push_back("svgz");
}
diff --git a/modules/svg/image_loader_svg.h b/modules/svg/image_loader_svg.h
index 0fa4a0fdf4..e64175b172 100644
--- a/modules/svg/image_loader_svg.h
+++ b/modules/svg/image_loader_svg.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,7 +32,7 @@
#define IMAGE_LOADER_SVG_H
#include "core/io/image_loader.h"
-#include "core/ustring.h"
+#include "core/string/ustring.h"
/**
@author Daniel Ramirez <djrmuv@gmail.com>
@@ -43,7 +43,6 @@ struct NSVGrasterizer;
struct NSVGimage;
class SVGRasterizer {
-
NSVGrasterizer *rasterizer;
public:
diff --git a/modules/svg/register_types.cpp b/modules/svg/register_types.cpp
index 37875313aa..1a611184d2 100644
--- a/modules/svg/register_types.cpp
+++ b/modules/svg/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
static ImageLoaderSVG *image_loader_svg = nullptr;
void register_svg_types() {
-
image_loader_svg = memnew(ImageLoaderSVG);
ImageLoader::add_image_format_loader(image_loader_svg);
}
void unregister_svg_types() {
-
memdelete(image_loader_svg);
}
diff --git a/modules/svg/register_types.h b/modules/svg/register_types.h
index a3d914e0cb..106ac9056f 100644
--- a/modules/svg/register_types.h
+++ b/modules/svg/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsub
new file mode 100644
index 0000000000..3589c8546d
--- /dev/null
+++ b/modules/text_server_adv/SCsub
@@ -0,0 +1,501 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_text_server_adv = env_modules.Clone()
+
+
+def make_icu_data(target, source, env):
+ import os
+
+ dst = target[0].srcnode().abspath
+
+ g = open(dst, "w", encoding="utf-8")
+
+ g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
+ g.write("/* (C) 2016 and later: Unicode, Inc. and others. */\n")
+ g.write("/* License & terms of use: http://www.unicode.org/copyright.html */\n")
+ g.write("#ifndef _ICU_DATA_H\n")
+ g.write("#define _ICU_DATA_H\n")
+ g.write('#include "unicode/utypes.h"\n')
+ g.write('#include "unicode/udata.h"\n')
+ g.write('#include "unicode/uversion.h"\n')
+
+ f = open(source[0].srcnode().abspath, "rb")
+ buf = f.read()
+ import os.path
+
+ g.write('extern "C" U_EXPORT const size_t U_ICUDATA_SIZE = ' + str(len(buf)) + ";\n")
+ g.write('extern "C" U_EXPORT const unsigned char U_ICUDATA_ENTRY_POINT[] = {\n')
+ for i in range(len(buf)):
+ g.write("\t" + str(buf[i]) + ",\n")
+
+ g.write("};\n")
+ g.write("#endif")
+
+
+# Thirdparty source files
+
+thirdparty_obj = []
+
+if env["builtin_harfbuzz"]:
+ env_harfbuzz = env_modules.Clone()
+ env_harfbuzz.disable_warnings()
+
+ thirdparty_dir = "#thirdparty/harfbuzz/"
+ thirdparty_sources = [
+ "src/hb-aat-layout.cc",
+ "src/hb-aat-map.cc",
+ "src/hb-blob.cc",
+ "src/hb-buffer-serialize.cc",
+ "src/hb-buffer.cc",
+ "src/hb-common.cc",
+ #'src/hb-coretext.cc',
+ #'src/hb-directwrite.cc',
+ "src/hb-draw.cc",
+ "src/hb-face.cc",
+ "src/hb-fallback-shape.cc",
+ "src/hb-font.cc",
+ "src/hb-ft.cc",
+ #'src/hb-gdi.cc',
+ #'src/hb-glib.cc',
+ #'src/hb-gobject-structs.cc',
+ "src/hb-graphite2.cc",
+ "src/hb-icu.cc",
+ "src/hb-map.cc",
+ "src/hb-number.cc",
+ "src/hb-ot-cff1-table.cc",
+ "src/hb-ot-cff2-table.cc",
+ "src/hb-ot-color.cc",
+ "src/hb-ot-face.cc",
+ "src/hb-ot-font.cc",
+ "src/hb-ot-layout.cc",
+ "src/hb-ot-map.cc",
+ "src/hb-ot-math.cc",
+ "src/hb-ot-meta.cc",
+ "src/hb-ot-metrics.cc",
+ "src/hb-ot-name.cc",
+ "src/hb-ot-shape-complex-arabic.cc",
+ "src/hb-ot-shape-complex-default.cc",
+ "src/hb-ot-shape-complex-hangul.cc",
+ "src/hb-ot-shape-complex-hebrew.cc",
+ "src/hb-ot-shape-complex-indic-table.cc",
+ "src/hb-ot-shape-complex-indic.cc",
+ "src/hb-ot-shape-complex-khmer.cc",
+ "src/hb-ot-shape-complex-myanmar.cc",
+ "src/hb-ot-shape-complex-thai.cc",
+ "src/hb-ot-shape-complex-use-table.cc",
+ "src/hb-ot-shape-complex-use.cc",
+ "src/hb-ot-shape-complex-vowel-constraints.cc",
+ "src/hb-ot-shape-fallback.cc",
+ "src/hb-ot-shape-normalize.cc",
+ "src/hb-ot-shape.cc",
+ "src/hb-ot-tag.cc",
+ "src/hb-ot-var.cc",
+ "src/hb-set.cc",
+ "src/hb-shape-plan.cc",
+ "src/hb-shape.cc",
+ "src/hb-shaper.cc",
+ "src/hb-static.cc",
+ "src/hb-style.cc",
+ "src/hb-subset-cff-common.cc",
+ "src/hb-subset-cff1.cc",
+ "src/hb-subset-cff2.cc",
+ "src/hb-subset-input.cc",
+ "src/hb-subset-plan.cc",
+ "src/hb-subset.cc",
+ "src/hb-ucd.cc",
+ "src/hb-unicode.cc",
+ #'src/hb-uniscribe.cc'
+ ]
+ thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+ env_harfbuzz.Append(
+ CPPPATH=[
+ "#thirdparty/harfbuzz/src",
+ "#thirdparty/freetype/include",
+ "#thirdparty/graphite/include",
+ "#thirdparty/icu4c/common/",
+ ]
+ )
+
+ if env["platform"] == "android" or env["platform"] == "linuxbsd" or env["platform"] == "server":
+ env_harfbuzz.Append(CCFLAGS=["-DHAVE_PTHREAD"])
+
+ if env["platform"] == "javascript":
+ if env["threads_enabled"]:
+ env_harfbuzz.Append(CCFLAGS=["-DHAVE_PTHREAD"])
+ else:
+ env_harfbuzz.Append(CCFLAGS=["-DHB_NO_MT"])
+
+ env_harfbuzz.Append(
+ CCFLAGS=[
+ "-DHAVE_ICU_BUILTIN",
+ "-DHAVE_ICU",
+ "-DHAVE_FREETYPE",
+ "-DHAVE_GRAPHITE2",
+ "-DGRAPHITE2_STATIC",
+ ]
+ )
+
+ lib = env_harfbuzz.add_library("harfbuzz_builtin", thirdparty_sources)
+ thirdparty_obj += lib
+
+ # Needs to be appended to arrive after libscene in the linker call,
+ # but we don't want it to arrive *after* system libs, so manual hack
+ # LIBS contains first SCons Library objects ("SCons.Node.FS.File object")
+ # and then plain strings for system library. We insert between the two.
+ inserted = False
+ for idx, linklib in enumerate(env["LIBS"]):
+ if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object
+ env["LIBS"].insert(idx, lib)
+ inserted = True
+ break
+ if not inserted:
+ env.Append(LIBS=[lib])
+
+
+if env["builtin_graphite"]:
+ env_graphite = env_modules.Clone()
+ env_graphite.disable_warnings()
+
+ thirdparty_dir = "#thirdparty/graphite/"
+ thirdparty_sources = [
+ "src/gr_char_info.cpp",
+ "src/gr_face.cpp",
+ "src/gr_features.cpp",
+ "src/gr_font.cpp",
+ "src/gr_logging.cpp",
+ "src/gr_segment.cpp",
+ "src/gr_slot.cpp",
+ "src/CmapCache.cpp",
+ "src/Code.cpp",
+ "src/Collider.cpp",
+ "src/Decompressor.cpp",
+ "src/Face.cpp",
+ #'src/FileFace.cpp',
+ "src/FeatureMap.cpp",
+ "src/Font.cpp",
+ "src/GlyphCache.cpp",
+ "src/GlyphFace.cpp",
+ "src/Intervals.cpp",
+ "src/Justifier.cpp",
+ "src/NameTable.cpp",
+ "src/Pass.cpp",
+ "src/Position.cpp",
+ "src/Segment.cpp",
+ "src/Silf.cpp",
+ "src/Slot.cpp",
+ "src/Sparse.cpp",
+ "src/TtfUtil.cpp",
+ "src/UtfCodec.cpp",
+ "src/FileFace.cpp",
+ "src/json.cpp",
+ ]
+ if not env_graphite.msvc:
+ thirdparty_sources += ["src/direct_machine.cpp"]
+ else:
+ thirdparty_sources += ["src/call_machine.cpp"]
+
+ thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+ env_graphite.Append(CPPPATH=["#thirdparty/graphite/src", "#thirdparty/graphite/include"])
+ env_graphite.Append(
+ CCFLAGS=[
+ "-DGRAPHITE2_STATIC",
+ "-DGRAPHITE2_NTRACING",
+ "-DGRAPHITE2_NFILEFACE",
+ ]
+ )
+
+ lib = env_graphite.add_library("graphite_builtin", thirdparty_sources)
+ thirdparty_obj += lib
+
+ # Needs to be appended to arrive after libscene in the linker call,
+ # but we don't want it to arrive *after* system libs, so manual hack
+ # LIBS contains first SCons Library objects ("SCons.Node.FS.File object")
+ # and then plain strings for system library. We insert between the two.
+ inserted = False
+ for idx, linklib in enumerate(env["LIBS"]):
+ if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object
+ env["LIBS"].insert(idx, lib)
+ inserted = True
+ break
+ if not inserted:
+ env.Append(LIBS=[lib])
+
+
+if env["builtin_icu"]:
+ env_icu = env_modules.Clone()
+ env_icu.disable_warnings()
+
+ thirdparty_dir = "#thirdparty/icu4c/"
+ thirdparty_sources = [
+ "common/appendable.cpp",
+ "common/bmpset.cpp",
+ "common/brkeng.cpp",
+ "common/brkiter.cpp",
+ "common/bytesinkutil.cpp",
+ "common/bytestream.cpp",
+ "common/bytestrie.cpp",
+ "common/bytestriebuilder.cpp",
+ "common/bytestrieiterator.cpp",
+ "common/caniter.cpp",
+ "common/characterproperties.cpp",
+ "common/chariter.cpp",
+ "common/charstr.cpp",
+ "common/cmemory.cpp",
+ "common/cstr.cpp",
+ "common/cstring.cpp",
+ "common/cwchar.cpp",
+ "common/dictbe.cpp",
+ "common/dictionarydata.cpp",
+ "common/dtintrv.cpp",
+ "common/edits.cpp",
+ "common/errorcode.cpp",
+ "common/filteredbrk.cpp",
+ "common/filterednormalizer2.cpp",
+ "common/icudataver.cpp",
+ "common/icuplug.cpp",
+ "common/loadednormalizer2impl.cpp",
+ "common/localebuilder.cpp",
+ "common/localematcher.cpp",
+ "common/localeprioritylist.cpp",
+ "common/locavailable.cpp",
+ "common/locbased.cpp",
+ "common/locdispnames.cpp",
+ "common/locdistance.cpp",
+ "common/locdspnm.cpp",
+ "common/locid.cpp",
+ "common/loclikely.cpp",
+ "common/loclikelysubtags.cpp",
+ "common/locmap.cpp",
+ "common/locresdata.cpp",
+ "common/locutil.cpp",
+ "common/lsr.cpp",
+ "common/messagepattern.cpp",
+ "common/normalizer2.cpp",
+ "common/normalizer2impl.cpp",
+ "common/normlzr.cpp",
+ "common/parsepos.cpp",
+ "common/patternprops.cpp",
+ "common/pluralmap.cpp",
+ "common/propname.cpp",
+ "common/propsvec.cpp",
+ "common/punycode.cpp",
+ "common/putil.cpp",
+ "common/rbbi.cpp",
+ "common/rbbi_cache.cpp",
+ "common/rbbidata.cpp",
+ "common/rbbinode.cpp",
+ "common/rbbirb.cpp",
+ "common/rbbiscan.cpp",
+ "common/rbbisetb.cpp",
+ "common/rbbistbl.cpp",
+ "common/rbbitblb.cpp",
+ "common/resbund.cpp",
+ "common/resbund_cnv.cpp",
+ "common/resource.cpp",
+ "common/restrace.cpp",
+ "common/ruleiter.cpp",
+ "common/schriter.cpp",
+ "common/serv.cpp",
+ "common/servlk.cpp",
+ "common/servlkf.cpp",
+ "common/servls.cpp",
+ "common/servnotf.cpp",
+ "common/servrbf.cpp",
+ "common/servslkf.cpp",
+ "common/sharedobject.cpp",
+ "common/simpleformatter.cpp",
+ "common/static_unicode_sets.cpp",
+ "common/stringpiece.cpp",
+ "common/stringtriebuilder.cpp",
+ "common/uarrsort.cpp",
+ "common/ubidi.cpp",
+ "common/ubidi_props.cpp",
+ "common/ubidiln.cpp",
+ "common/ubiditransform.cpp",
+ "common/ubidiwrt.cpp",
+ "common/ubrk.cpp",
+ "common/ucase.cpp",
+ "common/ucasemap.cpp",
+ "common/ucasemap_titlecase_brkiter.cpp",
+ "common/ucat.cpp",
+ "common/uchar.cpp",
+ "common/ucharstrie.cpp",
+ "common/ucharstriebuilder.cpp",
+ "common/ucharstrieiterator.cpp",
+ "common/uchriter.cpp",
+ "common/ucln_cmn.cpp",
+ "common/ucmndata.cpp",
+ "common/ucnv.cpp",
+ "common/ucnv2022.cpp",
+ "common/ucnv_bld.cpp",
+ "common/ucnv_cb.cpp",
+ "common/ucnv_cnv.cpp",
+ "common/ucnv_ct.cpp",
+ "common/ucnv_err.cpp",
+ "common/ucnv_ext.cpp",
+ "common/ucnv_io.cpp",
+ "common/ucnv_lmb.cpp",
+ "common/ucnv_set.cpp",
+ "common/ucnv_u16.cpp",
+ "common/ucnv_u32.cpp",
+ "common/ucnv_u7.cpp",
+ "common/ucnv_u8.cpp",
+ "common/ucnvbocu.cpp",
+ "common/ucnvdisp.cpp",
+ "common/ucnvhz.cpp",
+ "common/ucnvisci.cpp",
+ "common/ucnvlat1.cpp",
+ "common/ucnvmbcs.cpp",
+ "common/ucnvscsu.cpp",
+ "common/ucnvsel.cpp",
+ "common/ucol_swp.cpp",
+ "common/ucptrie.cpp",
+ "common/ucurr.cpp",
+ "common/udata.cpp",
+ "common/udatamem.cpp",
+ "common/udataswp.cpp",
+ "common/uenum.cpp",
+ "common/uhash.cpp",
+ "common/uhash_us.cpp",
+ "common/uidna.cpp",
+ "common/uinit.cpp",
+ "common/uinvchar.cpp",
+ "common/uiter.cpp",
+ "common/ulist.cpp",
+ "common/uloc.cpp",
+ "common/uloc_keytype.cpp",
+ "common/uloc_tag.cpp",
+ "common/umapfile.cpp",
+ "common/umath.cpp",
+ "common/umutablecptrie.cpp",
+ "common/umutex.cpp",
+ "common/unames.cpp",
+ "common/unifiedcache.cpp",
+ "common/unifilt.cpp",
+ "common/unifunct.cpp",
+ "common/uniset.cpp",
+ "common/uniset_closure.cpp",
+ "common/uniset_props.cpp",
+ "common/unisetspan.cpp",
+ "common/unistr.cpp",
+ "common/unistr_case.cpp",
+ "common/unistr_case_locale.cpp",
+ "common/unistr_cnv.cpp",
+ "common/unistr_props.cpp",
+ "common/unistr_titlecase_brkiter.cpp",
+ "common/unorm.cpp",
+ "common/unormcmp.cpp",
+ "common/uobject.cpp",
+ "common/uprops.cpp",
+ "common/ures_cnv.cpp",
+ "common/uresbund.cpp",
+ "common/uresdata.cpp",
+ "common/usc_impl.cpp",
+ "common/uscript.cpp",
+ "common/uscript_props.cpp",
+ "common/uset.cpp",
+ "common/uset_props.cpp",
+ "common/usetiter.cpp",
+ # "common/ushape.cpp",
+ "common/usprep.cpp",
+ "common/ustack.cpp",
+ "common/ustr_cnv.cpp",
+ "common/ustr_titlecase_brkiter.cpp",
+ "common/ustr_wcs.cpp",
+ "common/ustrcase.cpp",
+ "common/ustrcase_locale.cpp",
+ "common/ustrenum.cpp",
+ "common/ustrfmt.cpp",
+ "common/ustring.cpp",
+ "common/ustrtrns.cpp",
+ "common/utext.cpp",
+ "common/utf_impl.cpp",
+ "common/util.cpp",
+ "common/util_props.cpp",
+ "common/utrace.cpp",
+ "common/utrie.cpp",
+ "common/utrie2.cpp",
+ "common/utrie2_builder.cpp",
+ "common/utrie_swap.cpp",
+ "common/uts46.cpp",
+ "common/utypes.cpp",
+ "common/uvector.cpp",
+ "common/uvectr32.cpp",
+ "common/uvectr64.cpp",
+ "common/wintz.cpp",
+ ]
+ thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+
+ icu_data_name = "icudt68l.dat"
+
+ if env_icu["tools"]:
+ env_icu.Depends("#thirdparty/icu4c/icudata.gen.h", "#thirdparty/icu4c/" + icu_data_name)
+ env_icu.Command("#thirdparty/icu4c/icudata.gen.h", "#thirdparty/icu4c/" + icu_data_name, make_icu_data)
+ else:
+ thirdparty_sources += ["icu_data/icudata_stub.cpp"]
+
+ env_icu.Append(CPPPATH=["#thirdparty/icu4c/common/"])
+ env_icu.Append(
+ CXXFLAGS=[
+ "-DU_STATIC_IMPLEMENTATION",
+ "-DU_COMMON_IMPLEMENTATION",
+ "-DUCONFIG_NO_COLLATION",
+ "-DUCONFIG_NO_CONVERSION",
+ "-DUCONFIG_NO_FORMATTING",
+ "-DUCONFIG_NO_SERVICE",
+ "-DUCONFIG_NO_IDNA",
+ "-DUCONFIG_NO_FILE_IO",
+ "-DUCONFIG_NO_TRANSLITERATION",
+ "-DPKGDATA_MODE=static",
+ "-DICU_DATA_NAME=" + icu_data_name,
+ ]
+ )
+ env_text_server_adv.Append(
+ CXXFLAGS=[
+ "-DICU_DATA_NAME=" + icu_data_name,
+ ]
+ )
+
+ lib = env_icu.add_library("icu_builtin", thirdparty_sources)
+ thirdparty_obj += lib
+
+ # Needs to be appended to arrive after libscene in the linker call,
+ # but we don't want it to arrive *after* system libs, so manual hack
+ # LIBS contains first SCons Library objects ("SCons.Node.FS.File object")
+ # and then plain strings for system library. We insert between the two.
+ inserted = False
+ for idx, linklib in enumerate(env["LIBS"]):
+ if isinstance(linklib, (str, bytes)): # first system lib such as "X11", otherwise SCons lib object
+ env["LIBS"].insert(idx, lib)
+ inserted = True
+ break
+ if not inserted:
+ env.Append(LIBS=[lib])
+
+
+# Godot source files
+
+module_obj = []
+
+if env_text_server_adv["tools"]:
+ env_text_server_adv.Append(CXXFLAGS=["-DICU_STATIC_DATA"])
+
+env_text_server_adv.Append(
+ CPPPATH=[
+ "#thirdparty/harfbuzz/src",
+ "#thirdparty/freetype/include",
+ "#thirdparty/graphite/include",
+ "#thirdparty/icu4c/common/",
+ ]
+)
+
+env_text_server_adv.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/text_server_adv/bitmap_font_adv.cpp b/modules/text_server_adv/bitmap_font_adv.cpp
new file mode 100644
index 0000000000..01fa94aa7c
--- /dev/null
+++ b/modules/text_server_adv/bitmap_font_adv.cpp
@@ -0,0 +1,580 @@
+/*************************************************************************/
+/* bitmap_font_adv.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "bitmap_font_adv.h"
+
+/*************************************************************************/
+/* hb_bmp_font_t HarfBuzz Bitmap font interface */
+/*************************************************************************/
+
+struct hb_bmp_font_t {
+ BitmapFontDataAdvanced *face = nullptr;
+ float font_size = 0;
+ bool unref = false; /* Whether to destroy bm_face when done. */
+};
+
+static hb_bmp_font_t *_hb_bmp_font_create(BitmapFontDataAdvanced *p_face, float p_font_size, bool p_unref) {
+ hb_bmp_font_t *bm_font = reinterpret_cast<hb_bmp_font_t *>(calloc(1, sizeof(hb_bmp_font_t)));
+
+ if (!bm_font) {
+ return nullptr;
+ }
+
+ bm_font->face = p_face;
+ bm_font->font_size = p_font_size;
+ bm_font->unref = p_unref;
+
+ return bm_font;
+}
+
+static void _hb_bmp_font_destroy(void *data) {
+ hb_bmp_font_t *bm_font = reinterpret_cast<hb_bmp_font_t *>(data);
+ free(bm_font);
+}
+
+static hb_bool_t hb_bmp_get_nominal_glyph(hb_font_t *font, void *font_data, hb_codepoint_t unicode, hb_codepoint_t *glyph, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return false;
+ }
+
+ if (!bm_font->face->has_char(unicode)) {
+ if (bm_font->face->has_char(0xF000u + unicode)) {
+ *glyph = 0xF000u + unicode;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ *glyph = unicode;
+ return true;
+}
+
+static hb_position_t hb_bmp_get_glyph_h_advance(hb_font_t *font, void *font_data, hb_codepoint_t glyph, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return 0;
+ }
+
+ if (!bm_font->face->has_char(glyph)) {
+ return 0;
+ }
+
+ return bm_font->face->get_advance(glyph, bm_font->font_size).x * 64;
+}
+
+static hb_position_t hb_bmp_get_glyph_v_advance(hb_font_t *font, void *font_data, hb_codepoint_t glyph, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return 0;
+ }
+
+ if (!bm_font->face->has_char(glyph)) {
+ return 0;
+ }
+
+ return -bm_font->face->get_advance(glyph, bm_font->font_size).y * 64;
+}
+
+static hb_position_t hb_bmp_get_glyph_h_kerning(hb_font_t *font, void *font_data, hb_codepoint_t left_glyph, hb_codepoint_t right_glyph, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return 0;
+ }
+
+ if (!bm_font->face->has_char(left_glyph)) {
+ return 0;
+ }
+
+ if (!bm_font->face->has_char(right_glyph)) {
+ return 0;
+ }
+
+ return bm_font->face->get_kerning(left_glyph, right_glyph, bm_font->font_size).x * 64;
+}
+
+static hb_bool_t hb_bmp_get_glyph_v_origin(hb_font_t *font, void *font_data, hb_codepoint_t glyph, hb_position_t *x, hb_position_t *y, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return false;
+ }
+
+ if (!bm_font->face->has_char(glyph)) {
+ return false;
+ }
+
+ *x = bm_font->face->get_advance(glyph, bm_font->font_size).x * 32;
+ *y = bm_font->face->get_ascent(bm_font->font_size) * 64;
+
+ return true;
+}
+
+static hb_bool_t hb_bmp_get_glyph_extents(hb_font_t *font, void *font_data, hb_codepoint_t glyph, hb_glyph_extents_t *extents, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return false;
+ }
+
+ if (!bm_font->face->has_char(glyph)) {
+ return false;
+ }
+
+ extents->x_bearing = 0;
+ extents->y_bearing = 0;
+ extents->width = bm_font->face->get_size(glyph, bm_font->font_size).x * 64;
+ extents->height = bm_font->face->get_size(glyph, bm_font->font_size).y * 64;
+
+ return true;
+}
+
+static hb_bool_t hb_bmp_get_font_h_extents(hb_font_t *font, void *font_data, hb_font_extents_t *metrics, void *user_data) {
+ const hb_bmp_font_t *bm_font = reinterpret_cast<const hb_bmp_font_t *>(font_data);
+
+ if (!bm_font->face) {
+ return false;
+ }
+
+ metrics->ascender = bm_font->face->get_ascent(bm_font->font_size);
+ metrics->descender = bm_font->face->get_descent(bm_font->font_size);
+ metrics->line_gap = 0;
+
+ return true;
+}
+
+static hb_font_funcs_t *funcs = nullptr;
+void hb_bmp_create_font_funcs() {
+ funcs = hb_font_funcs_create();
+
+ hb_font_funcs_set_font_h_extents_func(funcs, hb_bmp_get_font_h_extents, nullptr, nullptr);
+ //hb_font_funcs_set_font_v_extents_func (funcs, hb_bmp_get_font_v_extents, nullptr, nullptr);
+ hb_font_funcs_set_nominal_glyph_func(funcs, hb_bmp_get_nominal_glyph, nullptr, nullptr);
+ //hb_font_funcs_set_variation_glyph_func (funcs, hb_bmp_get_variation_glyph, nullptr, nullptr);
+ hb_font_funcs_set_glyph_h_advance_func(funcs, hb_bmp_get_glyph_h_advance, nullptr, nullptr);
+ hb_font_funcs_set_glyph_v_advance_func(funcs, hb_bmp_get_glyph_v_advance, nullptr, nullptr);
+ //hb_font_funcs_set_glyph_h_origin_func(funcs, hb_bmp_get_glyph_h_origin, nullptr, nullptr);
+ hb_font_funcs_set_glyph_v_origin_func(funcs, hb_bmp_get_glyph_v_origin, nullptr, nullptr);
+ hb_font_funcs_set_glyph_h_kerning_func(funcs, hb_bmp_get_glyph_h_kerning, nullptr, nullptr);
+ //hb_font_funcs_set_glyph_v_kerning_func (funcs, hb_bmp_get_glyph_v_kerning, nullptr, nullptr);
+ hb_font_funcs_set_glyph_extents_func(funcs, hb_bmp_get_glyph_extents, nullptr, nullptr);
+ //hb_font_funcs_set_glyph_contour_point_func (funcs, hb_bmp_get_glyph_contour_point, nullptr, nullptr);
+ //hb_font_funcs_set_glyph_name_func (funcs, hb_bmp_get_glyph_name, nullptr, nullptr);
+ //hb_font_funcs_set_glyph_from_name_func (funcs, hb_bmp_get_glyph_from_name, nullptr, nullptr);
+
+ hb_font_funcs_make_immutable(funcs);
+}
+
+void hb_bmp_free_font_funcs() {
+ if (funcs != nullptr) {
+ hb_font_funcs_destroy(funcs);
+ funcs = nullptr;
+ }
+}
+
+static void _hb_bmp_font_set_funcs(hb_font_t *p_font, BitmapFontDataAdvanced *p_face, int p_size, bool p_unref) {
+ hb_font_set_funcs(p_font, funcs, _hb_bmp_font_create(p_face, p_size, p_unref), _hb_bmp_font_destroy);
+}
+
+hb_font_t *hb_bmp_font_create(BitmapFontDataAdvanced *p_face, int p_size, hb_destroy_func_t p_destroy) {
+ hb_font_t *font;
+ hb_face_t *face = hb_face_create(nullptr, 0);
+
+ font = hb_font_create(face);
+ hb_face_destroy(face);
+ _hb_bmp_font_set_funcs(font, p_face, p_size, false);
+ return font;
+}
+
+/*************************************************************************/
+/* BitmapFontDataAdvanced */
+/*************************************************************************/
+
+Error BitmapFontDataAdvanced::load_from_file(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ //fnt format used by angelcode bmfont
+ //http://www.angelcode.com/products/bmfont/
+
+ FileAccess *f = FileAccess::open(p_filename, FileAccess::READ);
+ ERR_FAIL_COND_V_MSG(!f, ERR_FILE_NOT_FOUND, "Can't open font: " + p_filename + ".");
+
+ while (true) {
+ String line = f->get_line();
+
+ int delimiter = line.find(" ");
+ String type = line.substr(0, delimiter);
+ int pos = delimiter + 1;
+ Map<String, String> keys;
+
+ while (pos < line.size() && line[pos] == ' ') {
+ pos++;
+ }
+
+ while (pos < line.size()) {
+ int eq = line.find("=", pos);
+ if (eq == -1) {
+ break;
+ }
+ String key = line.substr(pos, eq - pos);
+ int end = -1;
+ String value;
+ if (line[eq + 1] == '"') {
+ end = line.find("\"", eq + 2);
+ if (end == -1) {
+ break;
+ }
+ value = line.substr(eq + 2, end - 1 - eq - 1);
+ pos = end + 1;
+ } else {
+ end = line.find(" ", eq + 1);
+ if (end == -1) {
+ end = line.size();
+ }
+ value = line.substr(eq + 1, end - eq);
+ pos = end;
+ }
+
+ while (pos < line.size() && line[pos] == ' ') {
+ pos++;
+ }
+
+ keys[key] = value;
+ }
+
+ if (type == "info") {
+ if (keys.has("size")) {
+ base_size = keys["size"].to_int();
+ }
+ } else if (type == "common") {
+ if (keys.has("lineHeight")) {
+ height = keys["lineHeight"].to_int();
+ }
+ if (keys.has("base")) {
+ ascent = keys["base"].to_int();
+ }
+ } else if (type == "page") {
+ if (keys.has("file")) {
+ String base_dir = p_filename.get_base_dir();
+ String file = base_dir.plus_file(keys["file"]);
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Texture2D> tex = ResourceLoader::load(file);
+ if (tex.is_null()) {
+ ERR_PRINT("Can't load font texture!");
+ } else {
+ ERR_FAIL_COND_V_MSG(tex.is_null(), ERR_FILE_CANT_READ, "It's not a reference to a valid Texture object.");
+ textures.push_back(tex);
+ }
+ }
+ }
+ } else if (type == "char") {
+ Character c;
+ char32_t idx = 0;
+ if (keys.has("id")) {
+ idx = keys["id"].to_int();
+ }
+ if (keys.has("x")) {
+ c.rect.position.x = keys["x"].to_int();
+ }
+ if (keys.has("y")) {
+ c.rect.position.y = keys["y"].to_int();
+ }
+ if (keys.has("width")) {
+ c.rect.size.width = keys["width"].to_int();
+ }
+ if (keys.has("height")) {
+ c.rect.size.height = keys["height"].to_int();
+ }
+ if (keys.has("xoffset")) {
+ c.align.x = keys["xoffset"].to_int();
+ }
+ if (keys.has("yoffset")) {
+ c.align.y = keys["yoffset"].to_int();
+ }
+ if (keys.has("page")) {
+ c.texture_idx = keys["page"].to_int();
+ }
+ if (keys.has("xadvance")) {
+ c.advance.x = keys["xadvance"].to_int();
+ }
+ if (keys.has("yadvance")) {
+ c.advance.x = keys["yadvance"].to_int();
+ }
+ if (c.advance.x < 0) {
+ c.advance.x = c.rect.size.width + 1;
+ }
+ if (c.advance.y < 0) {
+ c.advance.y = c.rect.size.height + 1;
+ }
+ char_map[idx] = c;
+ } else if (type == "kerning") {
+ KerningPairKey kpk;
+ float k = 0;
+ if (keys.has("first")) {
+ kpk.A = keys["first"].to_int();
+ }
+ if (keys.has("second")) {
+ kpk.B = keys["second"].to_int();
+ }
+ if (keys.has("amount")) {
+ k = keys["amount"].to_int();
+ }
+ kerning_map[kpk] = k;
+ }
+
+ if (f->eof_reached()) {
+ break;
+ }
+ }
+ if (base_size == 0) {
+ base_size = height;
+ }
+
+ valid = true;
+
+ memdelete(f);
+ return OK;
+}
+
+Error BitmapFontDataAdvanced::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(p_data == nullptr, ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(p_size != sizeof(TextServer::BitmapFontData), ERR_CANT_CREATE);
+
+ const TextServer::BitmapFontData *data = (const TextServer::BitmapFontData *)p_data;
+
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Image> image = memnew(Image(data->img));
+ Ref<ImageTexture> tex = memnew(ImageTexture);
+ tex->create_from_image(image);
+
+ textures.push_back(tex);
+ }
+
+ for (int i = 0; i < data->charcount; i++) {
+ const int *c = &data->char_rects[i * 8];
+
+ Character chr;
+ chr.rect.position.x = c[1];
+ chr.rect.position.y = c[2];
+ chr.rect.size.x = c[3];
+ chr.rect.size.y = c[4];
+ if (c[7] < 0) {
+ chr.advance.x = c[3];
+ } else {
+ chr.advance.x = c[7];
+ }
+ chr.align = Vector2(c[6], c[5]);
+ char_map[c[0]] = chr;
+ }
+
+ for (int i = 0; i < data->kerning_count; i++) {
+ KerningPairKey kpk;
+ kpk.A = data->kernings[i * 3 + 0];
+ kpk.B = data->kernings[i * 3 + 1];
+
+ if (data->kernings[i * 3 + 2] == 0 && kerning_map.has(kpk)) {
+ kerning_map.erase(kpk);
+ } else {
+ kerning_map[kpk] = data->kernings[i * 3 + 2];
+ }
+ }
+
+ height = data->height;
+ ascent = data->ascent;
+
+ base_size = p_base_size;
+ if (base_size == 0) {
+ base_size = height;
+ }
+
+ valid = true;
+
+ return OK;
+}
+
+float BitmapFontDataAdvanced::get_height(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return height * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataAdvanced::get_ascent(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return ascent * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataAdvanced::get_descent(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return (height - ascent) * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataAdvanced::get_underline_position(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return 2 * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataAdvanced::get_underline_thickness(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return 1 * (float(p_size) / float(base_size));
+}
+
+void BitmapFontDataAdvanced::set_distance_field_hint(bool p_distance_field) {
+ distance_field_hint = p_distance_field;
+}
+
+bool BitmapFontDataAdvanced::get_distance_field_hint() const {
+ return distance_field_hint;
+}
+
+float BitmapFontDataAdvanced::get_base_size() const {
+ return base_size;
+}
+
+hb_font_t *BitmapFontDataAdvanced::get_hb_handle(int p_size) {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, nullptr);
+ if (!cache.has(p_size)) {
+ cache[p_size] = hb_bmp_font_create(this, p_size, nullptr);
+ }
+ return cache[p_size];
+}
+
+bool BitmapFontDataAdvanced::has_char(char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, false);
+ return char_map.has(p_char);
+}
+
+String BitmapFontDataAdvanced::get_supported_chars() const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, String());
+ String chars;
+ const uint32_t *k = nullptr;
+ while ((k = char_map.next(k))) {
+ chars += char32_t(*k);
+ }
+ return chars;
+}
+
+Vector2 BitmapFontDataAdvanced::get_advance(uint32_t p_char, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_char);
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+
+ return c->advance * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataAdvanced::get_align(uint32_t p_char, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_char);
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+
+ return c->align * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataAdvanced::get_size(uint32_t p_char, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_char);
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+
+ return c->rect.size * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataAdvanced::get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ KerningPairKey kpk;
+ kpk.A = p_char;
+ kpk.B = p_next;
+
+ const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
+ if (E) {
+ return Vector2(-E->get() * (float(p_size) / float(base_size)), 0.f);
+ } else {
+ return Vector2();
+ }
+}
+
+Vector2 BitmapFontDataAdvanced::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ if (p_index == 0) {
+ return Vector2();
+ }
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_index);
+
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2());
+ if (c->texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += c->align * (float(p_size) / float(base_size));
+ cpos.y -= ascent * (float(p_size) / float(base_size));
+ if (RenderingServer::get_singleton() != nullptr) {
+ //if (distance_field_hint) { // Not implemented.
+ // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, true);
+ //}
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, c->rect.size * (float(p_size) / float(base_size))), textures[c->texture_idx]->get_rid(), c->rect, p_color, false, false);
+ //if (distance_field_hint) {
+ // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, false);
+ //}
+ }
+ }
+
+ return c->advance * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataAdvanced::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ if (p_index == 0) {
+ return Vector2();
+ }
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_index);
+
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2());
+
+ // Not supported, return advance for compatibility.
+
+ return c->advance * (float(p_size) / float(base_size));
+}
+
+BitmapFontDataAdvanced::~BitmapFontDataAdvanced() {
+ for (Map<float, hb_font_t *>::Element *E = cache.front(); E; E = E->next()) {
+ hb_font_destroy(E->get());
+ }
+}
diff --git a/modules/text_server_adv/bitmap_font_adv.h b/modules/text_server_adv/bitmap_font_adv.h
new file mode 100644
index 0000000000..c314f1b087
--- /dev/null
+++ b/modules/text_server_adv/bitmap_font_adv.h
@@ -0,0 +1,118 @@
+/*************************************************************************/
+/* bitmap_font_adv.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 BITMAP_FONT_ADV_H
+#define BITMAP_FONT_ADV_H
+
+#include "font_adv.h"
+
+void hb_bmp_create_font_funcs();
+void hb_bmp_free_font_funcs();
+
+struct BitmapFontDataAdvanced : public FontDataAdvanced {
+ _THREAD_SAFE_CLASS_
+
+private:
+ Vector<Ref<Texture2D>> textures;
+
+ struct Character {
+ int texture_idx = 0;
+ Rect2 rect;
+ Vector2 align;
+ Vector2 advance = Vector2(-1, -1);
+ };
+
+ struct KerningPairKey {
+ union {
+ struct {
+ uint32_t A, B;
+ };
+
+ uint64_t pair = 0;
+ };
+
+ _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; }
+ };
+
+ HashMap<uint32_t, Character> char_map;
+ Map<KerningPairKey, int> kerning_map;
+ Map<float, hb_font_t *> cache;
+
+ float height = 0.f;
+ float ascent = 0.f;
+ float base_size = 0.f;
+ bool distance_field_hint = false;
+
+public:
+ virtual void clear_cache() override{};
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) override;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override;
+
+ virtual float get_height(int p_size) const override;
+ virtual float get_ascent(int p_size) const override;
+ virtual float get_descent(int p_size) const override;
+
+ virtual float get_underline_position(int p_size) const override;
+ virtual float get_underline_thickness(int p_size) const override;
+
+ virtual void set_antialiased(bool p_antialiased) override{};
+ virtual bool get_antialiased() const override { return false; };
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) override{};
+ virtual TextServer::Hinting get_hinting() const override { return TextServer::HINTING_NONE; };
+
+ virtual void set_distance_field_hint(bool p_distance_field) override;
+ virtual bool get_distance_field_hint() const override;
+
+ virtual void set_force_autohinter(bool p_enabeld) override{};
+ virtual bool get_force_autohinter() const override { return false; };
+
+ virtual bool has_outline() const override { return false; };
+ virtual float get_base_size() const override;
+
+ virtual hb_font_t *get_hb_handle(int p_size) override;
+
+ virtual bool has_char(char32_t p_char) const override;
+ virtual String get_supported_chars() const override;
+
+ virtual Vector2 get_advance(uint32_t p_char, int p_size) const override;
+ Vector2 get_align(uint32_t p_char, int p_size) const;
+ Vector2 get_size(uint32_t p_char, int p_size) const;
+ virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const override;
+ virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const override { return (uint32_t)p_char; };
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+
+ virtual ~BitmapFontDataAdvanced();
+};
+
+#endif // BITMAP_FONT_ADV_H
diff --git a/modules/text_server_adv/config.py b/modules/text_server_adv/config.py
new file mode 100644
index 0000000000..22482fce24
--- /dev/null
+++ b/modules/text_server_adv/config.py
@@ -0,0 +1,6 @@
+def can_build(env, platform):
+ return env.module_check_dependencies("text_server_adv", ["freetype"])
+
+
+def configure(env):
+ pass
diff --git a/modules/text_server_adv/dynamic_font_adv.cpp b/modules/text_server_adv/dynamic_font_adv.cpp
new file mode 100644
index 0000000000..fcefa60d98
--- /dev/null
+++ b/modules/text_server_adv/dynamic_font_adv.cpp
@@ -0,0 +1,1003 @@
+/*************************************************************************/
+/* dynamic_font_adv.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "dynamic_font_adv.h"
+
+#include FT_STROKER_H
+#include FT_ADVANCES_H
+#include FT_MULTIPLE_MASTERS_H
+
+DynamicFontDataAdvanced::DataAtSize *DynamicFontDataAdvanced::get_data_for_size(int p_size, int p_outline_size) {
+ ERR_FAIL_COND_V(!valid, nullptr);
+ ERR_FAIL_COND_V(p_size < 0 || p_size > UINT16_MAX, nullptr);
+ ERR_FAIL_COND_V(p_outline_size < 0 || p_outline_size > UINT16_MAX, nullptr);
+
+ CacheID id;
+ id.size = p_size;
+ id.outline_size = p_outline_size;
+
+ DataAtSize *fds = nullptr;
+ Map<CacheID, DataAtSize *>::Element *E = nullptr;
+ if (p_outline_size != 0) {
+ E = size_cache_outline.find(id);
+ } else {
+ E = size_cache.find(id);
+ }
+
+ if (E != nullptr) {
+ fds = E->get();
+ } else {
+ if (font_mem == nullptr && font_path != String()) {
+ if (!font_mem_cache.is_empty()) {
+ font_mem = font_mem_cache.ptr();
+ font_mem_size = font_mem_cache.size();
+ } else {
+ FileAccess *f = FileAccess::open(font_path, FileAccess::READ);
+ if (!f) {
+ ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'.");
+ }
+
+ size_t len = f->get_len();
+ font_mem_cache.resize(len);
+ f->get_buffer(font_mem_cache.ptrw(), len);
+ font_mem = font_mem_cache.ptr();
+ font_mem_size = len;
+ f->close();
+ }
+ }
+
+ int error = 0;
+ fds = memnew(DataAtSize);
+ if (font_mem) {
+ memset(&fds->stream, 0, sizeof(FT_StreamRec));
+ fds->stream.base = (unsigned char *)font_mem;
+ fds->stream.size = font_mem_size;
+ fds->stream.pos = 0;
+
+ FT_Open_Args fargs;
+ memset(&fargs, 0, sizeof(FT_Open_Args));
+ fargs.memory_base = (unsigned char *)font_mem;
+ fargs.memory_size = font_mem_size;
+ fargs.flags = FT_OPEN_MEMORY;
+ fargs.stream = &fds->stream;
+ error = FT_Open_Face(library, &fargs, 0, &fds->face);
+
+ } else {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "DynamicFont uninitialized.");
+ }
+
+ if (error == FT_Err_Unknown_File_Format) {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "Unknown font format.");
+ } else if (error) {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "Error loading font.");
+ }
+
+ oversampling = TS->font_get_oversampling();
+
+ if (FT_HAS_COLOR(fds->face) && fds->face->num_fixed_sizes > 0) {
+ int best_match = 0;
+ int diff = ABS(p_size - ((int64_t)fds->face->available_sizes[0].width));
+ fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[0].width;
+ for (int i = 1; i < fds->face->num_fixed_sizes; i++) {
+ int ndiff = ABS(p_size - ((int64_t)fds->face->available_sizes[i].width));
+ if (ndiff < diff) {
+ best_match = i;
+ diff = ndiff;
+ fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[i].width;
+ }
+ }
+ FT_Select_Size(fds->face, best_match);
+ } else {
+ FT_Set_Pixel_Sizes(fds->face, 0, p_size * oversampling);
+ }
+
+ fds->size = p_size;
+ fds->ascent = (fds->face->size->metrics.ascender / 64.0) / oversampling * fds->scale_color_font;
+ fds->descent = (-fds->face->size->metrics.descender / 64.0) / oversampling * fds->scale_color_font;
+ fds->underline_position = -fds->face->underline_position / 64.0 / oversampling * fds->scale_color_font;
+ fds->underline_thickness = fds->face->underline_thickness / 64.0 / oversampling * fds->scale_color_font;
+
+ //Load os2 TTF pable
+ fds->os2 = (TT_OS2 *)FT_Get_Sfnt_Table(fds->face, FT_SFNT_OS2);
+
+ fds->hb_handle = hb_ft_font_create(fds->face, nullptr);
+ if (fds->hb_handle == nullptr) {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "Error loading HB font.");
+ }
+
+ if (p_outline_size != 0) {
+ size_cache_outline[id] = fds;
+ } else {
+ size_cache[id] = fds;
+ }
+
+ // Write variations.
+ if (fds->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
+ FT_MM_Var *amaster;
+
+ FT_Get_MM_Var(fds->face, &amaster);
+
+ Vector<hb_variation_t> hb_vars;
+ Vector<FT_Fixed> coords;
+ coords.resize(amaster->num_axis);
+
+ FT_Get_Var_Design_Coordinates(fds->face, coords.size(), coords.ptrw());
+
+ for (FT_UInt i = 0; i < amaster->num_axis; i++) {
+ hb_variation_t var;
+
+ // Reset to default.
+ var.tag = amaster->axis[i].tag;
+ var.value = (double)amaster->axis[i].def / 65536.f;
+ coords.write[i] = amaster->axis[i].def;
+
+ if (variations.has(var.tag)) {
+ var.value = variations[var.tag];
+ coords.write[i] = CLAMP(variations[var.tag] * 65536.f, amaster->axis[i].minimum, amaster->axis[i].maximum);
+ }
+
+ hb_vars.push_back(var);
+ }
+
+ FT_Set_Var_Design_Coordinates(fds->face, coords.size(), coords.ptrw());
+ hb_font_set_variations(fds->hb_handle, hb_vars.is_empty() ? nullptr : &hb_vars[0], hb_vars.size());
+
+ FT_Done_MM_Var(library, amaster);
+ }
+ }
+ return fds;
+}
+
+Dictionary DynamicFontDataAdvanced::get_variation_list() const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ if (fds == nullptr) {
+ return Dictionary();
+ }
+
+ Dictionary ret;
+ // Read variations.
+ if (fds->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
+ FT_MM_Var *amaster;
+
+ FT_Get_MM_Var(fds->face, &amaster);
+
+ for (FT_UInt i = 0; i < amaster->num_axis; i++) {
+ ret[(int32_t)amaster->axis[i].tag] = Vector3i(amaster->axis[i].minimum / 65536, amaster->axis[i].maximum / 65536, amaster->axis[i].def / 65536);
+ }
+
+ FT_Done_MM_Var(library, amaster);
+ }
+ return ret;
+}
+
+void DynamicFontDataAdvanced::set_variation(const String &p_name, double p_value) {
+ _THREAD_SAFE_METHOD_
+ int32_t tag = TS->name_to_tag(p_name);
+ if (!variations.has(tag) || (variations[tag] != p_value)) {
+ variations[tag] = p_value;
+ clear_cache();
+ }
+}
+
+double DynamicFontDataAdvanced::get_variation(const String &p_name) const {
+ _THREAD_SAFE_METHOD_
+ int32_t tag = TS->name_to_tag(p_name);
+ if (!variations.has(tag)) {
+ return 0.f;
+ }
+ return variations[tag];
+}
+
+Dictionary DynamicFontDataAdvanced::get_feature_list() const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ if (fds == nullptr) {
+ return Dictionary();
+ }
+
+ Dictionary out;
+ // Read feature flags.
+ unsigned int count = hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, NULL, NULL);
+ if (count != 0) {
+ hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
+ hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, &count, feature_tags);
+ for (unsigned int i = 0; i < count; i++) {
+ out[feature_tags[i]] = 1;
+ }
+ memfree(feature_tags);
+ }
+ count = hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, NULL, NULL);
+ if (count != 0) {
+ hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
+ hb_ot_layout_table_get_feature_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, &count, feature_tags);
+ for (unsigned int i = 0; i < count; i++) {
+ out[feature_tags[i]] = 1;
+ }
+ memfree(feature_tags);
+ }
+
+ return out;
+}
+
+DynamicFontDataAdvanced::TexturePosition DynamicFontDataAdvanced::find_texture_pos_for_glyph(DynamicFontDataAdvanced::DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) {
+ TexturePosition ret;
+ ret.index = -1;
+
+ int mw = p_width;
+ int mh = p_height;
+
+ for (int i = 0; i < p_data->textures.size(); i++) {
+ const CharTexture &ct = p_data->textures[i];
+
+ if (RenderingServer::get_singleton() != nullptr) {
+ if (ct.texture->get_format() != p_image_format) {
+ continue;
+ }
+ }
+
+ if (mw > ct.texture_size || mh > ct.texture_size) { //too big for this texture
+ continue;
+ }
+
+ ret.y = 0x7FFFFFFF;
+ ret.x = 0;
+
+ for (int j = 0; j < ct.texture_size - mw; j++) {
+ int max_y = 0;
+
+ for (int k = j; k < j + mw; k++) {
+ int y = ct.offsets[k];
+ if (y > max_y) {
+ max_y = y;
+ }
+ }
+
+ if (max_y < ret.y) {
+ ret.y = max_y;
+ ret.x = j;
+ }
+ }
+
+ if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size) {
+ continue; //fail, could not fit it here
+ }
+
+ ret.index = i;
+ break;
+ }
+
+ if (ret.index == -1) {
+ //could not find texture to fit, create one
+ ret.x = 0;
+ ret.y = 0;
+
+ int texsize = MAX(p_data->size * oversampling * 8, 256);
+ if (mw > texsize) {
+ texsize = mw; //special case, adapt to it?
+ }
+ if (mh > texsize) {
+ texsize = mh; //special case, adapt to it?
+ }
+
+ texsize = next_power_of_2(texsize);
+
+ texsize = MIN(texsize, 4096);
+
+ CharTexture tex;
+ tex.texture_size = texsize;
+ tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha
+
+ {
+ //zero texture
+ uint8_t *w = tex.imgdata.ptrw();
+ ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
+ // Initialize the texture to all-white pixels to prevent artifacts when the
+ // font is displayed at a non-default scale with filtering enabled.
+ if (p_color_size == 2) {
+ for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8
+ w[i + 0] = 255;
+ w[i + 1] = 0;
+ }
+ } else if (p_color_size == 4) {
+ for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8
+ w[i + 0] = 255;
+ w[i + 1] = 255;
+ w[i + 2] = 255;
+ w[i + 3] = 0;
+ }
+ } else {
+ ERR_FAIL_V(ret);
+ }
+ }
+ tex.offsets.resize(texsize);
+ for (int i = 0; i < texsize; i++) { //zero offsets
+ tex.offsets.write[i] = 0;
+ }
+
+ p_data->textures.push_back(tex);
+ ret.index = p_data->textures.size() - 1;
+ }
+
+ return ret;
+}
+
+DynamicFontDataAdvanced::Character DynamicFontDataAdvanced::Character::not_found() {
+ Character ch;
+ return ch;
+}
+
+DynamicFontDataAdvanced::Character DynamicFontDataAdvanced::bitmap_to_character(DynamicFontDataAdvanced::DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance) {
+ int w = bitmap.width;
+ int h = bitmap.rows;
+
+ int mw = w + rect_margin * 2;
+ int mh = h + rect_margin * 2;
+
+ ERR_FAIL_COND_V(mw > 4096, Character::not_found());
+ ERR_FAIL_COND_V(mh > 4096, Character::not_found());
+
+ int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
+ Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
+
+ TexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh);
+ ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found());
+
+ //fit character in char texture
+
+ CharTexture &tex = p_data->textures.write[tex_pos.index];
+
+ {
+ uint8_t *wr = tex.imgdata.ptrw();
+
+ for (int i = 0; i < h; i++) {
+ for (int j = 0; j < w; j++) {
+ int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size;
+ ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found());
+ switch (bitmap.pixel_mode) {
+ case FT_PIXEL_MODE_MONO: {
+ int byte = i * bitmap.pitch + (j >> 3);
+ int bit = 1 << (7 - (j % 8));
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0;
+ } break;
+ case FT_PIXEL_MODE_GRAY:
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
+ break;
+ case FT_PIXEL_MODE_BGRA: {
+ int ofs_color = i * bitmap.pitch + (j << 2);
+ wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
+ wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
+ wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
+ wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
+ } break;
+ // TODO: FT_PIXEL_MODE_LCD
+ default:
+ ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + ".");
+ break;
+ }
+ }
+ }
+ }
+
+ //blit to image and texture
+ {
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata));
+
+ if (tex.texture.is_null()) {
+ tex.texture.instance();
+ tex.texture->create_from_image(img);
+ } else {
+ tex.texture->update(img); //update
+ }
+ }
+ }
+
+ // update height array
+ for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
+ tex.offsets.write[k] = tex_pos.y + mh;
+ }
+
+ Character chr;
+ chr.align = (Vector2(xofs, -yofs) * p_data->scale_color_font / oversampling).round();
+ chr.advance = (advance * p_data->scale_color_font / oversampling).round();
+ chr.texture_idx = tex_pos.index;
+ chr.found = true;
+
+ chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h);
+ chr.rect = chr.rect_uv;
+ chr.rect.position /= oversampling;
+ chr.rect.size *= (p_data->scale_color_font / oversampling);
+ return chr;
+}
+
+void DynamicFontDataAdvanced::update_glyph(int p_size, uint32_t p_index) {
+ DataAtSize *fds = get_data_for_size(p_size, false);
+ ERR_FAIL_COND(fds == nullptr);
+
+ if (fds->glyph_map.has(p_index)) {
+ return;
+ }
+
+ Character character = Character::not_found();
+ FT_GlyphSlot slot = fds->face->glyph;
+
+ if (p_index == 0) {
+ fds->glyph_map[p_index] = character;
+ return;
+ }
+
+ int ft_hinting;
+ switch (hinting) {
+ case TextServer::HINTING_NONE:
+ ft_hinting = FT_LOAD_NO_HINTING;
+ break;
+ case TextServer::HINTING_LIGHT:
+ ft_hinting = FT_LOAD_TARGET_LIGHT;
+ break;
+ default:
+ ft_hinting = FT_LOAD_TARGET_NORMAL;
+ break;
+ }
+
+ FT_Fixed v, h;
+ FT_Get_Advance(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting, &h);
+ FT_Get_Advance(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting | FT_LOAD_VERTICAL_LAYOUT, &v);
+
+ int error = FT_Load_Glyph(fds->face, p_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting);
+ if (error) {
+ fds->glyph_map[p_index] = character;
+ return;
+ }
+
+ error = FT_Render_Glyph(fds->face->glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
+ if (!error) {
+ character = bitmap_to_character(fds, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
+ }
+
+ fds->glyph_map[p_index] = character;
+}
+
+void DynamicFontDataAdvanced::update_glyph_outline(int p_size, int p_outline_size, uint32_t p_index) {
+ DataAtSize *fds = get_data_for_size(p_size, p_outline_size);
+ ERR_FAIL_COND(fds == nullptr);
+
+ if (fds->glyph_map.has(p_index)) {
+ return;
+ }
+
+ Character character = Character::not_found();
+ if (p_index == 0) {
+ fds->glyph_map[p_index] = character;
+ return;
+ }
+
+ int error = FT_Load_Glyph(fds->face, p_index, FT_LOAD_NO_BITMAP | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
+ if (error) {
+ fds->glyph_map[p_index] = character;
+ return;
+ }
+
+ FT_Stroker stroker;
+ if (FT_Stroker_New(library, &stroker) != 0) {
+ fds->glyph_map[p_index] = character;
+ return;
+ }
+
+ FT_Stroker_Set(stroker, (int)(p_outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
+ FT_Glyph glyph;
+ FT_BitmapGlyph glyph_bitmap;
+
+ if (FT_Get_Glyph(fds->face->glyph, &glyph) != 0) {
+ goto cleanup_stroker;
+ }
+ if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
+ goto cleanup_glyph;
+ }
+ if (FT_Glyph_To_Bitmap(&glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) {
+ goto cleanup_glyph;
+ }
+
+ glyph_bitmap = (FT_BitmapGlyph)glyph;
+ character = bitmap_to_character(fds, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2());
+
+cleanup_glyph:
+ FT_Done_Glyph(glyph);
+cleanup_stroker:
+ FT_Stroker_Done(stroker);
+
+ fds->glyph_map[p_index] = character;
+}
+
+void DynamicFontDataAdvanced::clear_cache() {
+ _THREAD_SAFE_METHOD_
+ for (Map<CacheID, DataAtSize *>::Element *E = size_cache.front(); E; E = E->next()) {
+ memdelete(E->get());
+ }
+ size_cache.clear();
+ for (Map<CacheID, DataAtSize *>::Element *E = size_cache_outline.front(); E; E = E->next()) {
+ memdelete(E->get());
+ }
+ size_cache_outline.clear();
+}
+
+Error DynamicFontDataAdvanced::load_from_file(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ if (library == nullptr) {
+ int error = FT_Init_FreeType(&library);
+ ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
+ }
+ clear_cache();
+
+ font_path = p_filename;
+ base_size = p_base_size;
+
+ valid = true;
+ DataAtSize *fds = get_data_for_size(base_size); // load base size.
+ if (fds == nullptr) {
+ valid = false;
+ ERR_FAIL_V(ERR_CANT_CREATE);
+ }
+
+ return OK;
+}
+
+Error DynamicFontDataAdvanced::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ if (library == nullptr) {
+ int error = FT_Init_FreeType(&library);
+ ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
+ }
+ clear_cache();
+
+ font_mem = p_data;
+ font_mem_size = p_size;
+ base_size = p_base_size;
+
+ valid = true;
+ DataAtSize *fds = get_data_for_size(base_size); // load base size.
+ if (fds == nullptr) {
+ valid = false;
+ ERR_FAIL_V(ERR_CANT_CREATE);
+ }
+
+ return OK;
+}
+
+float DynamicFontDataAdvanced::get_height(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->ascent + fds->descent;
+}
+
+float DynamicFontDataAdvanced::get_ascent(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->ascent;
+}
+
+float DynamicFontDataAdvanced::get_descent(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->descent;
+}
+
+float DynamicFontDataAdvanced::get_underline_position(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->underline_position;
+}
+
+float DynamicFontDataAdvanced::get_underline_thickness(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->underline_thickness;
+}
+
+bool DynamicFontDataAdvanced::is_script_supported(uint32_t p_script) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, false);
+
+ unsigned int count = hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, NULL, NULL);
+ if (count != 0) {
+ hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
+ hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GSUB, 0, &count, script_tags);
+ for (unsigned int i = 0; i < count; i++) {
+ if (p_script == script_tags[i]) {
+ memfree(script_tags);
+ return true;
+ }
+ }
+ memfree(script_tags);
+ }
+ count = hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, NULL, NULL);
+ if (count != 0) {
+ hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
+ hb_ot_layout_table_get_script_tags(hb_font_get_face(fds->hb_handle), HB_OT_TAG_GPOS, 0, &count, script_tags);
+ for (unsigned int i = 0; i < count; i++) {
+ if (p_script == script_tags[i]) {
+ memfree(script_tags);
+ return true;
+ }
+ }
+ memfree(script_tags);
+ }
+
+ if (!fds->os2) {
+ return false;
+ }
+
+ switch (p_script) {
+ case HB_SCRIPT_COMMON:
+ return (fds->os2->ulUnicodeRange1 & 1L << 4) || (fds->os2->ulUnicodeRange1 & 1L << 5) || (fds->os2->ulUnicodeRange1 & 1L << 6) || (fds->os2->ulUnicodeRange1 & 1L << 31) || (fds->os2->ulUnicodeRange2 & 1L << 0) || (fds->os2->ulUnicodeRange2 & 1L << 1) || (fds->os2->ulUnicodeRange2 & 1L << 2) || (fds->os2->ulUnicodeRange2 & 1L << 3) || (fds->os2->ulUnicodeRange2 & 1L << 4) || (fds->os2->ulUnicodeRange2 & 1L << 5) || (fds->os2->ulUnicodeRange2 & 1L << 6) || (fds->os2->ulUnicodeRange2 & 1L << 7) || (fds->os2->ulUnicodeRange2 & 1L << 8) || (fds->os2->ulUnicodeRange2 & 1L << 9) || (fds->os2->ulUnicodeRange2 & 1L << 10) || (fds->os2->ulUnicodeRange2 & 1L << 11) || (fds->os2->ulUnicodeRange2 & 1L << 12) || (fds->os2->ulUnicodeRange2 & 1L << 13) || (fds->os2->ulUnicodeRange2 & 1L << 14) || (fds->os2->ulUnicodeRange2 & 1L << 15) || (fds->os2->ulUnicodeRange2 & 1L << 30) || (fds->os2->ulUnicodeRange3 & 1L << 0) || (fds->os2->ulUnicodeRange3 & 1L << 1) || (fds->os2->ulUnicodeRange3 & 1L << 2) || (fds->os2->ulUnicodeRange3 & 1L << 4) || (fds->os2->ulUnicodeRange3 & 1L << 5) || (fds->os2->ulUnicodeRange3 & 1L << 18) || (fds->os2->ulUnicodeRange3 & 1L << 24) || (fds->os2->ulUnicodeRange3 & 1L << 25) || (fds->os2->ulUnicodeRange3 & 1L << 26) || (fds->os2->ulUnicodeRange3 & 1L << 27) || (fds->os2->ulUnicodeRange3 & 1L << 28) || (fds->os2->ulUnicodeRange4 & 1L << 3) || (fds->os2->ulUnicodeRange4 & 1L << 6) || (fds->os2->ulUnicodeRange4 & 1L << 15) || (fds->os2->ulUnicodeRange4 & 1L << 23) || (fds->os2->ulUnicodeRange4 & 1L << 24) || (fds->os2->ulUnicodeRange4 & 1L << 26);
+ case HB_SCRIPT_LATIN:
+ return (fds->os2->ulUnicodeRange1 & 1L << 0) || (fds->os2->ulUnicodeRange1 & 1L << 1) || (fds->os2->ulUnicodeRange1 & 1L << 2) || (fds->os2->ulUnicodeRange1 & 1L << 3) || (fds->os2->ulUnicodeRange1 & 1L << 29);
+ case HB_SCRIPT_GREEK:
+ return (fds->os2->ulUnicodeRange1 & 1L << 7) || (fds->os2->ulUnicodeRange1 & 1L << 30);
+ case HB_SCRIPT_COPTIC:
+ return (fds->os2->ulUnicodeRange1 & 1L << 8);
+ case HB_SCRIPT_CYRILLIC:
+ return (fds->os2->ulUnicodeRange1 & 1L << 9);
+ case HB_SCRIPT_ARMENIAN:
+ return (fds->os2->ulUnicodeRange1 & 1L << 10);
+ case HB_SCRIPT_HEBREW:
+ return (fds->os2->ulUnicodeRange1 & 1L << 11);
+ case HB_SCRIPT_VAI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 12);
+ case HB_SCRIPT_ARABIC:
+ return (fds->os2->ulUnicodeRange1 & 1L << 13) || (fds->os2->ulUnicodeRange2 & 1L << 31) || (fds->os2->ulUnicodeRange3 & 1L << 3);
+ case HB_SCRIPT_NKO:
+ return (fds->os2->ulUnicodeRange1 & 1L << 14);
+ case HB_SCRIPT_DEVANAGARI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 15);
+ case HB_SCRIPT_BENGALI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 16);
+ case HB_SCRIPT_GURMUKHI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 17);
+ case HB_SCRIPT_GUJARATI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 18);
+ case HB_SCRIPT_ORIYA:
+ return (fds->os2->ulUnicodeRange1 & 1L << 19);
+ case HB_SCRIPT_TAMIL:
+ return (fds->os2->ulUnicodeRange1 & 1L << 20);
+ case HB_SCRIPT_TELUGU:
+ return (fds->os2->ulUnicodeRange1 & 1L << 21);
+ case HB_SCRIPT_KANNADA:
+ return (fds->os2->ulUnicodeRange1 & 1L << 22);
+ case HB_SCRIPT_MALAYALAM:
+ return (fds->os2->ulUnicodeRange1 & 1L << 23);
+ case HB_SCRIPT_THAI:
+ return (fds->os2->ulUnicodeRange1 & 1L << 24);
+ case HB_SCRIPT_LAO:
+ return (fds->os2->ulUnicodeRange1 & 1L << 25);
+ case HB_SCRIPT_GEORGIAN:
+ return (fds->os2->ulUnicodeRange1 & 1L << 26);
+ case HB_SCRIPT_BALINESE:
+ return (fds->os2->ulUnicodeRange1 & 1L << 27);
+ case HB_SCRIPT_HANGUL:
+ return (fds->os2->ulUnicodeRange1 & 1L << 28) || (fds->os2->ulUnicodeRange2 & 1L << 20) || (fds->os2->ulUnicodeRange2 & 1L << 24);
+ case HB_SCRIPT_HAN:
+ return (fds->os2->ulUnicodeRange2 & 1L << 21) || (fds->os2->ulUnicodeRange2 & 1L << 22) || (fds->os2->ulUnicodeRange2 & 1L << 23) || (fds->os2->ulUnicodeRange2 & 1L << 26) || (fds->os2->ulUnicodeRange2 & 1L << 27) || (fds->os2->ulUnicodeRange2 & 1L << 29);
+ case HB_SCRIPT_HIRAGANA:
+ return (fds->os2->ulUnicodeRange2 & 1L << 17);
+ case HB_SCRIPT_KATAKANA:
+ return (fds->os2->ulUnicodeRange2 & 1L << 18);
+ case HB_SCRIPT_BOPOMOFO:
+ return (fds->os2->ulUnicodeRange2 & 1L << 19);
+ case HB_SCRIPT_TIBETAN:
+ return (fds->os2->ulUnicodeRange3 & 1L << 6);
+ case HB_SCRIPT_SYRIAC:
+ return (fds->os2->ulUnicodeRange3 & 1L << 7);
+ case HB_SCRIPT_THAANA:
+ return (fds->os2->ulUnicodeRange3 & 1L << 8);
+ case HB_SCRIPT_SINHALA:
+ return (fds->os2->ulUnicodeRange3 & 1L << 9);
+ case HB_SCRIPT_MYANMAR:
+ return (fds->os2->ulUnicodeRange3 & 1L << 10);
+ case HB_SCRIPT_ETHIOPIC:
+ return (fds->os2->ulUnicodeRange3 & 1L << 11);
+ case HB_SCRIPT_CHEROKEE:
+ return (fds->os2->ulUnicodeRange3 & 1L << 12);
+ case HB_SCRIPT_CANADIAN_SYLLABICS:
+ return (fds->os2->ulUnicodeRange3 & 1L << 13);
+ case HB_SCRIPT_OGHAM:
+ return (fds->os2->ulUnicodeRange3 & 1L << 14);
+ case HB_SCRIPT_RUNIC:
+ return (fds->os2->ulUnicodeRange3 & 1L << 15);
+ case HB_SCRIPT_KHMER:
+ return (fds->os2->ulUnicodeRange3 & 1L << 16);
+ case HB_SCRIPT_MONGOLIAN:
+ return (fds->os2->ulUnicodeRange3 & 1L << 17);
+ case HB_SCRIPT_YI:
+ return (fds->os2->ulUnicodeRange3 & 1L << 19);
+ case HB_SCRIPT_HANUNOO:
+ case HB_SCRIPT_TAGBANWA:
+ case HB_SCRIPT_BUHID:
+ case HB_SCRIPT_TAGALOG:
+ return (fds->os2->ulUnicodeRange3 & 1L << 20);
+ case HB_SCRIPT_OLD_ITALIC:
+ return (fds->os2->ulUnicodeRange3 & 1L << 21);
+ case HB_SCRIPT_GOTHIC:
+ return (fds->os2->ulUnicodeRange3 & 1L << 22);
+ case HB_SCRIPT_DESERET:
+ return (fds->os2->ulUnicodeRange3 & 1L << 23);
+ case HB_SCRIPT_LIMBU:
+ return (fds->os2->ulUnicodeRange3 & 1L << 29);
+ case HB_SCRIPT_TAI_LE:
+ return (fds->os2->ulUnicodeRange3 & 1L << 30);
+ case HB_SCRIPT_NEW_TAI_LUE:
+ return (fds->os2->ulUnicodeRange3 & 1L << 31);
+ case HB_SCRIPT_BUGINESE:
+ return (fds->os2->ulUnicodeRange4 & 1L << 0);
+ case HB_SCRIPT_GLAGOLITIC:
+ return (fds->os2->ulUnicodeRange4 & 1L << 1);
+ case HB_SCRIPT_TIFINAGH:
+ return (fds->os2->ulUnicodeRange4 & 1L << 2);
+ case HB_SCRIPT_SYLOTI_NAGRI:
+ return (fds->os2->ulUnicodeRange4 & 1L << 4);
+ case HB_SCRIPT_LINEAR_B:
+ return (fds->os2->ulUnicodeRange4 & 1L << 5);
+ case HB_SCRIPT_UGARITIC:
+ return (fds->os2->ulUnicodeRange4 & 1L << 7);
+ case HB_SCRIPT_OLD_PERSIAN:
+ return (fds->os2->ulUnicodeRange4 & 1L << 8);
+ case HB_SCRIPT_SHAVIAN:
+ return (fds->os2->ulUnicodeRange4 & 1L << 9);
+ case HB_SCRIPT_OSMANYA:
+ return (fds->os2->ulUnicodeRange4 & 1L << 10);
+ case HB_SCRIPT_CYPRIOT:
+ return (fds->os2->ulUnicodeRange4 & 1L << 11);
+ case HB_SCRIPT_KHAROSHTHI:
+ return (fds->os2->ulUnicodeRange4 & 1L << 12);
+ case HB_SCRIPT_TAI_VIET:
+ return (fds->os2->ulUnicodeRange4 & 1L << 13);
+ case HB_SCRIPT_CUNEIFORM:
+ return (fds->os2->ulUnicodeRange4 & 1L << 14);
+ case HB_SCRIPT_SUNDANESE:
+ return (fds->os2->ulUnicodeRange4 & 1L << 16);
+ case HB_SCRIPT_LEPCHA:
+ return (fds->os2->ulUnicodeRange4 & 1L << 17);
+ case HB_SCRIPT_OL_CHIKI:
+ return (fds->os2->ulUnicodeRange4 & 1L << 18);
+ case HB_SCRIPT_SAURASHTRA:
+ return (fds->os2->ulUnicodeRange4 & 1L << 19);
+ case HB_SCRIPT_KAYAH_LI:
+ return (fds->os2->ulUnicodeRange4 & 1L << 20);
+ case HB_SCRIPT_REJANG:
+ return (fds->os2->ulUnicodeRange4 & 1L << 21);
+ case HB_SCRIPT_CHAM:
+ return (fds->os2->ulUnicodeRange4 & 1L << 22);
+ case HB_SCRIPT_ANATOLIAN_HIEROGLYPHS:
+ return (fds->os2->ulUnicodeRange4 & 1L << 25);
+ default:
+ return false;
+ };
+}
+
+void DynamicFontDataAdvanced::set_antialiased(bool p_antialiased) {
+ if (antialiased != p_antialiased) {
+ clear_cache();
+ antialiased = p_antialiased;
+ }
+}
+
+bool DynamicFontDataAdvanced::get_antialiased() const {
+ return antialiased;
+}
+
+void DynamicFontDataAdvanced::set_force_autohinter(bool p_enabled) {
+ if (force_autohinter != p_enabled) {
+ clear_cache();
+ force_autohinter = p_enabled;
+ }
+}
+
+bool DynamicFontDataAdvanced::get_force_autohinter() const {
+ return force_autohinter;
+}
+
+void DynamicFontDataAdvanced::set_hinting(TextServer::Hinting p_hinting) {
+ if (hinting != p_hinting) {
+ clear_cache();
+ hinting = p_hinting;
+ }
+}
+
+TextServer::Hinting DynamicFontDataAdvanced::get_hinting() const {
+ return hinting;
+}
+
+bool DynamicFontDataAdvanced::has_outline() const {
+ return true;
+}
+
+float DynamicFontDataAdvanced::get_base_size() const {
+ return base_size;
+}
+
+String DynamicFontDataAdvanced::get_supported_chars() const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, String());
+
+ String chars;
+
+ FT_UInt gindex;
+ FT_ULong charcode = FT_Get_First_Char(fds->face, &gindex);
+ while (gindex != 0) {
+ if (charcode != 0) {
+ chars += char32_t(charcode);
+ }
+ charcode = FT_Get_Next_Char(fds->face, charcode, &gindex);
+ }
+
+ return chars;
+}
+
+float DynamicFontDataAdvanced::get_font_scale(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 1.0f);
+
+ return fds->scale_color_font / oversampling;
+}
+
+bool DynamicFontDataAdvanced::has_char(char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, false);
+
+ const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(base_size, FT_Get_Char_Index(fds->face, p_char));
+ Character ch = fds->glyph_map[FT_Get_Char_Index(fds->face, p_char)];
+
+ return (ch.found);
+}
+
+hb_font_t *DynamicFontDataAdvanced::get_hb_handle(int p_size) {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, nullptr);
+
+ return fds->hb_handle;
+}
+
+uint32_t DynamicFontDataAdvanced::get_glyph_index(char32_t p_char, char32_t p_variation_selector) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0);
+
+ if (p_variation_selector == 0x0000) {
+ return FT_Get_Char_Index(fds->face, p_char);
+ } else {
+ return FT_Face_GetCharVariantIndex(fds->face, p_char, p_variation_selector);
+ }
+}
+
+Vector2 DynamicFontDataAdvanced::get_advance(uint32_t p_index, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(p_size, p_index);
+ Character ch = fds->glyph_map[p_index];
+
+ return ch.advance;
+}
+
+Vector2 DynamicFontDataAdvanced::get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ FT_Vector delta;
+ FT_Get_Kerning(fds->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
+ return Vector2(delta.x, delta.y);
+}
+
+Vector2 DynamicFontDataAdvanced::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataAdvanced *>(this)->update_glyph(p_size, p_index);
+ Character ch = fds->glyph_map[p_index];
+
+ Vector2 advance;
+ if (ch.found) {
+ ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2());
+
+ if (ch.texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += ch.align;
+ Color modulate = p_color;
+ if (FT_HAS_COLOR(fds->face)) {
+ modulate.r = modulate.g = modulate.b = 1.0;
+ }
+ if (RenderingServer::get_singleton() != nullptr) {
+ RID texture = fds->textures[ch.texture_idx].texture->get_rid();
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false);
+ }
+ }
+
+ advance = ch.advance;
+ }
+
+ return advance;
+}
+
+Vector2 DynamicFontDataAdvanced::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataAdvanced *>(this)->get_data_for_size(p_size, p_outline_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataAdvanced *>(this)->update_glyph_outline(p_size, p_outline_size, p_index);
+ Character ch = fds->glyph_map[p_index];
+
+ Vector2 advance;
+ if (ch.found) {
+ ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2());
+
+ if (ch.texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += ch.align;
+ Color modulate = p_color;
+ if (FT_HAS_COLOR(fds->face)) {
+ modulate.r = modulate.g = modulate.b = 1.0;
+ }
+ if (RenderingServer::get_singleton() != nullptr) {
+ RID texture = fds->textures[ch.texture_idx].texture->get_rid();
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false);
+ }
+ }
+
+ advance = ch.advance;
+ }
+
+ return advance;
+}
+
+DynamicFontDataAdvanced::~DynamicFontDataAdvanced() {
+ clear_cache();
+ if (library != nullptr) {
+ FT_Done_FreeType(library);
+ }
+}
diff --git a/modules/text_server_adv/dynamic_font_adv.h b/modules/text_server_adv/dynamic_font_adv.h
new file mode 100644
index 0000000000..c35dd9390b
--- /dev/null
+++ b/modules/text_server_adv/dynamic_font_adv.h
@@ -0,0 +1,191 @@
+/*************************************************************************/
+/* dynamic_font_adv.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 DYNAMIC_FONT_ADV_H
+#define DYNAMIC_FONT_ADV_H
+
+#include "font_adv.h"
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_TRUETYPE_TABLES_H
+
+#include <hb-ft.h>
+#include <hb-ot.h>
+
+struct DynamicFontDataAdvanced : public FontDataAdvanced {
+ _THREAD_SAFE_CLASS_
+
+private:
+ struct CharTexture {
+ Vector<uint8_t> imgdata;
+ int texture_size = 0;
+ Vector<int> offsets;
+ Ref<ImageTexture> texture;
+ };
+
+ struct Character {
+ bool found = false;
+ int texture_idx = 0;
+ Rect2 rect;
+ Rect2 rect_uv;
+ Vector2 align;
+ Vector2 advance = Vector2(-1, -1);
+
+ static Character not_found();
+ };
+
+ struct TexturePosition {
+ int index = 0;
+ int x = 0;
+ int y = 0;
+ };
+
+ struct CacheID {
+ union {
+ struct {
+ uint32_t size : 16;
+ uint32_t outline_size : 16;
+ };
+ uint32_t key;
+ };
+ bool operator<(CacheID right) const {
+ return key < right.key;
+ }
+ CacheID() {
+ key = 0;
+ }
+ };
+
+ struct DataAtSize {
+ FT_Face face = nullptr;
+ TT_OS2 *os2 = nullptr;
+ FT_StreamRec stream;
+
+ int size = 0;
+ float scale_color_font = 1.f;
+ float ascent = 0;
+ float descent = 0;
+ float underline_position = 0;
+ float underline_thickness = 0;
+
+ Vector<CharTexture> textures;
+ HashMap<uint32_t, Character> glyph_map;
+
+ hb_font_t *hb_handle = nullptr;
+ ~DataAtSize() {
+ if (hb_handle != nullptr) {
+ hb_font_destroy(hb_handle);
+ }
+ if (face != nullptr) {
+ FT_Done_Face(face);
+ }
+ }
+ };
+
+ FT_Library library = nullptr;
+
+ // Source data.
+ const uint8_t *font_mem = nullptr;
+ int font_mem_size = 0;
+ String font_path;
+ Vector<uint8_t> font_mem_cache;
+
+ Map<int32_t, double> variations;
+
+ float rect_margin = 1.f;
+ int base_size = 16;
+ float oversampling = 1.f;
+ bool antialiased = true;
+ bool force_autohinter = false;
+ TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
+
+ Map<CacheID, DataAtSize *> size_cache;
+ Map<CacheID, DataAtSize *> size_cache_outline;
+
+ DataAtSize *get_data_for_size(int p_size, int p_outline_size = 0);
+
+ TexturePosition find_texture_pos_for_glyph(DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height);
+ Character bitmap_to_character(DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance);
+ _FORCE_INLINE_ void update_glyph(int p_size, uint32_t p_index);
+ _FORCE_INLINE_ void update_glyph_outline(int p_size, int p_outline_size, uint32_t p_index);
+
+public:
+ virtual void clear_cache() override;
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) override;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override;
+
+ virtual float get_height(int p_size) const override;
+ virtual float get_ascent(int p_size) const override;
+ virtual float get_descent(int p_size) const override;
+
+ virtual Dictionary get_feature_list() const override;
+ virtual Dictionary get_variation_list() const override;
+
+ virtual void set_variation(const String &p_name, double p_value) override;
+ virtual double get_variation(const String &p_name) const override;
+
+ virtual float get_underline_position(int p_size) const override;
+ virtual float get_underline_thickness(int p_size) const override;
+
+ virtual void set_antialiased(bool p_antialiased) override;
+ virtual bool get_antialiased() const override;
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) override;
+ virtual TextServer::Hinting get_hinting() const override;
+
+ virtual void set_force_autohinter(bool p_enabled) override;
+ virtual bool get_force_autohinter() const override;
+
+ virtual void set_distance_field_hint(bool p_distance_field) override{};
+ virtual bool get_distance_field_hint() const override { return false; };
+
+ virtual bool has_outline() const override;
+ virtual float get_base_size() const override;
+
+ virtual bool is_script_supported(uint32_t p_script) const override;
+
+ virtual bool has_char(char32_t p_char) const override;
+ virtual String get_supported_chars() const override;
+ virtual float get_font_scale(int p_size) const override;
+
+ virtual hb_font_t *get_hb_handle(int p_size) override;
+ virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const override;
+ virtual Vector2 get_advance(uint32_t p_index, int p_size) const override;
+ virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const override;
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+
+ virtual ~DynamicFontDataAdvanced() override;
+};
+
+#endif // DYNAMIC_FONT_ADV_H
diff --git a/modules/text_server_adv/font_adv.h b/modules/text_server_adv/font_adv.h
new file mode 100644
index 0000000000..4bbd2dd4bf
--- /dev/null
+++ b/modules/text_server_adv/font_adv.h
@@ -0,0 +1,94 @@
+/*************************************************************************/
+/* font_adv.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FONT_ADV_H
+#define FONT_ADV_H
+
+#include "servers/text_server.h"
+
+#include <hb.h>
+
+struct FontDataAdvanced {
+ Map<String, bool> lang_support_overrides;
+ Map<String, bool> script_support_overrides;
+ bool valid = false;
+
+ virtual void clear_cache() = 0;
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) = 0;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) = 0;
+
+ virtual float get_height(int p_size) const = 0;
+ virtual float get_ascent(int p_size) const = 0;
+ virtual float get_descent(int p_size) const = 0;
+
+ virtual Dictionary get_feature_list() const { return Dictionary(); };
+ virtual Dictionary get_variation_list() const { return Dictionary(); };
+
+ virtual void set_variation(const String &p_name, double p_value){};
+ virtual double get_variation(const String &p_name) const { return 0; };
+
+ virtual float get_underline_position(int p_size) const = 0;
+ virtual float get_underline_thickness(int p_size) const = 0;
+
+ virtual void set_antialiased(bool p_antialiased) = 0;
+ virtual bool get_antialiased() const = 0;
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) = 0;
+ virtual TextServer::Hinting get_hinting() const = 0;
+
+ virtual void set_distance_field_hint(bool p_distance_field) = 0;
+ virtual bool get_distance_field_hint() const = 0;
+
+ virtual void set_force_autohinter(bool p_enabeld) = 0;
+ virtual bool get_force_autohinter() const = 0;
+
+ virtual bool has_outline() const = 0;
+ virtual float get_base_size() const = 0;
+
+ virtual bool is_lang_supported(const String &p_lang) const { return false; };
+ virtual bool is_script_supported(uint32_t p_script) const { return false; };
+
+ virtual bool has_char(char32_t p_char) const = 0;
+ virtual String get_supported_chars() const = 0;
+ virtual float get_font_scale(int p_size) const { return 1.0f; };
+
+ virtual hb_font_t *get_hb_handle(int p_size) = 0;
+ virtual uint32_t get_glyph_index(char32_t p_char, char32_t p_variation_selector) const = 0;
+ virtual Vector2 get_advance(uint32_t p_char, int p_size) const = 0;
+ virtual Vector2 get_kerning(uint32_t p_char, uint32_t p_next, int p_size) const = 0;
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0;
+
+ virtual ~FontDataAdvanced(){};
+};
+
+#endif // FONT_ADV_H
diff --git a/modules/text_server_adv/icu_data/icudata_stub.cpp b/modules/text_server_adv/icu_data/icudata_stub.cpp
new file mode 100644
index 0000000000..187001f33a
--- /dev/null
+++ b/modules/text_server_adv/icu_data/icudata_stub.cpp
@@ -0,0 +1,63 @@
+/*************************************************************************/
+/* icudata_stub.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "unicode/udata.h"
+#include "unicode/utypes.h"
+#include "unicode/uversion.h"
+
+typedef struct {
+ uint16_t header_size;
+ uint8_t magic_1, magic_2;
+ UDataInfo info;
+ char padding[8];
+ uint32_t count, reserved;
+ int fake_name_and_data[4];
+} ICU_data_header;
+
+extern "C" U_EXPORT const ICU_data_header U_ICUDATA_ENTRY_POINT = {
+ 32,
+ 0xDA, 0x27,
+ { sizeof(UDataInfo),
+ 0,
+#if U_IS_BIG_ENDIAN
+ 1,
+#else
+ 0,
+#endif
+ U_CHARSET_FAMILY,
+ sizeof(UChar),
+ 0,
+ { 0x54, 0x6F, 0x43, 0x50 },
+ { 1, 0, 0, 0 },
+ { 0, 0, 0, 0 } },
+ { 0, 0, 0, 0, 0, 0, 0, 0 },
+ 0, 0,
+ { 0, 0, 0, 0 }
+};
diff --git a/modules/text_server_adv/register_types.cpp b/modules/text_server_adv/register_types.cpp
new file mode 100644
index 0000000000..abefa83b9b
--- /dev/null
+++ b/modules/text_server_adv/register_types.cpp
@@ -0,0 +1,43 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "text_server_adv.h"
+
+void preregister_text_server_adv_types() {
+ TextServerAdvanced::register_server();
+}
+
+void register_text_server_adv_types() {
+}
+
+void unregister_text_server_adv_types() {
+}
diff --git a/modules/text_server_adv/register_types.h b/modules/text_server_adv/register_types.h
new file mode 100644
index 0000000000..ddd1190f40
--- /dev/null
+++ b/modules/text_server_adv/register_types.h
@@ -0,0 +1,40 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEXT_SERVER_ADV_REGISTER_TYPES_H
+#define TEXT_SERVER_ADV_REGISTER_TYPES_H
+
+#define MODULE_TEXT_SERVER_ADV_HAS_PREREGISTER
+
+void preregister_text_server_adv_types();
+void register_text_server_adv_types();
+void unregister_text_server_adv_types();
+
+#endif // TEXT_SERVER_ADV_REGISTER_TYPES_H
diff --git a/modules/text_server_adv/script_iterator.cpp b/modules/text_server_adv/script_iterator.cpp
new file mode 100644
index 0000000000..8f23bb9e02
--- /dev/null
+++ b/modules/text_server_adv/script_iterator.cpp
@@ -0,0 +1,110 @@
+/*************************************************************************/
+/* script_iterator.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "script_iterator.h"
+
+bool ScriptIterator::same_script(int32_t p_script_one, int32_t p_script_two) {
+ return p_script_one <= USCRIPT_INHERITED || p_script_two <= USCRIPT_INHERITED || p_script_one == p_script_two;
+}
+
+ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length) {
+ struct ParenStackEntry {
+ int pair_index;
+ UScriptCode script_code;
+ };
+
+ if (p_start >= p_length) {
+ p_start = p_length - 1;
+ }
+
+ if (p_start < 0) {
+ p_start = 0;
+ }
+
+ ParenStackEntry paren_stack[128];
+
+ int script_start;
+ int script_end = p_start;
+ UScriptCode script_code;
+ int paren_sp = -1;
+ int start_sp = paren_sp;
+ UErrorCode err = U_ZERO_ERROR;
+ const char32_t *str = p_string.ptr();
+
+ do {
+ script_code = USCRIPT_COMMON;
+ for (script_start = script_end; script_end < p_length; script_end++) {
+ UChar32 ch = str[script_end];
+ UScriptCode sc = uscript_getScript(ch, &err);
+ if (U_FAILURE(err)) {
+ ERR_FAIL_MSG(u_errorName(err));
+ }
+ if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) != U_BPT_NONE) {
+ if (u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_OPEN) {
+ paren_stack[++paren_sp].pair_index = ch;
+ paren_stack[paren_sp].script_code = script_code;
+ } else if (paren_sp >= 0) {
+ UChar32 paired_ch = u_getBidiPairedBracket(ch);
+ while (paren_sp >= 0 && paren_stack[paren_sp].pair_index != paired_ch) {
+ paren_sp -= 1;
+ }
+ if (paren_sp < start_sp)
+ start_sp = paren_sp;
+ if (paren_sp >= 0)
+ sc = paren_stack[paren_sp].script_code;
+ }
+ }
+
+ if (same_script(script_code, sc)) {
+ if (script_code <= USCRIPT_INHERITED && sc > USCRIPT_INHERITED) {
+ script_code = sc;
+ while (start_sp < paren_sp) {
+ paren_stack[++start_sp].script_code = script_code;
+ }
+ }
+ if ((u_getIntPropertyValue(ch, UCHAR_BIDI_PAIRED_BRACKET_TYPE) == U_BPT_CLOSE) && paren_sp >= 0) {
+ paren_sp -= 1;
+ if (start_sp >= 0) {
+ start_sp -= 1;
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ ScriptRange rng;
+ rng.script = hb_icu_script_to_script(script_code);
+ rng.start = script_start;
+ rng.end = script_end;
+
+ script_ranges.push_back(rng);
+ } while (script_end < p_length);
+}
diff --git a/modules/text_server_adv/script_iterator.h b/modules/text_server_adv/script_iterator.h
new file mode 100644
index 0000000000..ad476f7c75
--- /dev/null
+++ b/modules/text_server_adv/script_iterator.h
@@ -0,0 +1,61 @@
+/*************************************************************************/
+/* script_iterator.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 SCRIPT_ITERATOR_H
+#define SCRIPT_ITERATOR_H
+
+#include "servers/text_server.h"
+
+#include <unicode/uchar.h>
+#include <unicode/uloc.h>
+#include <unicode/uscript.h>
+#include <unicode/ustring.h>
+#include <unicode/utypes.h>
+
+#include <hb-icu.h>
+#include <hb.h>
+
+class ScriptIterator {
+public:
+ struct ScriptRange {
+ int start;
+ int end;
+ hb_script_t script;
+ };
+ Vector<ScriptRange> script_ranges;
+
+private:
+ static bool same_script(int32_t p_script_one, int32_t p_script_two);
+
+public:
+ ScriptIterator(const String &p_string, int p_start, int p_length);
+};
+
+#endif //SCRIPT_ITERATOR_H
diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp
new file mode 100644
index 0000000000..8b05611089
--- /dev/null
+++ b/modules/text_server_adv/text_server_adv.cpp
@@ -0,0 +1,2571 @@
+/*************************************************************************/
+/* text_server_adv.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "text_server_adv.h"
+#include "bitmap_font_adv.h"
+#include "dynamic_font_adv.h"
+
+#include "core/string/translation.h"
+
+#ifdef ICU_STATIC_DATA
+#include "thirdparty/icu4c/icudata.gen.h"
+#endif
+
+_FORCE_INLINE_ bool is_ain(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AIN;
+}
+
+_FORCE_INLINE_ bool is_alef(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_ALEF;
+}
+
+_FORCE_INLINE_ bool is_beh(char32_t p_chr) {
+ int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
+ return (prop == U_JG_BEH) || (prop == U_JG_NOON) || (prop == U_JG_AFRICAN_NOON) || (prop == U_JG_NYA) || (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH);
+}
+
+_FORCE_INLINE_ bool is_dal(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_DAL;
+}
+
+_FORCE_INLINE_ bool is_feh(char32_t p_chr) {
+ return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_FEH) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_FEH);
+}
+
+_FORCE_INLINE_ bool is_gaf(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_GAF;
+}
+
+_FORCE_INLINE_ bool is_heh(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_HEH;
+}
+
+_FORCE_INLINE_ bool is_kaf(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_KAF;
+}
+
+_FORCE_INLINE_ bool is_lam(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_LAM;
+}
+
+_FORCE_INLINE_ bool is_qaf(char32_t p_chr) {
+ return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_QAF) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_QAF);
+}
+
+_FORCE_INLINE_ bool is_reh(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_REH;
+}
+
+_FORCE_INLINE_ bool is_seen_sad(char32_t p_chr) {
+ return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SAD) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SEEN);
+}
+
+_FORCE_INLINE_ bool is_tah(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TAH;
+}
+
+_FORCE_INLINE_ bool is_teh_marbuta(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TEH_MARBUTA;
+}
+
+_FORCE_INLINE_ bool is_yeh(char32_t p_chr) {
+ int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
+ return (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH) || (prop == U_JG_YEH_BARREE) || (prop == U_JG_BURUSHASKI_YEH_BARREE) || (prop == U_JG_YEH_WITH_TAIL);
+}
+
+_FORCE_INLINE_ bool is_waw(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_WAW;
+}
+
+_FORCE_INLINE_ bool is_transparent(char32_t p_chr) {
+ return u_getIntPropertyValue(p_chr, UCHAR_JOINING_TYPE) == U_JT_TRANSPARENT;
+}
+
+_FORCE_INLINE_ bool is_ligature(char32_t p_chr, char32_t p_nchr) {
+ return (is_lam(p_chr) && is_alef(p_nchr));
+}
+
+_FORCE_INLINE_ bool is_connected_to_prev(char32_t p_chr, char32_t p_pchr) {
+ int32_t prop = u_getIntPropertyValue(p_pchr, UCHAR_JOINING_TYPE);
+ return (prop != U_JT_RIGHT_JOINING) && (prop != U_JT_NON_JOINING) ? !is_ligature(p_pchr, p_chr) : false;
+}
+
+_FORCE_INLINE_ bool is_control(char32_t p_char) {
+ return (p_char <= 0x001f) || (p_char >= 0x007f && p_char <= 0x009F);
+}
+
+_FORCE_INLINE_ bool is_whitespace(char32_t p_char) {
+ return (p_char == 0x0020) || (p_char == 0x00A0) || (p_char == 0x1680) || (p_char >= 0x2000 && p_char <= 0x200a) || (p_char == 0x202f) || (p_char == 0x205f) || (p_char == 0x3000) || (p_char == 0x2028) || (p_char == 0x2029) || (p_char >= 0x0009 && p_char <= 0x000d) || (p_char == 0x0085);
+}
+
+_FORCE_INLINE_ bool is_linebreak(char32_t p_char) {
+ return (p_char >= 0x000a && p_char <= 0x000d) || (p_char == 0x0085) || (p_char == 0x2028) || (p_char == 0x2029);
+}
+
+/*************************************************************************/
+
+String TextServerAdvanced::interface_name = "ICU / HarfBuzz / Graphite";
+uint32_t TextServerAdvanced::interface_features = FEATURE_BIDI_LAYOUT | FEATURE_VERTICAL_LAYOUT | FEATURE_SHAPING | FEATURE_KASHIDA_JUSTIFICATION | FEATURE_BREAK_ITERATORS | FEATURE_USE_SUPPORT_DATA | FEATURE_FONT_VARIABLE;
+
+bool TextServerAdvanced::has_feature(Feature p_feature) {
+ return (interface_features & p_feature) == p_feature;
+}
+
+String TextServerAdvanced::get_name() const {
+ return interface_name;
+}
+
+void TextServerAdvanced::free(RID p_rid) {
+ _THREAD_SAFE_METHOD_
+ if (font_owner.owns(p_rid)) {
+ FontDataAdvanced *fd = font_owner.getornull(p_rid);
+ font_owner.free(p_rid);
+ memdelete(fd);
+ } else if (shaped_owner.owns(p_rid)) {
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_rid);
+ shaped_owner.free(p_rid);
+ memdelete(sd);
+ }
+}
+
+bool TextServerAdvanced::has(RID p_rid) {
+ _THREAD_SAFE_METHOD_
+ return font_owner.owns(p_rid) || shaped_owner.owns(p_rid);
+}
+
+bool TextServerAdvanced::load_support_data(const String &p_filename) {
+ _THREAD_SAFE_METHOD_
+
+#ifdef ICU_STATIC_DATA
+ if (icu_data == nullptr) {
+ UErrorCode err = U_ZERO_ERROR;
+ u_init(&err); // Do not check for errors, since we only load part the of data.
+ icu_data = (uint8_t *)&U_ICUDATA_ENTRY_POINT;
+ }
+#else
+ if (icu_data == nullptr) {
+ String filename = (p_filename.is_empty()) ? String("res://") + _MKSTR(ICU_DATA_NAME) : p_filename;
+
+ FileAccess *f = FileAccess::open(filename, FileAccess::READ);
+ if (!f) {
+ return false;
+ }
+
+ UErrorCode err = U_ZERO_ERROR;
+
+ // ICU data found.
+ size_t len = f->get_len();
+ icu_data = (uint8_t *)memalloc(len);
+ f->get_buffer(icu_data, len);
+ f->close();
+ memdelete(f);
+
+ udata_setCommonData(icu_data, &err);
+ if (U_FAILURE(err)) {
+ memfree(icu_data);
+ icu_data = nullptr;
+ ERR_FAIL_V_MSG(false, u_errorName(err));
+ }
+
+ err = U_ZERO_ERROR;
+ u_init(&err);
+ if (U_FAILURE(err)) {
+ memfree(icu_data);
+ icu_data = nullptr;
+ ERR_FAIL_V_MSG(false, u_errorName(err));
+ }
+ }
+#endif
+ return true;
+}
+
+#ifdef TOOLS_ENABLED
+
+bool TextServerAdvanced::save_support_data(const String &p_filename) {
+ _THREAD_SAFE_METHOD_
+#ifdef ICU_STATIC_DATA
+
+ // Store data to the res file if it's available.
+ FileAccess *f = FileAccess::open(p_filename, FileAccess::WRITE);
+ if (!f) {
+ return false;
+ }
+ f->store_buffer(U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE);
+ f->close();
+ memdelete(f);
+ return true;
+
+#else
+ return false;
+#endif
+}
+
+#endif
+
+bool TextServerAdvanced::is_locale_right_to_left(const String &p_locale) {
+ String l = p_locale.get_slicec('_', 0);
+ if ((l == "ar") || (l == "dv") || (l == "he") || (l == "fa") || (l == "ff") || (l == "ku") || (l == "ur")) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+struct FeatureInfo {
+ int32_t tag;
+ String name;
+};
+
+static FeatureInfo feature_set[] = {
+ // Registred OpenType feature tags.
+ { HB_TAG('a', 'a', 'l', 't'), "access_all_alternates" },
+ { HB_TAG('a', 'b', 'v', 'f'), "above_base_forms" },
+ { HB_TAG('a', 'b', 'v', 'm'), "above_base_mark_positioning" },
+ { HB_TAG('a', 'b', 'v', 's'), "above_base_substitutions" },
+ { HB_TAG('a', 'f', 'r', 'c'), "alternative_fractions" },
+ { HB_TAG('a', 'k', 'h', 'n'), "akhands" },
+ { HB_TAG('b', 'l', 'w', 'f'), "below_base_forms" },
+ { HB_TAG('b', 'l', 'w', 'm'), "below_base_mark_positioning" },
+ { HB_TAG('b', 'l', 'w', 's'), "below_base_substitutions" },
+ { HB_TAG('c', 'a', 'l', 't'), "contextual_alternates" },
+ { HB_TAG('c', 'a', 's', 'e'), "case_sensitive_forms" },
+ { HB_TAG('c', 'c', 'm', 'p'), "glyph_composition" },
+ { HB_TAG('c', 'f', 'a', 'r'), "conjunct_form_after_ro" },
+ { HB_TAG('c', 'j', 'c', 't'), "conjunct_forms" },
+ { HB_TAG('c', 'l', 'i', 'g'), "contextual_ligatures" },
+ { HB_TAG('c', 'p', 'c', 't'), "centered_cjk_punctuation" },
+ { HB_TAG('c', 'p', 's', 'p'), "capital_spacing" },
+ { HB_TAG('c', 's', 'w', 'h'), "contextual_swash" },
+ { HB_TAG('c', 'u', 'r', 's'), "cursive_positioning" },
+ { HB_TAG('c', 'v', '0', '1'), "character_variant_01" },
+ { HB_TAG('c', 'v', '0', '2'), "character_variant_02" },
+ { HB_TAG('c', 'v', '0', '3'), "character_variant_03" },
+ { HB_TAG('c', 'v', '0', '4'), "character_variant_04" },
+ { HB_TAG('c', 'v', '0', '5'), "character_variant_05" },
+ { HB_TAG('c', 'v', '0', '6'), "character_variant_06" },
+ { HB_TAG('c', 'v', '0', '7'), "character_variant_07" },
+ { HB_TAG('c', 'v', '0', '8'), "character_variant_08" },
+ { HB_TAG('c', 'v', '0', '9'), "character_variant_09" },
+ { HB_TAG('c', 'v', '1', '0'), "character_variant_10" },
+ { HB_TAG('c', 'v', '1', '1'), "character_variant_11" },
+ { HB_TAG('c', 'v', '1', '2'), "character_variant_12" },
+ { HB_TAG('c', 'v', '1', '3'), "character_variant_13" },
+ { HB_TAG('c', 'v', '1', '4'), "character_variant_14" },
+ { HB_TAG('c', 'v', '1', '5'), "character_variant_15" },
+ { HB_TAG('c', 'v', '1', '6'), "character_variant_16" },
+ { HB_TAG('c', 'v', '1', '7'), "character_variant_17" },
+ { HB_TAG('c', 'v', '1', '8'), "character_variant_18" },
+ { HB_TAG('c', 'v', '1', '9'), "character_variant_19" },
+ { HB_TAG('c', 'v', '2', '0'), "character_variant_20" },
+ { HB_TAG('c', 'v', '2', '1'), "character_variant_21" },
+ { HB_TAG('c', 'v', '2', '2'), "character_variant_22" },
+ { HB_TAG('c', 'v', '2', '3'), "character_variant_23" },
+ { HB_TAG('c', 'v', '2', '4'), "character_variant_24" },
+ { HB_TAG('c', 'v', '2', '5'), "character_variant_25" },
+ { HB_TAG('c', 'v', '2', '6'), "character_variant_26" },
+ { HB_TAG('c', 'v', '2', '7'), "character_variant_27" },
+ { HB_TAG('c', 'v', '2', '8'), "character_variant_28" },
+ { HB_TAG('c', 'v', '2', '9'), "character_variant_29" },
+ { HB_TAG('c', 'v', '3', '0'), "character_variant_30" },
+ { HB_TAG('c', 'v', '3', '1'), "character_variant_31" },
+ { HB_TAG('c', 'v', '3', '2'), "character_variant_32" },
+ { HB_TAG('c', 'v', '3', '3'), "character_variant_33" },
+ { HB_TAG('c', 'v', '3', '4'), "character_variant_34" },
+ { HB_TAG('c', 'v', '3', '5'), "character_variant_35" },
+ { HB_TAG('c', 'v', '3', '6'), "character_variant_36" },
+ { HB_TAG('c', 'v', '3', '7'), "character_variant_37" },
+ { HB_TAG('c', 'v', '3', '8'), "character_variant_38" },
+ { HB_TAG('c', 'v', '3', '9'), "character_variant_39" },
+ { HB_TAG('c', 'v', '4', '0'), "character_variant_40" },
+ { HB_TAG('c', 'v', '4', '1'), "character_variant_41" },
+ { HB_TAG('c', 'v', '4', '2'), "character_variant_42" },
+ { HB_TAG('c', 'v', '4', '3'), "character_variant_43" },
+ { HB_TAG('c', 'v', '4', '4'), "character_variant_44" },
+ { HB_TAG('c', 'v', '4', '5'), "character_variant_45" },
+ { HB_TAG('c', 'v', '4', '6'), "character_variant_46" },
+ { HB_TAG('c', 'v', '4', '7'), "character_variant_47" },
+ { HB_TAG('c', 'v', '4', '8'), "character_variant_48" },
+ { HB_TAG('c', 'v', '4', '9'), "character_variant_49" },
+ { HB_TAG('c', 'v', '5', '0'), "character_variant_50" },
+ { HB_TAG('c', 'v', '5', '1'), "character_variant_51" },
+ { HB_TAG('c', 'v', '5', '2'), "character_variant_52" },
+ { HB_TAG('c', 'v', '5', '3'), "character_variant_53" },
+ { HB_TAG('c', 'v', '5', '4'), "character_variant_54" },
+ { HB_TAG('c', 'v', '5', '5'), "character_variant_55" },
+ { HB_TAG('c', 'v', '5', '6'), "character_variant_56" },
+ { HB_TAG('c', 'v', '5', '7'), "character_variant_57" },
+ { HB_TAG('c', 'v', '5', '8'), "character_variant_58" },
+ { HB_TAG('c', 'v', '5', '9'), "character_variant_59" },
+ { HB_TAG('c', 'v', '6', '0'), "character_variant_60" },
+ { HB_TAG('c', 'v', '6', '1'), "character_variant_61" },
+ { HB_TAG('c', 'v', '6', '2'), "character_variant_62" },
+ { HB_TAG('c', 'v', '6', '3'), "character_variant_63" },
+ { HB_TAG('c', 'v', '6', '4'), "character_variant_64" },
+ { HB_TAG('c', 'v', '6', '5'), "character_variant_65" },
+ { HB_TAG('c', 'v', '6', '6'), "character_variant_66" },
+ { HB_TAG('c', 'v', '6', '7'), "character_variant_67" },
+ { HB_TAG('c', 'v', '6', '8'), "character_variant_68" },
+ { HB_TAG('c', 'v', '6', '9'), "character_variant_69" },
+ { HB_TAG('c', 'v', '7', '0'), "character_variant_70" },
+ { HB_TAG('c', 'v', '7', '1'), "character_variant_71" },
+ { HB_TAG('c', 'v', '7', '2'), "character_variant_72" },
+ { HB_TAG('c', 'v', '7', '3'), "character_variant_73" },
+ { HB_TAG('c', 'v', '7', '4'), "character_variant_74" },
+ { HB_TAG('c', 'v', '7', '5'), "character_variant_75" },
+ { HB_TAG('c', 'v', '7', '6'), "character_variant_76" },
+ { HB_TAG('c', 'v', '7', '7'), "character_variant_77" },
+ { HB_TAG('c', 'v', '7', '8'), "character_variant_78" },
+ { HB_TAG('c', 'v', '7', '9'), "character_variant_79" },
+ { HB_TAG('c', 'v', '8', '0'), "character_variant_80" },
+ { HB_TAG('c', 'v', '8', '1'), "character_variant_81" },
+ { HB_TAG('c', 'v', '8', '2'), "character_variant_82" },
+ { HB_TAG('c', 'v', '8', '3'), "character_variant_83" },
+ { HB_TAG('c', 'v', '8', '4'), "character_variant_84" },
+ { HB_TAG('c', 'v', '8', '5'), "character_variant_85" },
+ { HB_TAG('c', 'v', '8', '6'), "character_variant_86" },
+ { HB_TAG('c', 'v', '8', '7'), "character_variant_87" },
+ { HB_TAG('c', 'v', '8', '8'), "character_variant_88" },
+ { HB_TAG('c', 'v', '8', '9'), "character_variant_89" },
+ { HB_TAG('c', 'v', '9', '0'), "character_variant_90" },
+ { HB_TAG('c', 'v', '9', '1'), "character_variant_91" },
+ { HB_TAG('c', 'v', '9', '2'), "character_variant_92" },
+ { HB_TAG('c', 'v', '9', '3'), "character_variant_93" },
+ { HB_TAG('c', 'v', '9', '4'), "character_variant_94" },
+ { HB_TAG('c', 'v', '9', '5'), "character_variant_95" },
+ { HB_TAG('c', 'v', '9', '6'), "character_variant_96" },
+ { HB_TAG('c', 'v', '9', '7'), "character_variant_97" },
+ { HB_TAG('c', 'v', '9', '8'), "character_variant_98" },
+ { HB_TAG('c', 'v', '9', '9'), "character_variant_99" },
+ { HB_TAG('c', '2', 'p', 'c'), "petite_capitals_from_capitals" },
+ { HB_TAG('c', '2', 's', 'c'), "small_capitals_from_capitals" },
+ { HB_TAG('d', 'i', 's', 't'), "distances" },
+ { HB_TAG('d', 'l', 'i', 'g'), "discretionary_ligatures" },
+ { HB_TAG('d', 'n', 'o', 'm'), "denominators" },
+ { HB_TAG('d', 't', 'l', 's'), "dotless_forms" },
+ { HB_TAG('e', 'x', 'p', 't'), "expert_forms" },
+ { HB_TAG('f', 'a', 'l', 't'), "final_glyph_on_line_alternates" },
+ { HB_TAG('f', 'i', 'n', '2'), "terminal_forms_2" },
+ { HB_TAG('f', 'i', 'n', '3'), "terminal_forms_3" },
+ { HB_TAG('f', 'i', 'n', 'a'), "terminal_forms" },
+ { HB_TAG('f', 'l', 'a', 'c'), "flattened_accent_forms" },
+ { HB_TAG('f', 'r', 'a', 'c'), "fractions" },
+ { HB_TAG('f', 'w', 'i', 'd'), "full_widths" },
+ { HB_TAG('h', 'a', 'l', 'f'), "half_forms" },
+ { HB_TAG('h', 'a', 'l', 'n'), "halant_forms" },
+ { HB_TAG('h', 'a', 'l', 't'), "alternate_half_widths" },
+ { HB_TAG('h', 'i', 's', 't'), "historical_forms" },
+ { HB_TAG('h', 'k', 'n', 'a'), "horizontal_kana_alternates" },
+ { HB_TAG('h', 'l', 'i', 'g'), "historical_ligatures" },
+ { HB_TAG('h', 'n', 'g', 'l'), "hangul" },
+ { HB_TAG('h', 'o', 'j', 'o'), "hojo_kanji_forms" },
+ { HB_TAG('h', 'w', 'i', 'd'), "half_widths" },
+ { HB_TAG('i', 'n', 'i', 't'), "initial_forms" },
+ { HB_TAG('i', 's', 'o', 'l'), "isolated_forms" },
+ { HB_TAG('i', 't', 'a', 'l'), "italics" },
+ { HB_TAG('j', 'a', 'l', 't'), "justification_alternates" },
+ { HB_TAG('j', 'p', '7', '8'), "jis78_forms" },
+ { HB_TAG('j', 'p', '8', '3'), "jis83_forms" },
+ { HB_TAG('j', 'p', '9', '0'), "jis90_forms" },
+ { HB_TAG('j', 'p', '0', '4'), "jis2004_forms" },
+ { HB_TAG('k', 'e', 'r', 'n'), "kerning" },
+ { HB_TAG('l', 'f', 'b', 'd'), "left_bounds" },
+ { HB_TAG('l', 'i', 'g', 'a'), "standard_ligatures" },
+ { HB_TAG('l', 'j', 'm', 'o'), "leading_jamo_forms" },
+ { HB_TAG('l', 'n', 'u', 'm'), "lining_figures" },
+ { HB_TAG('l', 'o', 'c', 'l'), "localized_forms" },
+ { HB_TAG('l', 't', 'r', 'a'), "left_to_right_alternates" },
+ { HB_TAG('l', 't', 'r', 'm'), "left_to_right_mirrored_forms" },
+ { HB_TAG('m', 'a', 'r', 'k'), "mark_positioning" },
+ { HB_TAG('m', 'e', 'd', '2'), "medial_forms_2" },
+ { HB_TAG('m', 'e', 'd', 'i'), "medial_forms" },
+ { HB_TAG('m', 'g', 'r', 'k'), "mathematical_greek" },
+ { HB_TAG('m', 'k', 'm', 'k'), "mark_to_mark_positioning" },
+ { HB_TAG('m', 's', 'e', 't'), "mark_positioning_via_substitution" },
+ { HB_TAG('n', 'a', 'l', 't'), "alternate_annotation_forms" },
+ { HB_TAG('n', 'l', 'c', 'k'), "nlc_kanji_forms" },
+ { HB_TAG('n', 'u', 'k', 't'), "nukta_forms" },
+ { HB_TAG('n', 'u', 'm', 'r'), "numerators" },
+ { HB_TAG('o', 'n', 'u', 'm'), "oldstyle_figures" },
+ { HB_TAG('o', 'p', 'b', 'd'), "optical_bounds" },
+ { HB_TAG('o', 'r', 'd', 'n'), "ordinals" },
+ { HB_TAG('o', 'r', 'n', 'm'), "ornaments" },
+ { HB_TAG('p', 'a', 'l', 't'), "proportional_alternate_widths" },
+ { HB_TAG('p', 'c', 'a', 'p'), "petite_capitals" },
+ { HB_TAG('p', 'k', 'n', 'a'), "proportional_kana" },
+ { HB_TAG('p', 'n', 'u', 'm'), "proportional_figures" },
+ { HB_TAG('p', 'r', 'e', 'f'), "pre_base_forms" },
+ { HB_TAG('p', 'r', 'e', 's'), "pre_base_substitutions" },
+ { HB_TAG('p', 's', 't', 'f'), "post_base_forms" },
+ { HB_TAG('p', 's', 't', 's'), "post_base_substitutions" },
+ { HB_TAG('p', 'w', 'i', 'd'), "proportional_widths" },
+ { HB_TAG('q', 'w', 'i', 'd'), "quarter_widths" },
+ { HB_TAG('r', 'a', 'n', 'd'), "randomize" },
+ { HB_TAG('r', 'c', 'l', 't'), "required_contextual_alternates" },
+ { HB_TAG('r', 'k', 'r', 'f'), "rakar_forms" },
+ { HB_TAG('r', 'l', 'i', 'g'), "required_ligatures" },
+ { HB_TAG('r', 'p', 'h', 'f'), "reph_forms" },
+ { HB_TAG('r', 't', 'b', 'd'), "right_bounds" },
+ { HB_TAG('r', 't', 'l', 'a'), "right_to_left_alternates" },
+ { HB_TAG('r', 't', 'l', 'm'), "right_to_left_mirrored_forms" },
+ { HB_TAG('r', 'u', 'b', 'y'), "ruby_notation_forms" },
+ { HB_TAG('r', 'v', 'r', 'n'), "required_variation_alternates" },
+ { HB_TAG('s', 'a', 'l', 't'), "stylistic_alternates" },
+ { HB_TAG('s', 'i', 'n', 'f'), "scientific_inferiors" },
+ { HB_TAG('s', 'i', 'z', 'e'), "optical_size" },
+ { HB_TAG('s', 'm', 'c', 'p'), "small_capitals" },
+ { HB_TAG('s', 'm', 'p', 'l'), "simplified_forms" },
+ { HB_TAG('s', 's', '0', '1'), "stylistic_set_01" },
+ { HB_TAG('s', 's', '0', '2'), "stylistic_set_02" },
+ { HB_TAG('s', 's', '0', '3'), "stylistic_set_03" },
+ { HB_TAG('s', 's', '0', '4'), "stylistic_set_04" },
+ { HB_TAG('s', 's', '0', '5'), "stylistic_set_05" },
+ { HB_TAG('s', 's', '0', '6'), "stylistic_set_06" },
+ { HB_TAG('s', 's', '0', '7'), "stylistic_set_07" },
+ { HB_TAG('s', 's', '0', '8'), "stylistic_set_08" },
+ { HB_TAG('s', 's', '0', '9'), "stylistic_set_09" },
+ { HB_TAG('s', 's', '1', '0'), "stylistic_set_10" },
+ { HB_TAG('s', 's', '1', '1'), "stylistic_set_11" },
+ { HB_TAG('s', 's', '1', '2'), "stylistic_set_12" },
+ { HB_TAG('s', 's', '1', '3'), "stylistic_set_13" },
+ { HB_TAG('s', 's', '1', '4'), "stylistic_set_14" },
+ { HB_TAG('s', 's', '1', '5'), "stylistic_set_15" },
+ { HB_TAG('s', 's', '1', '6'), "stylistic_set_16" },
+ { HB_TAG('s', 's', '1', '7'), "stylistic_set_17" },
+ { HB_TAG('s', 's', '1', '8'), "stylistic_set_18" },
+ { HB_TAG('s', 's', '1', '9'), "stylistic_set_19" },
+ { HB_TAG('s', 's', '2', '0'), "stylistic_set_20" },
+ { HB_TAG('s', 's', 't', 'y'), "math_script_style_alternates" },
+ { HB_TAG('s', 't', 'c', 'h'), "stretching_glyph_decomposition" },
+ { HB_TAG('s', 'u', 'b', 's'), "subscript" },
+ { HB_TAG('s', 'u', 'p', 's'), "superscript" },
+ { HB_TAG('s', 'w', 's', 'h'), "swash" },
+ { HB_TAG('t', 'i', 't', 'l'), "titling" },
+ { HB_TAG('t', 'j', 'm', 'o'), "trailing_jamo_forms" },
+ { HB_TAG('t', 'n', 'a', 'm'), "traditional_name_forms" },
+ { HB_TAG('t', 'n', 'u', 'm'), "tabular_figures" },
+ { HB_TAG('t', 'r', 'a', 'd'), "traditional_forms" },
+ { HB_TAG('t', 'w', 'i', 'd'), "third_widths" },
+ { HB_TAG('u', 'n', 'i', 'c'), "unicase" },
+ { HB_TAG('v', 'a', 'l', 't'), "alternate_vertical_metrics" },
+ { HB_TAG('v', 'a', 't', 'u'), "vattu_variants" },
+ { HB_TAG('v', 'e', 'r', 't'), "vertical_writing" },
+ { HB_TAG('v', 'h', 'a', 'l'), "alternate_vertical_half_metrics" },
+ { HB_TAG('v', 'j', 'm', 'o'), "vowel_jamo_forms" },
+ { HB_TAG('v', 'k', 'n', 'a'), "vertical_kana_alternates" },
+ { HB_TAG('v', 'k', 'r', 'n'), "vertical_kerning" },
+ { HB_TAG('v', 'p', 'a', 'l'), "proportional_alternate_vertical_metrics" },
+ { HB_TAG('v', 'r', 't', '2'), "vertical_alternates_and_rotation" },
+ { HB_TAG('v', 'r', 't', 'r'), "vertical_alternates_for_rotation" },
+ { HB_TAG('z', 'e', 'r', 'o'), "slashed_zero" },
+ // Registred OpenType variation tags.
+ { HB_TAG('i', 't', 'a', 'l'), "italic" },
+ { HB_TAG('o', 'p', 's', 'z'), "optical_size" },
+ { HB_TAG('s', 'l', 'n', 't'), "slant" },
+ { HB_TAG('w', 'd', 't', 'h'), "width" },
+ { HB_TAG('w', 'g', 'h', 't'), "weight" },
+ { 0, String() },
+};
+
+int32_t TextServerAdvanced::name_to_tag(const String &p_name) {
+ for (int i = 0; feature_set[i].tag != 0; i++) {
+ if (feature_set[i].name == p_name) {
+ return feature_set[i].tag;
+ }
+ }
+
+ // No readable name, use tag string.
+ return hb_tag_from_string(p_name.replace("custom_", "").ascii().get_data(), -1);
+}
+
+String TextServerAdvanced::tag_to_name(int32_t p_tag) {
+ for (int i = 0; feature_set[i].tag != 0; i++) {
+ if (feature_set[i].tag == p_tag) {
+ return feature_set[i].name;
+ }
+ }
+
+ // No readable name, use tag string.
+ char name[5];
+ memset(name, 0, 5);
+ hb_tag_to_string(p_tag, name);
+ return String("custom_") + String(name);
+}
+
+/*************************************************************************/
+/* Font interface */
+/*************************************************************************/
+
+RID TextServerAdvanced::create_font_system(const String &p_name, int p_base_size) {
+ ERR_FAIL_V_MSG(RID(), "System fonts are not supported by this text server.");
+}
+
+RID TextServerAdvanced::create_font_resource(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = nullptr;
+ if (p_filename.get_extension() == "ttf" || p_filename.get_extension() == "otf" || p_filename.get_extension() == "woff") {
+ fd = memnew(DynamicFontDataAdvanced);
+ } else if (p_filename.get_extension() == "fnt" || p_filename.get_extension() == "font") {
+ fd = memnew(BitmapFontDataAdvanced);
+ } else {
+ return RID();
+ }
+
+ Error err = fd->load_from_file(p_filename, p_base_size);
+ if (err != OK) {
+ memdelete(fd);
+ return RID();
+ }
+
+ return font_owner.make_rid(fd);
+}
+
+RID TextServerAdvanced::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = nullptr;
+ if (p_type == "ttf" || p_type == "otf" || p_type == "woff") {
+ fd = memnew(DynamicFontDataAdvanced);
+ } else if (p_type == "fnt" || p_type == "font") {
+ fd = memnew(BitmapFontDataAdvanced);
+ } else {
+ return RID();
+ }
+
+ Error err = fd->load_from_memory(p_data, p_size, p_base_size);
+ if (err != OK) {
+ memdelete(fd);
+ return RID();
+ }
+
+ return font_owner.make_rid(fd);
+}
+
+float TextServerAdvanced::font_get_height(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_height(p_size);
+}
+
+float TextServerAdvanced::font_get_ascent(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_ascent(p_size);
+}
+
+float TextServerAdvanced::font_get_descent(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_descent(p_size);
+}
+
+float TextServerAdvanced::font_get_underline_position(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_underline_position(p_size);
+}
+
+float TextServerAdvanced::font_get_underline_thickness(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_underline_thickness(p_size);
+}
+
+void TextServerAdvanced::font_set_antialiased(RID p_font, bool p_antialiased) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_antialiased(p_antialiased);
+}
+
+Dictionary TextServerAdvanced::font_get_feature_list(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Dictionary());
+ return fd->get_feature_list();
+}
+
+bool TextServerAdvanced::font_get_antialiased(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_antialiased();
+}
+
+Dictionary TextServerAdvanced::font_get_variation_list(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Dictionary());
+ return fd->get_variation_list();
+}
+
+void TextServerAdvanced::font_set_variation(RID p_font, const String &p_name, double p_value) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_variation(p_name, p_value);
+}
+
+double TextServerAdvanced::font_get_variation(RID p_font, const String &p_name) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0);
+ return fd->get_variation(p_name);
+}
+
+void TextServerAdvanced::font_set_distance_field_hint(RID p_font, bool p_distance_field) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_distance_field_hint(p_distance_field);
+}
+
+bool TextServerAdvanced::font_get_distance_field_hint(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_distance_field_hint();
+}
+
+void TextServerAdvanced::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_hinting(p_hinting);
+}
+
+TextServer::Hinting TextServerAdvanced::font_get_hinting(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, TextServer::HINTING_NONE);
+ return fd->get_hinting();
+}
+
+void TextServerAdvanced::font_set_force_autohinter(RID p_font, bool p_enabeld) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_force_autohinter(p_enabeld);
+}
+
+bool TextServerAdvanced::font_get_force_autohinter(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_force_autohinter();
+}
+
+bool TextServerAdvanced::font_has_char(RID p_font, char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->has_char(p_char);
+}
+
+String TextServerAdvanced::font_get_supported_chars(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, String());
+ return fd->get_supported_chars();
+}
+
+bool TextServerAdvanced::font_has_outline(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->has_outline();
+}
+
+float TextServerAdvanced::font_get_base_size(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_base_size();
+}
+
+bool TextServerAdvanced::font_is_language_supported(RID p_font, const String &p_language) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ if (fd->lang_support_overrides.has(p_language)) {
+ return fd->lang_support_overrides[p_language];
+ } else {
+ Vector<String> tags = p_language.replace("-", "_").split("_");
+ if (tags.size() > 0) {
+ if (fd->lang_support_overrides.has(tags[0])) {
+ return fd->lang_support_overrides[tags[0]];
+ }
+ }
+ return fd->is_lang_supported(p_language);
+ }
+}
+
+void TextServerAdvanced::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->lang_support_overrides[p_language] = p_supported;
+}
+
+bool TextServerAdvanced::font_get_language_support_override(RID p_font, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->lang_support_overrides[p_language];
+}
+
+void TextServerAdvanced::font_remove_language_support_override(RID p_font, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->lang_support_overrides.erase(p_language);
+}
+
+Vector<String> TextServerAdvanced::font_get_language_support_overrides(RID p_font) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector<String>());
+ Vector<String> ret;
+ for (Map<String, bool>::Element *E = fd->lang_support_overrides.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+ return ret;
+}
+
+bool TextServerAdvanced::font_is_script_supported(RID p_font, const String &p_script) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ if (fd->script_support_overrides.has(p_script)) {
+ return fd->script_support_overrides[p_script];
+ } else {
+ hb_script_t scr = hb_script_from_string(p_script.ascii().get_data(), -1);
+ return fd->is_script_supported(scr);
+ }
+}
+
+void TextServerAdvanced::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->script_support_overrides[p_script] = p_supported;
+}
+
+bool TextServerAdvanced::font_get_script_support_override(RID p_font, const String &p_script) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->script_support_overrides[p_script];
+}
+
+void TextServerAdvanced::font_remove_script_support_override(RID p_font, const String &p_script) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->script_support_overrides.erase(p_script);
+}
+
+Vector<String> TextServerAdvanced::font_get_script_support_overrides(RID p_font) {
+ _THREAD_SAFE_METHOD_
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector<String>());
+ Vector<String> ret;
+ for (Map<String, bool>::Element *E = fd->script_support_overrides.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+ return ret;
+}
+
+uint32_t TextServerAdvanced::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0);
+ return fd->get_glyph_index(p_char, p_variation_selector);
+}
+
+Vector2 TextServerAdvanced::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->get_advance(p_index, p_size);
+}
+
+Vector2 TextServerAdvanced::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->get_kerning(p_index_a, p_index_b, p_size);
+}
+
+Vector2 TextServerAdvanced::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->draw_glyph(p_canvas, p_size, p_pos, p_index, p_color);
+}
+
+Vector2 TextServerAdvanced::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataAdvanced *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->draw_glyph_outline(p_canvas, p_size, p_outline_size, p_pos, p_index, p_color);
+}
+
+float TextServerAdvanced::font_get_oversampling() const {
+ return oversampling;
+}
+
+void TextServerAdvanced::font_set_oversampling(float p_oversampling) {
+ _THREAD_SAFE_METHOD_
+ if (oversampling != p_oversampling) {
+ oversampling = p_oversampling;
+ List<RID> fonts;
+ font_owner.get_owned_list(&fonts);
+ for (List<RID>::Element *E = fonts.front(); E; E = E->next()) {
+ font_owner.getornull(E->get())->clear_cache();
+ }
+
+ List<RID> text_bufs;
+ shaped_owner.get_owned_list(&text_bufs);
+ for (List<RID>::Element *E = text_bufs.front(); E; E = E->next()) {
+ invalidate(shaped_owner.getornull(E->get()));
+ }
+ }
+}
+
+Vector<String> TextServerAdvanced::get_system_fonts() const {
+ return Vector<String>();
+}
+
+/*************************************************************************/
+/* Shaped text buffer interface */
+/*************************************************************************/
+
+int TextServerAdvanced::_convert_pos(const ShapedTextDataAdvanced *p_sd, int p_pos) const {
+ int32_t limit = p_pos;
+ if (p_sd->text.length() != p_sd->utf16.length()) {
+ const UChar *data = p_sd->utf16.ptr();
+ for (int i = 0; i < p_pos; i++) {
+ if (U16_IS_LEAD(data[i])) {
+ limit--;
+ }
+ }
+ }
+ return limit;
+}
+
+int TextServerAdvanced::_convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int p_pos) const {
+ int32_t limit = p_pos;
+ if (p_sd->text.length() != p_sd->utf16.length()) {
+ for (int i = 0; i < p_pos; i++) {
+ if (p_sd->text[i] > 0xFFFF) {
+ limit++;
+ }
+ }
+ }
+ return limit;
+}
+
+void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced *p_shaped) {
+ p_shaped->valid = false;
+ p_shaped->sort_valid = false;
+ p_shaped->line_breaks_valid = false;
+ p_shaped->justification_ops_valid = false;
+ p_shaped->ascent = 0.f;
+ p_shaped->descent = 0.f;
+ p_shaped->width = 0.f;
+ p_shaped->upos = 0.f;
+ p_shaped->uthk = 0.f;
+ p_shaped->glyphs.clear();
+ p_shaped->glyphs_logical.clear();
+ p_shaped->utf16 = Char16String();
+ if (p_shaped->script_iter != nullptr) {
+ memdelete(p_shaped->script_iter);
+ p_shaped->script_iter = nullptr;
+ }
+ for (int i = 0; i < p_shaped->bidi_iter.size(); i++) {
+ ubidi_close(p_shaped->bidi_iter[i]);
+ }
+ p_shaped->bidi_iter.clear();
+}
+
+void TextServerAdvanced::full_copy(ShapedTextDataAdvanced *p_shaped) {
+ ShapedTextDataAdvanced *parent = shaped_owner.getornull(p_shaped->parent);
+
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = parent->objects.front(); E; E = E->next()) {
+ if (E->get().pos >= p_shaped->start && E->get().pos < p_shaped->end) {
+ p_shaped->objects[E->key()] = E->get();
+ }
+ }
+
+ for (int k = 0; k < parent->spans.size(); k++) {
+ ShapedTextDataAdvanced::Span span = parent->spans[k];
+ if (span.start >= p_shaped->end || span.end <= p_shaped->start) {
+ continue;
+ }
+ span.start = MAX(p_shaped->start, span.start);
+ span.end = MIN(p_shaped->end, span.end);
+ p_shaped->spans.push_back(span);
+ }
+
+ p_shaped->parent = RID();
+}
+
+RID TextServerAdvanced::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = memnew(ShapedTextDataAdvanced);
+ sd->hb_buffer = hb_buffer_create();
+ sd->direction = p_direction;
+ sd->orientation = p_orientation;
+ return shaped_owner.make_rid(sd);
+}
+
+void TextServerAdvanced::shaped_text_clear(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+
+ sd->parent = RID();
+ sd->start = 0;
+ sd->end = 0;
+ sd->text = String();
+ sd->spans.clear();
+ sd->objects.clear();
+ sd->bidi_override.clear();
+ invalidate(sd);
+}
+
+void TextServerAdvanced::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+
+ if (sd->direction != p_direction) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->direction = p_direction;
+ invalidate(sd);
+ }
+}
+
+TextServer::Direction TextServerAdvanced::shaped_text_get_direction(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, TextServer::DIRECTION_LTR);
+ return sd->direction;
+}
+
+void TextServerAdvanced::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->bidi_override = p_override;
+ invalidate(sd);
+}
+
+void TextServerAdvanced::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->orientation != p_orientation) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->orientation = p_orientation;
+ invalidate(sd);
+ }
+}
+
+void TextServerAdvanced::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ ERR_FAIL_COND(sd->parent != RID());
+ if (sd->preserve_invalid != p_enabled) {
+ sd->preserve_invalid = p_enabled;
+ invalidate(sd);
+ }
+}
+
+bool TextServerAdvanced::shaped_text_get_preserve_invalid(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->preserve_invalid;
+}
+
+void TextServerAdvanced::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->preserve_control != p_enabled) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->preserve_control = p_enabled;
+ invalidate(sd);
+ }
+}
+
+bool TextServerAdvanced::shaped_text_get_preserve_control(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->preserve_control;
+}
+
+TextServer::Orientation TextServerAdvanced::shaped_text_get_orientation(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL);
+ return sd->orientation;
+}
+
+bool TextServerAdvanced::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(p_size <= 0, false);
+
+ if (p_text.is_empty()) {
+ return true;
+ }
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+
+ ShapedTextDataAdvanced::Span span;
+ span.start = sd->text.length();
+ span.end = span.start + p_text.length();
+ span.fonts = p_fonts; // Do not pre-sort, spans will be divided to subruns later.
+ span.font_size = p_size;
+ span.language = p_language;
+ span.features = p_opentype_features;
+
+ sd->spans.push_back(span);
+ sd->text += p_text;
+ sd->end += p_text.length();
+ invalidate(sd);
+
+ return true;
+}
+
+bool TextServerAdvanced::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(p_key == Variant(), false);
+ ERR_FAIL_COND_V(sd->objects.has(p_key), false);
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+
+ ShapedTextDataAdvanced::Span span;
+ span.start = sd->text.length();
+ span.end = span.start + p_length;
+ span.embedded_key = p_key;
+
+ ShapedTextDataAdvanced::EmbeddedObject obj;
+ obj.inline_align = p_inline_align;
+ obj.rect.size = p_size;
+ obj.pos = span.start;
+
+ sd->spans.push_back(span);
+ sd->text += String::chr(0xfffc).repeat(p_length);
+ sd->end += p_length;
+ sd->objects[p_key] = obj;
+ invalidate(sd);
+
+ return true;
+}
+
+bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(!sd->objects.has(p_key), false);
+ sd->objects[p_key].rect.size = p_size;
+ sd->objects[p_key].inline_align = p_inline_align;
+ if (sd->valid) {
+ // Recalc string metrics.
+ sd->ascent = 0;
+ sd->descent = 0;
+ sd->width = 0;
+ sd->upos = 0;
+ sd->uthk = 0;
+ int sd_size = sd->glyphs.size();
+
+ for (int i = 0; i < sd_size; i++) {
+ Glyph gl = sd->glyphs[i];
+ Variant key;
+ if (gl.count == 1) {
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (E->get().pos == gl.start) {
+ key = E->key();
+ break;
+ }
+ }
+ }
+ if (key != Variant()) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->objects[key].rect.position.x = sd->width;
+ sd->width += sd->objects[key].rect.size.x;
+ switch (sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.y / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y);
+ } break;
+ }
+ sd->glyphs.write[i].advance = sd->objects[key].rect.size.x;
+ } else {
+ sd->objects[key].rect.position.y = sd->width;
+ sd->width += sd->objects[key].rect.size.y;
+ switch (sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.x / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x);
+ } break;
+ }
+ sd->glyphs.write[i].advance = sd->objects[key].rect.size.y;
+ }
+ } else {
+ const FontDataAdvanced *fd = font_owner.getornull(gl.font_rid);
+ if (fd != nullptr) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->ascent = MAX(sd->ascent, MAX(fd->get_ascent(gl.font_size), -gl.y_off));
+ sd->descent = MAX(sd->descent, MAX(fd->get_descent(gl.font_size), gl.y_off));
+ } else {
+ sd->ascent = MAX(sd->ascent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ sd->descent = MAX(sd->descent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ }
+ sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size));
+ sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size));
+ } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) {
+ // Glyph not found, replace with hex code box.
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f));
+ } else {
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ }
+ }
+ sd->width += gl.advance * gl.repeat;
+ }
+ }
+
+ // Align embedded objects to baseline.
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+ }
+ }
+ return true;
+}
+
+RID TextServerAdvanced::shaped_text_substr(RID p_shaped, int p_start, int p_length) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, RID());
+ if (sd->parent != RID()) {
+ return shaped_text_substr(sd->parent, p_start, p_length);
+ }
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID());
+ ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID());
+ ERR_FAIL_COND_V(sd->end < p_start + p_length, RID());
+
+ ShapedTextDataAdvanced *new_sd = memnew(ShapedTextDataAdvanced);
+
+ new_sd->hb_buffer = hb_buffer_create();
+ new_sd->parent = p_shaped;
+ new_sd->start = p_start;
+ new_sd->end = p_start + p_length;
+
+ new_sd->orientation = sd->orientation;
+ new_sd->direction = sd->direction;
+ new_sd->para_direction = sd->para_direction;
+ new_sd->line_breaks_valid = sd->line_breaks_valid;
+ new_sd->justification_ops_valid = sd->justification_ops_valid;
+ new_sd->sort_valid = false;
+ new_sd->upos = sd->upos;
+ new_sd->uthk = sd->uthk;
+
+ if (p_length > 0) {
+ new_sd->text = sd->text.substr(p_start, p_length);
+ new_sd->utf16 = new_sd->text.utf16();
+ new_sd->script_iter = memnew(ScriptIterator(new_sd->text, 0, new_sd->text.length()));
+
+ int sd_size = sd->glyphs.size();
+ const Glyph *sd_glyphs = sd->glyphs.ptr();
+ const FontDataAdvanced *fd = nullptr;
+ RID prev_rid = RID();
+
+ for (int ov = 0; ov < sd->bidi_override.size(); ov++) {
+ UErrorCode err = U_ZERO_ERROR;
+
+ if (sd->bidi_override[ov].x >= p_start + p_length || sd->bidi_override[ov].y <= p_start) {
+ continue;
+ }
+ int start = _convert_pos_inv(sd, MAX(0, p_start - sd->bidi_override[ov].x));
+ int end = _convert_pos_inv(sd, MIN(p_start + p_length, sd->bidi_override[ov].y) - sd->bidi_override[ov].x);
+
+ ERR_FAIL_COND_V_MSG((start < 0 || end - start > new_sd->utf16.length()), RID(), "Invalid BiDi override range.");
+
+ //Create temporary line bidi & shape
+ UBiDi *bidi_iter = ubidi_openSized(end - start, 0, &err);
+ ERR_FAIL_COND_V_MSG(U_FAILURE(err), RID(), u_errorName(err));
+ ubidi_setLine(sd->bidi_iter[ov], start, end, bidi_iter, &err);
+ if (U_FAILURE(err)) {
+ ubidi_close(bidi_iter);
+ ERR_FAIL_V_MSG(RID(), u_errorName(err));
+ }
+ new_sd->bidi_iter.push_back(bidi_iter);
+
+ err = U_ZERO_ERROR;
+ int bidi_run_count = ubidi_countRuns(bidi_iter, &err);
+ ERR_FAIL_COND_V_MSG(U_FAILURE(err), RID(), u_errorName(err));
+ for (int i = 0; i < bidi_run_count; i++) {
+ int32_t _bidi_run_start = 0;
+ int32_t _bidi_run_length = 0;
+ ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length);
+
+ int32_t bidi_run_start = _convert_pos(sd, sd->bidi_override[ov].x + start + _bidi_run_start);
+ int32_t bidi_run_end = _convert_pos(sd, sd->bidi_override[ov].x + start + _bidi_run_start + _bidi_run_length);
+
+ for (int j = 0; j < sd_size; j++) {
+ if ((sd_glyphs[j].start >= bidi_run_start) && (sd_glyphs[j].end <= bidi_run_end)) {
+ // Copy glyphs.
+ Glyph gl = sd_glyphs[j];
+ Variant key;
+ bool find_embedded = false;
+ if (gl.count == 1) {
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (E->get().pos == gl.start) {
+ find_embedded = true;
+ key = E->key();
+ new_sd->objects[key] = E->get();
+ break;
+ }
+ }
+ }
+ if (find_embedded) {
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->objects[key].rect.position.x = new_sd->width;
+ new_sd->width += new_sd->objects[key].rect.size.x;
+ switch (new_sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.y / 2));
+ new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y);
+ } break;
+ }
+ } else {
+ new_sd->objects[key].rect.position.y = new_sd->width;
+ new_sd->width += new_sd->objects[key].rect.size.y;
+ switch (new_sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.x / 2));
+ new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x);
+ } break;
+ }
+ }
+ } else {
+ if (prev_rid != gl.font_rid) {
+ fd = font_owner.getornull(gl.font_rid);
+ prev_rid = gl.font_rid;
+ }
+ if (fd != nullptr) {
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->ascent = MAX(new_sd->ascent, MAX(fd->get_ascent(gl.font_size), -gl.y_off));
+ new_sd->descent = MAX(new_sd->descent, MAX(fd->get_descent(gl.font_size), gl.y_off));
+ } else {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ new_sd->descent = MAX(new_sd->descent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ }
+ } else if (new_sd->preserve_invalid || (new_sd->preserve_control && is_control(gl.index))) {
+ // Glyph not found, replace with hex code box.
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f));
+ new_sd->descent = MAX(new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f));
+ } else {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ new_sd->descent = MAX(new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ }
+ }
+ new_sd->width += gl.advance * gl.repeat;
+ }
+ new_sd->glyphs.push_back(gl);
+ }
+ }
+ }
+ }
+
+ // Align embedded objects to baseline.
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) {
+ if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -new_sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = new_sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -new_sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = new_sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+ }
+ }
+
+ new_sd->valid = true;
+
+ return shaped_owner.make_rid(new_sd);
+}
+
+RID TextServerAdvanced::shaped_text_get_parent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, RID());
+ return sd->parent;
+}
+
+float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (!sd->justification_ops_valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_update_justification_ops(p_shaped);
+ }
+
+ int start_pos = 0;
+ int end_pos = sd->glyphs.size() - 1;
+
+ if ((p_jst_flags & JUSTIFICATION_AFTER_LAST_TAB) == JUSTIFICATION_AFTER_LAST_TAB) {
+ int start, end, delta;
+ if (sd->para_direction == DIRECTION_LTR) {
+ start = sd->glyphs.size() - 1;
+ end = -1;
+ delta = -1;
+ } else {
+ start = 0;
+ end = sd->glyphs.size();
+ delta = +1;
+ }
+
+ for (int i = start; i != end; i += delta) {
+ if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
+ if (sd->para_direction == DIRECTION_LTR) {
+ start_pos = i;
+ break;
+ } else {
+ end_pos = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if ((p_jst_flags & JUSTIFICATION_TRIM_EDGE_SPACES) == JUSTIFICATION_TRIM_EDGE_SPACES) {
+ while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
+ sd->width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat;
+ sd->glyphs.write[start_pos].advance = 0;
+ start_pos += sd->glyphs[start_pos].count;
+ }
+ while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
+ sd->width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat;
+ sd->glyphs.write[end_pos].advance = 0;
+ end_pos -= sd->glyphs[end_pos].count;
+ }
+ }
+
+ int space_count = 0;
+ int elongation_count = 0;
+ for (int i = start_pos; i <= end_pos; i++) {
+ const Glyph &gl = sd->glyphs[i];
+ if (gl.count > 0) {
+ if ((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) {
+ elongation_count++;
+ }
+ if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
+ space_count++;
+ }
+ }
+ }
+
+ if ((elongation_count > 0) && ((p_jst_flags & JUSTIFICATION_KASHIDA) == JUSTIFICATION_KASHIDA)) {
+ float delta_width_per_kashida = (p_width - sd->width) / elongation_count;
+ for (int i = start_pos; i <= end_pos; i++) {
+ Glyph &gl = sd->glyphs.write[i];
+ if (gl.count > 0) {
+ if (((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) && (gl.advance > 0)) {
+ int count = delta_width_per_kashida / gl.advance;
+ int prev_count = gl.repeat;
+ if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
+ gl.repeat = count;
+ } else {
+ gl.repeat = count + 1;
+ }
+ sd->width += (gl.repeat - prev_count) * gl.advance;
+ }
+ }
+ }
+ }
+
+ if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) {
+ float delta_width_per_space = (p_width - sd->width) / space_count;
+ for (int i = start_pos; i <= end_pos; i++) {
+ Glyph &gl = sd->glyphs.write[i];
+ if (gl.count > 0) {
+ if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
+ float old_adv = gl.advance;
+ if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
+ gl.advance = Math::round(MAX(gl.advance + delta_width_per_space, 0.f));
+ } else {
+ gl.advance = Math::round(MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size));
+ }
+ sd->width += (gl.advance - old_adv);
+ }
+ }
+ }
+ }
+
+ return sd->width;
+}
+
+float TextServerAdvanced::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (!sd->line_breaks_valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_update_breaks(p_shaped);
+ }
+
+ int tab_index = 0;
+ float off = 0.f;
+
+ int start, end, delta;
+ if (sd->para_direction == DIRECTION_LTR) {
+ start = 0;
+ end = sd->glyphs.size();
+ delta = +1;
+ } else {
+ start = sd->glyphs.size() - 1;
+ end = -1;
+ delta = -1;
+ }
+
+ Glyph *gl = sd->glyphs.ptrw();
+
+ for (int i = start; i != end; i += delta) {
+ if ((gl[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
+ float tab_off = 0.f;
+ while (tab_off <= off) {
+ tab_off += p_tab_stops[tab_index];
+ tab_index++;
+ if (tab_index >= p_tab_stops.size()) {
+ tab_index = 0;
+ }
+ }
+ float old_adv = gl[i].advance;
+ gl[i].advance = tab_off - off;
+ sd->width += gl[i].advance - old_adv;
+ off = 0;
+ continue;
+ }
+ off += gl[i].advance * gl[i].repeat;
+ }
+
+ return 0.f;
+}
+
+bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ if (!sd->valid) {
+ shaped_text_shape(p_shaped);
+ }
+
+ if (sd->line_breaks_valid) {
+ return true; // Noting to do.
+ }
+
+ const UChar *data = sd->utf16.ptr();
+
+ HashMap<int, bool> breaks;
+ UErrorCode err = U_ZERO_ERROR;
+ for (int i = 0; i < sd->spans.size(); i++) {
+ UBreakIterator *bi = ubrk_open(UBRK_LINE, sd->spans[i].language.ascii().get_data(), data + _convert_pos_inv(sd, sd->spans[i].start), _convert_pos_inv(sd, sd->spans[i].end - sd->spans[i].start), &err);
+ if (U_FAILURE(err)) {
+ //No data loaded - use fallback.
+ for (int j = sd->spans[i].start; j < sd->spans[i].end; j++) {
+ char32_t c = sd->text[j - sd->start];
+ if (is_whitespace(c)) {
+ breaks[j] = false;
+ }
+ if (is_linebreak(c)) {
+ breaks[j] = true;
+ }
+ }
+ } else {
+ while (ubrk_next(bi) != UBRK_DONE) {
+ int pos = _convert_pos(sd, ubrk_current(bi)) + sd->spans[i].start - 1;
+ if (pos != sd->spans[i].end) {
+ if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_HARD) && (ubrk_getRuleStatus(bi) < UBRK_LINE_HARD_LIMIT)) {
+ breaks[pos] = true;
+ } else if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_SOFT) && (ubrk_getRuleStatus(bi) < UBRK_LINE_SOFT_LIMIT)) {
+ breaks[pos] = false;
+ }
+ }
+ }
+ }
+ ubrk_close(bi);
+ }
+
+ sd->sort_valid = false;
+ sd->glyphs_logical.clear();
+ int sd_size = sd->glyphs.size();
+ const char32_t *ch = sd->text.ptr();
+ Glyph *sd_glyphs = sd->glyphs.ptrw();
+
+ for (int i = 0; i < sd_size; i++) {
+ if (sd_glyphs[i].count > 0) {
+ char32_t c = ch[sd_glyphs[i].start - sd->start];
+ if (c == 0xfffc) {
+ continue;
+ }
+ if (c == 0x0009 || c == 0x000b) {
+ sd_glyphs[i].flags |= GRAPHEME_IS_TAB;
+ }
+ if (is_whitespace(c)) {
+ sd_glyphs[i].flags |= GRAPHEME_IS_SPACE;
+ }
+ if (u_ispunct(c)) {
+ sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION;
+ }
+ if (breaks.has(sd->glyphs[i].start)) {
+ if (breaks[sd->glyphs[i].start]) {
+ sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_HARD;
+ } else {
+ if (is_whitespace(c)) {
+ sd_glyphs[i].flags |= GRAPHEME_IS_BREAK_SOFT;
+ } else {
+ TextServer::Glyph gl;
+ gl.start = sd_glyphs[i].start;
+ gl.end = sd_glyphs[i].end;
+ gl.count = 1;
+ gl.font_rid = sd_glyphs[i].font_rid;
+ gl.font_size = sd_glyphs[i].font_size;
+ gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL;
+ sd->glyphs.insert(i + sd_glyphs[i].count, gl); // insert after
+
+ // Update write pointer and size.
+ sd_size = sd->glyphs.size();
+ sd_glyphs = sd->glyphs.ptrw();
+
+ i += sd_glyphs[i].count;
+ continue;
+ }
+ }
+ }
+
+ i += (sd_glyphs[i].count - 1);
+ }
+ }
+
+ sd->line_breaks_valid = true;
+
+ return sd->line_breaks_valid;
+}
+
+_FORCE_INLINE_ int _generate_kashida_justification_opportunies(const String &p_data, int p_start, int p_end) {
+ int kashida_pos = -1;
+ int8_t priority = 100;
+ int i = p_start;
+
+ char32_t pc = 0;
+
+ while ((p_end > p_start) && is_transparent(p_data[p_end - 1])) {
+ p_end--;
+ }
+
+ while (i < p_end) {
+ uint32_t c = p_data[i];
+
+ if (c == 0x0640) {
+ kashida_pos = i;
+ priority = 0;
+ }
+ if (priority >= 1 && i < p_end - 1) {
+ if (is_seen_sad(c) && (p_data[i + 1] != 0x200C)) {
+ kashida_pos = i;
+ priority = 1;
+ }
+ }
+ if (priority >= 2 && i > p_start) {
+ if (is_teh_marbuta(c) || is_dal(c) || (is_heh(c) && i == p_end - 1)) {
+ if (is_connected_to_prev(c, pc)) {
+ kashida_pos = i - 1;
+ priority = 2;
+ }
+ }
+ }
+ if (priority >= 3 && i > p_start) {
+ if (is_alef(c) || ((is_lam(c) || is_tah(c) || is_kaf(c) || is_gaf(c)) && i == p_end - 1)) {
+ if (is_connected_to_prev(c, pc)) {
+ kashida_pos = i - 1;
+ priority = 3;
+ }
+ }
+ }
+ if (priority >= 4 && i > p_start && i < p_end - 1) {
+ if (is_beh(c)) {
+ if (is_reh(p_data[i + 1]) || is_yeh(p_data[i + 1])) {
+ if (is_connected_to_prev(c, pc)) {
+ kashida_pos = i - 1;
+ priority = 4;
+ }
+ }
+ }
+ }
+ if (priority >= 5 && i > p_start) {
+ if (is_waw(c) || ((is_ain(c) || is_qaf(c) || is_feh(c)) && i == p_end - 1)) {
+ if (is_connected_to_prev(c, pc)) {
+ kashida_pos = i - 1;
+ priority = 5;
+ }
+ }
+ }
+ if (priority >= 6 && i > p_start) {
+ if (is_reh(c)) {
+ if (is_connected_to_prev(c, pc)) {
+ kashida_pos = i - 1;
+ priority = 6;
+ }
+ }
+ }
+ if (!is_transparent(c))
+ pc = c;
+ i++;
+ }
+
+ return kashida_pos;
+}
+
+bool TextServerAdvanced::shaped_text_update_justification_ops(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ if (!sd->valid) {
+ shaped_text_shape(p_shaped);
+ }
+ if (!sd->line_breaks_valid) {
+ shaped_text_update_breaks(p_shaped);
+ }
+
+ if (sd->justification_ops_valid) {
+ return true; // Noting to do.
+ }
+
+ const UChar *data = sd->utf16.ptr();
+ int32_t data_size = sd->utf16.length();
+
+ Map<int, bool> jstops;
+
+ // Use ICU word iterator and custom kashida detection.
+ UErrorCode err = U_ZERO_ERROR;
+ UBreakIterator *bi = ubrk_open(UBRK_WORD, "", data, data_size, &err);
+ if (U_FAILURE(err)) {
+ // No data - use fallback
+ int limit = 0;
+ for (int i = 0; i < sd->text.length(); i++) {
+ if (is_whitespace(data[i])) {
+ int ks = _generate_kashida_justification_opportunies(sd->text, limit, i) + sd->start;
+ if (ks != -1) {
+ jstops[ks] = true;
+ }
+ limit = i + 1;
+ }
+ }
+ int ks = _generate_kashida_justification_opportunies(sd->text, limit, sd->text.length()) + sd->start;
+ if (ks != -1) {
+ jstops[ks] = true;
+ }
+ } else {
+ int limit = 0;
+ while (ubrk_next(bi) != UBRK_DONE) {
+ if (ubrk_getRuleStatus(bi) != UBRK_WORD_NONE) {
+ int i = _convert_pos(sd, ubrk_current(bi));
+ jstops[i + sd->start] = false;
+ int ks = _generate_kashida_justification_opportunies(sd->text, limit, i);
+ if (ks != -1) {
+ jstops[ks + sd->start] = true;
+ }
+ limit = i;
+ }
+ }
+ ubrk_close(bi);
+ }
+
+ sd->sort_valid = false;
+ sd->glyphs_logical.clear();
+ int sd_size = sd->glyphs.size();
+
+ if (jstops.size() > 0) {
+ for (int i = 0; i < sd_size; i++) {
+ if (sd->glyphs[i].count > 0) {
+ if (jstops.has(sd->glyphs[i].start)) {
+ char32_t c = sd->text[sd->glyphs[i].start - sd->start];
+ if (c == 0xfffc) {
+ continue;
+ }
+ if (jstops[sd->glyphs[i].start]) {
+ if (c == 0x0640) {
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_ELONGATION;
+ } else {
+ if (sd->glyphs[i].font_rid != RID()) {
+ TextServer::Glyph gl = _shape_single_glyph(sd, 0x0640, HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, sd->glyphs[i].font_rid, sd->glyphs[i].font_size);
+ if ((gl.flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
+ gl.start = sd->glyphs[i].start;
+ gl.end = sd->glyphs[i].end;
+ gl.repeat = 0;
+ gl.count = 1;
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.y_off = sd->glyphs[i].y_off;
+ } else {
+ gl.x_off = sd->glyphs[i].x_off;
+ }
+ gl.flags |= GRAPHEME_IS_ELONGATION | GRAPHEME_IS_VIRTUAL;
+ sd->glyphs.insert(i, gl);
+ i++;
+ }
+ }
+ }
+ } else if (!is_whitespace(c)) {
+ TextServer::Glyph gl;
+ gl.start = sd->glyphs[i].start;
+ gl.end = sd->glyphs[i].end;
+ gl.count = 1;
+ gl.font_rid = sd->glyphs[i].font_rid;
+ gl.font_size = sd->glyphs[i].font_size;
+ gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_VIRTUAL;
+ sd->glyphs.insert(i + sd->glyphs[i].count, gl); // insert after
+ i += sd->glyphs[i].count;
+ continue;
+ }
+ }
+ }
+ }
+ }
+
+ sd->justification_ops_valid = true;
+ return sd->justification_ops_valid;
+}
+
+TextServer::Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, RID p_font, int p_font_size) {
+ FontDataAdvanced *fd = font_owner.getornull(p_font);
+ hb_font_t *hb_font = fd->get_hb_handle(p_font_size);
+
+ hb_buffer_clear_contents(p_sd->hb_buffer);
+ hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
+ hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT));
+ hb_buffer_set_script(p_sd->hb_buffer, p_script);
+ hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)&p_char, 1, 0, 1);
+
+ hb_shape(hb_font, p_sd->hb_buffer, nullptr, 0);
+
+ unsigned int glyph_count = 0;
+ hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
+ hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
+
+ // Process glyphs.
+ TextServer::Glyph gl;
+
+ if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
+ gl.flags |= TextServer::GRAPHEME_IS_RTL;
+ }
+
+ gl.font_rid = p_font;
+ gl.font_size = p_font_size;
+
+ if (glyph_count > 0) {
+ if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = Math::round(glyph_pos[0].x_advance / (64.0 / fd->get_font_scale(p_font_size)));
+ } else {
+ gl.advance = -Math::round(glyph_pos[0].y_advance / (64.0 / fd->get_font_scale(p_font_size)));
+ }
+ gl.count = 1;
+
+ gl.index = glyph_info[0].codepoint;
+ gl.x_off = Math::round(glyph_pos[0].x_offset / (64.0 / fd->get_font_scale(p_font_size)));
+ gl.y_off = -Math::round(glyph_pos[0].y_offset / (64.0 / fd->get_font_scale(p_font_size)));
+
+ if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) {
+ gl.flags |= GRAPHEME_IS_VALID;
+ }
+ }
+ return gl;
+}
+
+void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_start, int32_t p_end, hb_script_t p_script, hb_direction_t p_direction, Vector<RID> p_fonts, int p_span, int p_fb_index) {
+ FontDataAdvanced *fd = nullptr;
+ if (p_fb_index < p_fonts.size()) {
+ fd = font_owner.getornull(p_fonts[p_fb_index]);
+ }
+
+ int fs = p_sd->spans[p_span].font_size;
+ if (fd == nullptr) {
+ // Add fallback glyphs
+ for (int i = p_start; i < p_end; i++) {
+ if (p_sd->preserve_invalid || (p_sd->preserve_control && is_control(p_sd->text[i]))) {
+ TextServer::Glyph gl;
+ gl.start = i;
+ gl.end = i + 1;
+ gl.count = 1;
+ gl.index = p_sd->text[i];
+ gl.font_size = fs;
+ gl.font_rid = RID();
+ if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
+ gl.flags |= TextServer::GRAPHEME_IS_RTL;
+ }
+ if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = get_hex_code_box_size(fs, gl.index).x;
+ p_sd->ascent = MAX(p_sd->ascent, Math::round(get_hex_code_box_size(fs, gl.index).y * 0.75f));
+ p_sd->descent = MAX(p_sd->descent, Math::round(get_hex_code_box_size(fs, gl.index).y * 0.25f));
+ } else {
+ gl.advance = get_hex_code_box_size(fs, gl.index).y;
+ p_sd->ascent = MAX(p_sd->ascent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5f));
+ p_sd->descent = MAX(p_sd->descent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5f));
+ }
+ p_sd->width += gl.advance;
+
+ p_sd->glyphs.push_back(gl);
+ }
+ }
+ return;
+ }
+
+ hb_font_t *hb_font = fd->get_hb_handle(fs);
+ ERR_FAIL_COND(hb_font == nullptr);
+
+ hb_buffer_clear_contents(p_sd->hb_buffer);
+ hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
+ if (p_sd->preserve_control) {
+ hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES | (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0)));
+ } else {
+ hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT | (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0)));
+ }
+ hb_buffer_set_script(p_sd->hb_buffer, p_script);
+
+ if (p_sd->spans[p_span].language != String()) {
+ hb_language_t lang = hb_language_from_string(p_sd->spans[p_span].language.ascii().get_data(), -1);
+ hb_buffer_set_language(p_sd->hb_buffer, lang);
+ }
+
+ hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)p_sd->text.ptr(), p_sd->text.length(), p_start, p_end - p_start);
+
+ Vector<hb_feature_t> ftrs;
+ for (const Variant *ftr = p_sd->spans[p_span].features.next(nullptr); ftr != nullptr; ftr = p_sd->spans[p_span].features.next(ftr)) {
+ double values = p_sd->spans[p_span].features[*ftr];
+ if (values >= 0) {
+ hb_feature_t feature;
+ feature.tag = *ftr;
+ feature.value = values;
+ feature.start = 0;
+ feature.end = -1;
+ ftrs.push_back(feature);
+ }
+ }
+ hb_shape(hb_font, p_sd->hb_buffer, ftrs.is_empty() ? nullptr : &ftrs[0], ftrs.size());
+
+ unsigned int glyph_count = 0;
+ hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
+ hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
+
+ // Process glyphs.
+ if (glyph_count > 0) {
+ TextServer::Glyph *w = (TextServer::Glyph *)memalloc(glyph_count * sizeof(TextServer::Glyph));
+
+ int end = (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) ? p_end : 0;
+ uint32_t last_cluster_id = UINT32_MAX;
+ unsigned int last_cluster_index = 0;
+ bool last_cluster_valid = true;
+
+ for (unsigned int i = 0; i < glyph_count; i++) {
+ if ((i > 0) && (last_cluster_id != glyph_info[i].cluster)) {
+ if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
+ end = w[last_cluster_index].start;
+ } else {
+ for (unsigned int j = last_cluster_index; j < i; j++) {
+ w[j].end = glyph_info[i].cluster;
+ }
+ }
+ if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
+ w[last_cluster_index].flags |= TextServer::GRAPHEME_IS_RTL;
+ }
+ if (last_cluster_valid) {
+ w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
+ }
+ w[last_cluster_index].count = i - last_cluster_index;
+ last_cluster_index = i;
+ last_cluster_valid = true;
+ }
+
+ last_cluster_id = glyph_info[i].cluster;
+
+ TextServer::Glyph &gl = w[i];
+ gl = TextServer::Glyph();
+
+ gl.start = glyph_info[i].cluster;
+ gl.end = end;
+ gl.count = 0;
+
+ gl.font_rid = p_fonts[p_fb_index];
+ gl.font_size = fs;
+
+ gl.index = glyph_info[i].codepoint;
+ if (gl.index != 0) {
+ if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = Math::round(glyph_pos[i].x_advance / (64.0 / fd->get_font_scale(fs)));
+ } else {
+ gl.advance = -Math::round(glyph_pos[i].y_advance / (64.0 / fd->get_font_scale(fs)));
+ }
+ gl.x_off = Math::round(glyph_pos[i].x_offset / (64.0 / fd->get_font_scale(fs)));
+ gl.y_off = -Math::round(glyph_pos[i].y_offset / (64.0 / fd->get_font_scale(fs)));
+ }
+
+ if (p_sd->preserve_control) {
+ last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || is_whitespace(p_sd->text[glyph_info[i].cluster]) || is_linebreak(p_sd->text[glyph_info[i].cluster]));
+ } else {
+ last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || !u_isgraph(p_sd->text[glyph_info[i].cluster]));
+ }
+ }
+ if (p_direction == HB_DIRECTION_LTR || p_direction == HB_DIRECTION_TTB) {
+ for (unsigned int j = last_cluster_index; j < glyph_count; j++) {
+ w[j].end = p_end;
+ }
+ }
+ w[last_cluster_index].count = glyph_count - last_cluster_index;
+ if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
+ w[last_cluster_index].flags |= TextServer::GRAPHEME_IS_RTL;
+ }
+ if (last_cluster_valid) {
+ w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
+ }
+
+ //Fallback.
+ int failed_subrun_start = p_end + 1;
+ int failed_subrun_end = p_start;
+
+ for (unsigned int i = 0; i < glyph_count; i++) {
+ if ((w[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
+ if (failed_subrun_start != p_end + 1) {
+ _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1);
+ failed_subrun_start = p_end + 1;
+ failed_subrun_end = p_start;
+ }
+ for (int j = 0; j < w[i].count; j++) {
+ if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
+ p_sd->ascent = MAX(p_sd->ascent, -w[i + j].y_off);
+ p_sd->descent = MAX(p_sd->descent, w[i + j].y_off);
+ } else {
+ p_sd->ascent = MAX(p_sd->ascent, Math::round(fd->get_advance(w[i + j].index, fs).x * 0.5));
+ p_sd->descent = MAX(p_sd->descent, Math::round(fd->get_advance(w[i + j].index, fs).x * 0.5));
+ }
+ p_sd->width += w[i + j].advance;
+ p_sd->glyphs.push_back(w[i + j]);
+ }
+ } else {
+ if (failed_subrun_start >= w[i].start) {
+ failed_subrun_start = w[i].start;
+ }
+ if (failed_subrun_end <= w[i].end) {
+ failed_subrun_end = w[i].end;
+ }
+ }
+ i += w[i].count - 1;
+ }
+ memfree(w);
+ if (failed_subrun_start != p_end + 1) {
+ _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1);
+ }
+ p_sd->ascent = MAX(p_sd->ascent, fd->get_ascent(fs));
+ p_sd->descent = MAX(p_sd->descent, fd->get_descent(fs));
+ p_sd->upos = MAX(p_sd->upos, fd->get_underline_position(fs));
+ p_sd->uthk = MAX(p_sd->uthk, fd->get_underline_thickness(fs));
+ }
+}
+
+bool TextServerAdvanced::shaped_text_shape(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+
+ if (sd->valid) {
+ return true;
+ }
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ invalidate(sd);
+
+ if (sd->text.length() == 0) {
+ sd->valid = true;
+ return true;
+ }
+
+ sd->utf16 = sd->text.utf16();
+ const UChar *data = sd->utf16.ptr();
+
+ // Create script iterator.
+ if (sd->script_iter == nullptr) {
+ sd->script_iter = memnew(ScriptIterator(sd->text, 0, sd->text.length()));
+ }
+
+ if (sd->bidi_override.is_empty()) {
+ sd->bidi_override.push_back(Vector2i(0, sd->end));
+ }
+
+ for (int ov = 0; ov < sd->bidi_override.size(); ov++) {
+ // Create BiDi iterator.
+ int start = _convert_pos_inv(sd, sd->bidi_override[ov].x);
+ int end = _convert_pos_inv(sd, sd->bidi_override[ov].y);
+
+ ERR_FAIL_COND_V_MSG((start < 0 || end - start > sd->utf16.length()), false, "Invalid BiDi override range.");
+
+ UErrorCode err = U_ZERO_ERROR;
+ UBiDi *bidi_iter = ubidi_openSized(end, 0, &err);
+ ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
+
+ switch (sd->direction) {
+ case DIRECTION_LTR: {
+ ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_LTR, nullptr, &err);
+ sd->para_direction = DIRECTION_LTR;
+ } break;
+ case DIRECTION_RTL: {
+ ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_RTL, nullptr, &err);
+ sd->para_direction = DIRECTION_RTL;
+ } break;
+ case DIRECTION_AUTO: {
+ UBiDiDirection direction = ubidi_getBaseDirection(data + start, end - start);
+ if (direction != UBIDI_NEUTRAL) {
+ ubidi_setPara(bidi_iter, data + start, end - start, direction, nullptr, &err);
+ sd->para_direction = (direction == UBIDI_RTL) ? DIRECTION_RTL : DIRECTION_LTR;
+ } else {
+ ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_DEFAULT_LTR, nullptr, &err);
+ sd->para_direction = DIRECTION_LTR;
+ }
+ } break;
+ }
+ ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
+ sd->bidi_iter.push_back(bidi_iter);
+
+ err = U_ZERO_ERROR;
+ int bidi_run_count = ubidi_countRuns(bidi_iter, &err);
+ ERR_FAIL_COND_V_MSG(U_FAILURE(err), false, u_errorName(err));
+ for (int i = 0; i < bidi_run_count; i++) {
+ int32_t _bidi_run_start = 0;
+ int32_t _bidi_run_length = 0;
+ hb_direction_t bidi_run_direction = HB_DIRECTION_INVALID;
+ bool is_rtl = (ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length) == UBIDI_LTR);
+ switch (sd->orientation) {
+ case ORIENTATION_HORIZONTAL: {
+ if (is_rtl) {
+ bidi_run_direction = HB_DIRECTION_LTR;
+ } else {
+ bidi_run_direction = HB_DIRECTION_RTL;
+ }
+ } break;
+ case ORIENTATION_VERTICAL: {
+ if (is_rtl) {
+ bidi_run_direction = HB_DIRECTION_TTB;
+ } else {
+ bidi_run_direction = HB_DIRECTION_BTT;
+ }
+ }
+ }
+
+ int32_t bidi_run_start = _convert_pos(sd, sd->bidi_override[ov].x + _bidi_run_start);
+ int32_t bidi_run_end = _convert_pos(sd, sd->bidi_override[ov].x + _bidi_run_start + _bidi_run_length);
+
+ // Shape runs.
+
+ int scr_from = (is_rtl) ? 0 : sd->script_iter->script_ranges.size() - 1;
+ int scr_to = (is_rtl) ? sd->script_iter->script_ranges.size() : -1;
+ int scr_delta = (is_rtl) ? +1 : -1;
+
+ for (int j = scr_from; j != scr_to; j += scr_delta) {
+ if ((sd->script_iter->script_ranges[j].start < bidi_run_end) && (sd->script_iter->script_ranges[j].end > bidi_run_start)) {
+ int32_t script_run_start = MAX(sd->script_iter->script_ranges[j].start, bidi_run_start);
+ int32_t script_run_end = MIN(sd->script_iter->script_ranges[j].end, bidi_run_end);
+ char scr_buffer[5] = { 0, 0, 0, 0, 0 };
+ hb_tag_to_string(hb_script_to_iso15924_tag(sd->script_iter->script_ranges[j].script), scr_buffer);
+ String script = String(scr_buffer);
+
+ int spn_from = (is_rtl) ? 0 : sd->spans.size() - 1;
+ int spn_to = (is_rtl) ? sd->spans.size() : -1;
+ int spn_delta = (is_rtl) ? +1 : -1;
+
+ for (int k = spn_from; k != spn_to; k += spn_delta) {
+ const ShapedTextDataAdvanced::Span &span = sd->spans[k];
+ if (span.start >= script_run_end || span.end <= script_run_start) {
+ continue;
+ }
+ if (span.embedded_key != Variant()) {
+ // Embedded object.
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->objects[span.embedded_key].rect.position.x = sd->width;
+ sd->width += sd->objects[span.embedded_key].rect.size.x;
+ switch (sd->objects[span.embedded_key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y);
+ } break;
+ }
+ } else {
+ sd->objects[span.embedded_key].rect.position.y = sd->width;
+ sd->width += sd->objects[span.embedded_key].rect.size.y;
+ switch (sd->objects[span.embedded_key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x);
+ } break;
+ }
+ }
+ Glyph gl;
+ gl.start = span.start;
+ gl.end = span.end;
+ gl.count = 1;
+ gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_VIRTUAL;
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = sd->objects[span.embedded_key].rect.size.x;
+ } else {
+ gl.advance = sd->objects[span.embedded_key].rect.size.y;
+ }
+ sd->glyphs.push_back(gl);
+ } else {
+ Vector<RID> fonts;
+ // Push fonts with the language and script support first.
+ for (int l = 0; l < span.fonts.size(); l++) {
+ if ((font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) {
+ fonts.push_back(sd->spans[k].fonts[l]);
+ }
+ }
+ // Push fonts with the script support.
+ for (int l = 0; l < sd->spans[k].fonts.size(); l++) {
+ if (!(font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) {
+ fonts.push_back(sd->spans[k].fonts[l]);
+ }
+ }
+ // Push the rest valid fonts.
+ for (int l = 0; l < sd->spans[k].fonts.size(); l++) {
+ if (!(font_is_language_supported(span.fonts[l], span.language)) && !(font_is_script_supported(span.fonts[l], script))) {
+ fonts.push_back(sd->spans[k].fonts[l]);
+ }
+ }
+ _shape_run(sd, MAX(sd->spans[k].start, script_run_start), MIN(sd->spans[k].end, script_run_end), sd->script_iter->script_ranges[j].script, bidi_run_direction, fonts, k, 0);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Align embedded objects to baseline.
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+
+ sd->valid = true;
+ return sd->valid;
+}
+
+bool TextServerAdvanced::shaped_text_is_ready(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->valid;
+}
+
+Vector<TextServer::Glyph> TextServerAdvanced::shaped_text_get_glyphs(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>());
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->glyphs;
+}
+
+Vector2i TextServerAdvanced::shaped_text_get_range(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector2i());
+ return Vector2(sd->start, sd->end);
+}
+
+Vector<TextServer::Glyph> TextServerAdvanced::shaped_text_sort_logical(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>());
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ if (!sd->sort_valid) {
+ sd->glyphs_logical = sd->glyphs;
+ sd->glyphs_logical.sort_custom<TextServer::GlyphCompare>();
+ sd->sort_valid = true;
+ }
+
+ return sd->glyphs_logical;
+}
+
+Array TextServerAdvanced::shaped_text_get_objects(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ Array ret;
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, ret);
+ for (const Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+
+ return ret;
+}
+
+Rect2 TextServerAdvanced::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Rect2());
+ ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2());
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->objects[p_key].rect;
+}
+
+Size2 TextServerAdvanced::shaped_text_get_size(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Size2());
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) {
+ return Size2(sd->width, sd->ascent + sd->descent);
+ } else {
+ return Size2(sd->ascent + sd->descent, sd->width);
+ }
+}
+
+float TextServerAdvanced::shaped_text_get_ascent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->ascent;
+}
+
+float TextServerAdvanced::shaped_text_get_descent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->descent;
+}
+
+float TextServerAdvanced::shaped_text_get_width(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->width;
+}
+
+float TextServerAdvanced::shaped_text_get_underline_position(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ return sd->upos;
+}
+
+float TextServerAdvanced::shaped_text_get_underline_thickness(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ return sd->uthk;
+}
+
+struct num_system_data {
+ String lang;
+ String digits;
+ String percent_sign;
+ String exp;
+};
+
+static num_system_data num_systems[]{
+ { "ar,ar_AR,ar_BH,ar_DJ,ar_EG,ar_ER,ar_IL,ar_IQ,ar_JO,ar_KM,ar_KW,ar_LB,ar_MR,ar_OM,ar_PS,ar_QA,ar_SA,ar_SD,ar_SO,ar_SS,ar_SY,ar_TD,ar_YE", U"٠١٢٣٤٥٦٧٨٩٫", U"٪", U"اس" },
+ { "fa,ks,pa_Arab,ps,ug,ur_IN,ur,uz_Arab", U"۰۱۲۳۴۵۶۷۸۹٫", U"٪", U"اس" },
+ { "as,bn,mni", U"০১২৩৪৫৬৭৮৯.", U"%", U"e" },
+ { "mr,ne", U"०१२३४५६७८९.", U"%", U"e" },
+ { "dz", U"༠༡༢༣༤༥༦༧༨༩.", U"%", U"e" },
+ { "sat", U"᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙.", U"%", U"e" },
+ { "my", U"၀၁၂၃၄၅၆၇၈၉.", U"%", U"e" },
+ { String(), String(), String(), String() },
+};
+
+String TextServerAdvanced::format_number(const String &p_string, const String &p_language) const {
+ _THREAD_SAFE_METHOD_
+ String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
+
+ String res = p_string;
+ for (int i = 0; num_systems[i].lang != String(); i++) {
+ Vector<String> langs = num_systems[i].lang.split(",");
+ if (langs.has(lang)) {
+ if (num_systems[i].digits == String()) {
+ return p_string;
+ }
+ res.replace("e", num_systems[i].exp);
+ res.replace("E", num_systems[i].exp);
+ char32_t *data = res.ptrw();
+ for (int j = 0; j < res.size(); j++) {
+ if (data[j] >= 0x30 && data[j] <= 0x39) {
+ data[j] = num_systems[i].digits[data[j] - 0x30];
+ } else if (data[j] == '.' || data[j] == ',') {
+ data[j] = num_systems[i].digits[10];
+ }
+ }
+ break;
+ }
+ }
+ return res;
+}
+
+String TextServerAdvanced::parse_number(const String &p_string, const String &p_language) const {
+ _THREAD_SAFE_METHOD_
+ String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
+
+ String res = p_string;
+ for (int i = 0; num_systems[i].lang != String(); i++) {
+ Vector<String> langs = num_systems[i].lang.split(",");
+ if (langs.has(lang)) {
+ if (num_systems[i].digits == String()) {
+ return p_string;
+ }
+ res.replace(num_systems[i].exp, "e");
+ char32_t *data = res.ptrw();
+ for (int j = 0; j < res.size(); j++) {
+ if (data[j] == num_systems[i].digits[10]) {
+ data[j] = '.';
+ } else {
+ for (int k = 0; k < 10; k++) {
+ if (data[j] == num_systems[i].digits[k]) {
+ data[j] = 0x30 + k;
+ }
+ }
+ }
+ }
+ break;
+ }
+ }
+ return res;
+}
+
+String TextServerAdvanced::percent_sign(const String &p_language) const {
+ _THREAD_SAFE_METHOD_
+ String lang = (p_language == "") ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
+
+ for (int i = 0; num_systems[i].lang != String(); i++) {
+ Vector<String> langs = num_systems[i].lang.split(",");
+ if (langs.has(lang)) {
+ if (num_systems[i].percent_sign == String()) {
+ return "%";
+ }
+ return num_systems[i].percent_sign;
+ }
+ }
+ return "%";
+}
+
+TextServer *TextServerAdvanced::create_func(Error &r_error, void *p_user_data) {
+ r_error = OK;
+ return memnew(TextServerAdvanced());
+}
+
+void TextServerAdvanced::register_server() {
+ TextServerManager::register_create_function(interface_name, interface_features, create_func, nullptr);
+}
+
+TextServerAdvanced::TextServerAdvanced() {
+ hb_bmp_create_font_funcs();
+}
+
+TextServerAdvanced::~TextServerAdvanced() {
+ hb_bmp_free_font_funcs();
+ u_cleanup();
+#ifndef ICU_STATIC_DATA
+ if (icu_data != nullptr) {
+ memfree(icu_data);
+ icu_data = nullptr;
+ }
+#endif
+}
diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h
new file mode 100644
index 0000000000..89fae477f9
--- /dev/null
+++ b/modules/text_server_adv/text_server_adv.h
@@ -0,0 +1,248 @@
+/*************************************************************************/
+/* text_server_adv.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEXT_SERVER_ADV_H
+#define TEXT_SERVER_ADV_H
+
+/*************************************************************************/
+/* ICU/HarfBuzz/Graphite backed Text Server implementation with BiDi, */
+/* shaping and advanced font features support. */
+/*************************************************************************/
+
+#include "servers/text_server.h"
+
+#include "core/templates/rid_owner.h"
+#include "scene/resources/texture.h"
+#include "script_iterator.h"
+
+#include <unicode/ubidi.h>
+#include <unicode/ubrk.h>
+#include <unicode/uchar.h>
+#include <unicode/uclean.h>
+#include <unicode/udata.h>
+#include <unicode/uiter.h>
+#include <unicode/uloc.h>
+#include <unicode/uscript.h>
+#include <unicode/ustring.h>
+#include <unicode/utypes.h>
+
+#include <hb-icu.h>
+#include <hb.h>
+
+#include "font_adv.h"
+
+class TextServerAdvanced : public TextServer {
+ GDCLASS(TextServerAdvanced, TextServer);
+ _THREAD_SAFE_CLASS_
+
+ static String interface_name;
+ static uint32_t interface_features;
+
+ uint8_t *icu_data = nullptr;
+
+ struct ShapedTextDataAdvanced : public ShapedTextData {
+ /* Intermediate data */
+ Char16String utf16;
+ Vector<UBiDi *> bidi_iter;
+ Vector<Vector2i> bidi_override;
+ ScriptIterator *script_iter = nullptr;
+ hb_buffer_t *hb_buffer = nullptr;
+
+ ~ShapedTextDataAdvanced() {
+ for (int i = 0; i < bidi_iter.size(); i++) {
+ ubidi_close(bidi_iter[i]);
+ }
+ if (script_iter) {
+ memdelete(script_iter);
+ }
+ if (hb_buffer) {
+ hb_buffer_destroy(hb_buffer);
+ }
+ }
+ };
+
+ float oversampling = 1.f;
+ mutable RID_PtrOwner<FontDataAdvanced> font_owner;
+ mutable RID_PtrOwner<ShapedTextDataAdvanced> shaped_owner;
+
+ int _convert_pos(const ShapedTextDataAdvanced *p_sd, int p_pos) const;
+ int _convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int p_pos) const;
+ void _shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_start, int32_t p_end, hb_script_t p_script, hb_direction_t p_direction, Vector<RID> p_fonts, int p_span, int p_fb_index);
+ TextServer::Glyph _shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, RID p_font, int p_font_size);
+
+protected:
+ static void _bind_methods(){};
+
+ void full_copy(ShapedTextDataAdvanced *p_shaped);
+ void invalidate(ShapedTextDataAdvanced *p_shaped);
+
+public:
+ virtual bool has_feature(Feature p_feature) override;
+ virtual String get_name() const override;
+
+ virtual void free(RID p_rid) override;
+ virtual bool has(RID p_rid) override;
+ virtual bool load_support_data(const String &p_filename) override;
+
+#ifdef TOOLS_ENABLED
+ virtual String get_support_data_filename() override { return _MKSTR(ICU_DATA_NAME); };
+ virtual String get_support_data_info() override { return String("ICU break iteration data (") + _MKSTR(ICU_DATA_NAME) + String(")."); };
+ virtual bool save_support_data(const String &p_filename) override;
+#endif
+
+ virtual bool is_locale_right_to_left(const String &p_locale) override;
+
+ virtual int32_t name_to_tag(const String &p_name) override;
+ virtual String tag_to_name(int32_t p_tag) override;
+
+ /* Font interface */
+ virtual RID create_font_system(const String &p_name, int p_base_size = 16) override;
+ virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override;
+ virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override;
+
+ virtual float font_get_height(RID p_font, int p_size) const override;
+ virtual float font_get_ascent(RID p_font, int p_size) const override;
+ virtual float font_get_descent(RID p_font, int p_size) const override;
+
+ virtual float font_get_underline_position(RID p_font, int p_size) const override;
+ virtual float font_get_underline_thickness(RID p_font, int p_size) const override;
+
+ virtual void font_set_antialiased(RID p_font, bool p_antialiased) override;
+ virtual bool font_get_antialiased(RID p_font) const override;
+
+ virtual Dictionary font_get_feature_list(RID p_font) const override;
+ virtual Dictionary font_get_variation_list(RID p_font) const override;
+
+ virtual void font_set_variation(RID p_font, const String &p_name, double p_value) override;
+ virtual double font_get_variation(RID p_font, const String &p_name) const override;
+
+ virtual void font_set_hinting(RID p_font, Hinting p_hinting) override;
+ virtual Hinting font_get_hinting(RID p_font) const override;
+
+ virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override;
+ virtual bool font_get_distance_field_hint(RID p_font) const override;
+
+ virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override;
+ virtual bool font_get_force_autohinter(RID p_font) const override;
+
+ virtual bool font_has_char(RID p_font, char32_t p_char) const override;
+ virtual String font_get_supported_chars(RID p_font) const override;
+
+ virtual bool font_has_outline(RID p_font) const override;
+ virtual float font_get_base_size(RID p_font) const override;
+
+ virtual bool font_is_language_supported(RID p_font, const String &p_language) const override;
+ virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override;
+ virtual bool font_get_language_support_override(RID p_font, const String &p_language) override;
+ virtual void font_remove_language_support_override(RID p_font, const String &p_language) override;
+ Vector<String> font_get_language_support_overrides(RID p_font) override;
+
+ virtual bool font_is_script_supported(RID p_font, const String &p_script) const override;
+ virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override;
+ virtual bool font_get_script_support_override(RID p_font, const String &p_script) override;
+ virtual void font_remove_script_support_override(RID p_font, const String &p_script) override;
+ Vector<String> font_get_script_support_overrides(RID p_font) override;
+
+ virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override;
+ virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override;
+ virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override;
+
+ virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+ virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+
+ virtual float font_get_oversampling() const override;
+ virtual void font_set_oversampling(float p_oversampling) override;
+
+ virtual Vector<String> get_system_fonts() const override;
+
+ /* Shaped text buffer interface */
+
+ virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+
+ virtual void shaped_text_clear(RID p_shaped) override;
+
+ virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override;
+ virtual Direction shaped_text_get_direction(RID p_shaped) const override;
+
+ virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override;
+
+ virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+ virtual Orientation shaped_text_get_orientation(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_control(RID p_shaped) const override;
+
+ virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override;
+ virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override;
+ virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override;
+
+ virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override;
+ virtual RID shaped_text_get_parent(RID p_shaped) const override;
+
+ virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override;
+ virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override;
+
+ virtual bool shaped_text_shape(RID p_shaped) override;
+ virtual bool shaped_text_update_breaks(RID p_shaped) override;
+ virtual bool shaped_text_update_justification_ops(RID p_shaped) override;
+
+ virtual bool shaped_text_is_ready(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override;
+
+ virtual Vector2i shaped_text_get_range(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override;
+
+ virtual Array shaped_text_get_objects(RID p_shaped) const override;
+ virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override;
+
+ virtual Size2 shaped_text_get_size(RID p_shaped) const override;
+ virtual float shaped_text_get_ascent(RID p_shaped) const override;
+ virtual float shaped_text_get_descent(RID p_shaped) const override;
+ virtual float shaped_text_get_width(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_position(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_thickness(RID p_shaped) const override;
+
+ virtual String format_number(const String &p_string, const String &p_language = "") const override;
+ virtual String parse_number(const String &p_string, const String &p_language = "") const override;
+ virtual String percent_sign(const String &p_language = "") const override;
+
+ static TextServer *create_func(Error &r_error, void *p_user_data);
+ static void register_server();
+
+ TextServerAdvanced();
+ ~TextServerAdvanced();
+};
+
+#endif // TEXT_SERVER_ADV_H
diff --git a/modules/text_server_fb/SCsub b/modules/text_server_fb/SCsub
new file mode 100644
index 0000000000..03eccbe7bd
--- /dev/null
+++ b/modules/text_server_fb/SCsub
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+env_text_server_fb = env_modules.Clone()
+env_text_server_fb.Append(
+ CPPPATH=[
+ "#thirdparty/freetype/include",
+ ]
+)
+
+env_text_server_fb.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/text_server_fb/bitmap_font_fb.cpp b/modules/text_server_fb/bitmap_font_fb.cpp
new file mode 100644
index 0000000000..5c691b7bbd
--- /dev/null
+++ b/modules/text_server_fb/bitmap_font_fb.cpp
@@ -0,0 +1,356 @@
+/*************************************************************************/
+/* bitmap_font_fb.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "bitmap_font_fb.h"
+
+Error BitmapFontDataFallback::load_from_file(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ //fnt format used by angelcode bmfont
+ //http://www.angelcode.com/products/bmfont/
+
+ FileAccess *f = FileAccess::open(p_filename, FileAccess::READ);
+ ERR_FAIL_COND_V_MSG(!f, ERR_FILE_NOT_FOUND, "Can't open font: " + p_filename + ".");
+
+ while (true) {
+ String line = f->get_line();
+
+ int delimiter = line.find(" ");
+ String type = line.substr(0, delimiter);
+ int pos = delimiter + 1;
+ Map<String, String> keys;
+
+ while (pos < line.size() && line[pos] == ' ') {
+ pos++;
+ }
+
+ while (pos < line.size()) {
+ int eq = line.find("=", pos);
+ if (eq == -1) {
+ break;
+ }
+ String key = line.substr(pos, eq - pos);
+ int end = -1;
+ String value;
+ if (line[eq + 1] == '"') {
+ end = line.find("\"", eq + 2);
+ if (end == -1) {
+ break;
+ }
+ value = line.substr(eq + 2, end - 1 - eq - 1);
+ pos = end + 1;
+ } else {
+ end = line.find(" ", eq + 1);
+ if (end == -1) {
+ end = line.size();
+ }
+ value = line.substr(eq + 1, end - eq);
+ pos = end;
+ }
+
+ while (pos < line.size() && line[pos] == ' ') {
+ pos++;
+ }
+
+ keys[key] = value;
+ }
+
+ if (type == "info") {
+ if (keys.has("size")) {
+ base_size = keys["size"].to_int();
+ }
+ } else if (type == "common") {
+ if (keys.has("lineHeight")) {
+ height = keys["lineHeight"].to_int();
+ }
+ if (keys.has("base")) {
+ ascent = keys["base"].to_int();
+ }
+ } else if (type == "page") {
+ if (keys.has("file")) {
+ String base_dir = p_filename.get_base_dir();
+ String file = base_dir.plus_file(keys["file"]);
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Texture2D> tex = ResourceLoader::load(file);
+ if (tex.is_null()) {
+ ERR_PRINT("Can't load font texture!");
+ } else {
+ ERR_FAIL_COND_V_MSG(tex.is_null(), ERR_FILE_CANT_READ, "It's not a reference to a valid Texture object.");
+ textures.push_back(tex);
+ }
+ }
+ }
+ } else if (type == "char") {
+ Character c;
+ char32_t idx = 0;
+ if (keys.has("id")) {
+ idx = keys["id"].to_int();
+ }
+ if (keys.has("x")) {
+ c.rect.position.x = keys["x"].to_int();
+ }
+ if (keys.has("y")) {
+ c.rect.position.y = keys["y"].to_int();
+ }
+ if (keys.has("width")) {
+ c.rect.size.width = keys["width"].to_int();
+ }
+ if (keys.has("height")) {
+ c.rect.size.height = keys["height"].to_int();
+ }
+ if (keys.has("xoffset")) {
+ c.align.x = keys["xoffset"].to_int();
+ }
+ if (keys.has("yoffset")) {
+ c.align.y = keys["yoffset"].to_int();
+ }
+ if (keys.has("page")) {
+ c.texture_idx = keys["page"].to_int();
+ }
+ if (keys.has("xadvance")) {
+ c.advance.x = keys["xadvance"].to_int();
+ }
+ if (keys.has("yadvance")) {
+ c.advance.y = keys["yadvance"].to_int();
+ }
+ if (c.advance.x < 0) {
+ c.advance.x = c.rect.size.width + 1;
+ }
+ if (c.advance.y < 0) {
+ c.advance.y = c.rect.size.height + 1;
+ }
+ char_map[idx] = c;
+ } else if (type == "kerning") {
+ KerningPairKey kpk;
+ float k = 0;
+ if (keys.has("first")) {
+ kpk.A = keys["first"].to_int();
+ }
+ if (keys.has("second")) {
+ kpk.B = keys["second"].to_int();
+ }
+ if (keys.has("amount")) {
+ k = keys["amount"].to_int();
+ }
+ kerning_map[kpk] = k;
+ }
+
+ if (f->eof_reached()) {
+ break;
+ }
+ }
+ if (base_size == 0) {
+ base_size = height;
+ }
+
+ valid = true;
+
+ memdelete(f);
+ return OK;
+}
+
+Error BitmapFontDataFallback::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(p_data == nullptr, ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(p_size != sizeof(TextServer::BitmapFontData), ERR_CANT_CREATE);
+
+ const TextServer::BitmapFontData *data = (const TextServer::BitmapFontData *)p_data;
+
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Image> image = memnew(Image(data->img));
+ Ref<ImageTexture> tex = memnew(ImageTexture);
+ tex->create_from_image(image);
+
+ textures.push_back(tex);
+ }
+
+ for (int i = 0; i < data->charcount; i++) {
+ const int *c = &data->char_rects[i * 8];
+
+ Character chr;
+ chr.rect.position.x = c[1];
+ chr.rect.position.y = c[2];
+ chr.rect.size.x = c[3];
+ chr.rect.size.y = c[4];
+ if (c[7] < 0) {
+ chr.advance.x = c[3];
+ } else {
+ chr.advance.x = c[7];
+ }
+ chr.align = Vector2(c[6], c[5]);
+ char_map[c[0]] = chr;
+ }
+
+ for (int i = 0; i < data->kerning_count; i++) {
+ KerningPairKey kpk;
+ kpk.A = data->kernings[i * 3 + 0];
+ kpk.B = data->kernings[i * 3 + 1];
+
+ if (data->kernings[i * 3 + 2] == 0 && kerning_map.has(kpk)) {
+ kerning_map.erase(kpk);
+ } else {
+ kerning_map[kpk] = data->kernings[i * 3 + 2];
+ }
+ }
+
+ height = data->height;
+ ascent = data->ascent;
+
+ base_size = p_base_size;
+ if (base_size == 0) {
+ base_size = height;
+ }
+
+ valid = true;
+
+ return OK;
+}
+
+float BitmapFontDataFallback::get_height(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return height * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataFallback::get_ascent(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return ascent * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataFallback::get_descent(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return (height - ascent) * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataFallback::get_underline_position(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return 2 * (float(p_size) / float(base_size));
+}
+
+float BitmapFontDataFallback::get_underline_thickness(int p_size) const {
+ ERR_FAIL_COND_V(!valid, 0.f);
+ return 1 * (float(p_size) / float(base_size));
+}
+
+void BitmapFontDataFallback::set_distance_field_hint(bool p_distance_field) {
+ distance_field_hint = p_distance_field;
+}
+
+bool BitmapFontDataFallback::get_distance_field_hint() const {
+ return distance_field_hint;
+}
+
+float BitmapFontDataFallback::get_base_size() const {
+ return base_size;
+}
+
+bool BitmapFontDataFallback::has_char(char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, false);
+ return char_map.has(p_char);
+}
+
+String BitmapFontDataFallback::get_supported_chars() const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, String());
+ String chars;
+ const char32_t *k = nullptr;
+ while ((k = char_map.next(k))) {
+ chars += char32_t(*k);
+ }
+ return chars;
+}
+
+Vector2 BitmapFontDataFallback::get_advance(char32_t p_char, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_char);
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+
+ return c->advance * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataFallback::get_kerning(char32_t p_char, char32_t p_next, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND_V(!valid, Vector2());
+ KerningPairKey kpk;
+ kpk.A = p_char;
+ kpk.B = p_next;
+
+ const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
+ if (E) {
+ return Vector2(-E->get() * (float(p_size) / float(base_size)), 0);
+ } else {
+ return Vector2();
+ }
+}
+
+Vector2 BitmapFontDataFallback::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ if (p_index == 0) {
+ return Vector2();
+ }
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_index);
+
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2());
+ if (c->texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += c->align * (float(p_size) / float(base_size));
+ cpos.y -= ascent * (float(p_size) / float(base_size));
+
+ if (RenderingServer::get_singleton() != nullptr) {
+ //if (distance_field_hint) { // Not implemented.
+ // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, true);
+ //}
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, c->rect.size * (float(p_size) / float(base_size))), textures[c->texture_idx]->get_rid(), c->rect, p_color, false, false);
+ //if (distance_field_hint) {
+ // RenderingServer::get_singleton()->canvas_item_set_distance_field_mode(p_canvas, false);
+ //}
+ }
+ }
+
+ return c->advance * (float(p_size) / float(base_size));
+}
+
+Vector2 BitmapFontDataFallback::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ if (p_index == 0) {
+ return Vector2();
+ }
+ ERR_FAIL_COND_V(!valid, Vector2());
+ const Character *c = char_map.getptr(p_index);
+
+ ERR_FAIL_COND_V(c == nullptr, Vector2());
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), Vector2());
+
+ // Not supported, return advance for compatibility.
+
+ return c->advance * (float(p_size) / float(base_size));
+}
diff --git a/modules/text_server_fb/bitmap_font_fb.h b/modules/text_server_fb/bitmap_font_fb.h
new file mode 100644
index 0000000000..33401b85fa
--- /dev/null
+++ b/modules/text_server_fb/bitmap_font_fb.h
@@ -0,0 +1,107 @@
+/*************************************************************************/
+/* bitmap_font_fb.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 BITMAP_FONT_FALLBACK_H
+#define BITMAP_FONT_FALLBACK_H
+
+#include "font_fb.h"
+
+struct BitmapFontDataFallback : public FontDataFallback {
+ _THREAD_SAFE_CLASS_
+
+private:
+ Vector<Ref<Texture2D>> textures;
+
+ struct Character {
+ int texture_idx = 0;
+ Rect2 rect;
+ Vector2 align;
+ Vector2 advance = Vector2(-1, -1);
+ };
+
+ struct KerningPairKey {
+ union {
+ struct {
+ uint32_t A, B;
+ };
+
+ uint64_t pair = 0;
+ };
+
+ _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; }
+ };
+
+ HashMap<char32_t, Character> char_map;
+ Map<KerningPairKey, int> kerning_map;
+
+ float height = 0.f;
+ float ascent = 0.f;
+ int base_size = 0;
+ bool distance_field_hint = false;
+
+public:
+ virtual void clear_cache() override{};
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) override;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override;
+
+ virtual float get_height(int p_size) const override;
+ virtual float get_ascent(int p_size) const override;
+ virtual float get_descent(int p_size) const override;
+
+ virtual float get_underline_position(int p_size) const override;
+ virtual float get_underline_thickness(int p_size) const override;
+
+ virtual void set_antialiased(bool p_antialiased) override{};
+ virtual bool get_antialiased() const override { return false; };
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) override{};
+ virtual TextServer::Hinting get_hinting() const override { return TextServer::HINTING_NONE; };
+
+ virtual void set_distance_field_hint(bool p_distance_field) override;
+ virtual bool get_distance_field_hint() const override;
+
+ virtual void set_force_autohinter(bool p_enabeld) override{};
+ virtual bool get_force_autohinter() const override { return false; };
+
+ virtual bool has_outline() const override { return false; };
+ virtual float get_base_size() const override;
+
+ virtual bool has_char(char32_t p_char) const override;
+ virtual String get_supported_chars() const override;
+
+ virtual Vector2 get_advance(char32_t p_char, int p_size) const override;
+ virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const override;
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+};
+
+#endif // BITMAP_FONT_FALLBACK_H
diff --git a/modules/text_server_fb/config.py b/modules/text_server_fb/config.py
new file mode 100644
index 0000000000..491377a369
--- /dev/null
+++ b/modules/text_server_fb/config.py
@@ -0,0 +1,11 @@
+def can_build(env, platform):
+ return env.module_check_dependencies("text_server_fb", ["freetype"])
+
+
+def configure(env):
+ pass
+
+
+def is_enabled():
+ # The module is disabled by default. Use module_text_server_fb_enabled=yes to enable it.
+ return False
diff --git a/modules/text_server_fb/dynamic_font_fb.cpp b/modules/text_server_fb/dynamic_font_fb.cpp
new file mode 100644
index 0000000000..4eecba6ae8
--- /dev/null
+++ b/modules/text_server_fb/dynamic_font_fb.cpp
@@ -0,0 +1,685 @@
+/*************************************************************************/
+/* dynamic_font_fb.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "dynamic_font_fb.h"
+
+#include FT_STROKER_H
+#include FT_ADVANCES_H
+
+DynamicFontDataFallback::DataAtSize *DynamicFontDataFallback::get_data_for_size(int p_size, int p_outline_size) {
+ ERR_FAIL_COND_V(!valid, nullptr);
+ ERR_FAIL_COND_V(p_size < 0 || p_size > UINT16_MAX, nullptr);
+ ERR_FAIL_COND_V(p_outline_size < 0 || p_outline_size > UINT16_MAX, nullptr);
+
+ CacheID id;
+ id.size = p_size;
+ id.outline_size = p_outline_size;
+
+ DataAtSize *fds = nullptr;
+ Map<CacheID, DataAtSize *>::Element *E = nullptr;
+ if (p_outline_size != 0) {
+ E = size_cache_outline.find(id);
+ } else {
+ E = size_cache.find(id);
+ }
+
+ if (E != nullptr) {
+ fds = E->get();
+ } else {
+ if (font_mem == nullptr && font_path != String()) {
+ if (!font_mem_cache.is_empty()) {
+ font_mem = font_mem_cache.ptr();
+ font_mem_size = font_mem_cache.size();
+ } else {
+ FileAccess *f = FileAccess::open(font_path, FileAccess::READ);
+ if (!f) {
+ ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'.");
+ }
+
+ size_t len = f->get_len();
+ font_mem_cache.resize(len);
+ f->get_buffer(font_mem_cache.ptrw(), len);
+ font_mem = font_mem_cache.ptr();
+ font_mem_size = len;
+ f->close();
+ }
+ }
+
+ int error = 0;
+ fds = memnew(DataAtSize);
+ if (font_mem) {
+ memset(&fds->stream, 0, sizeof(FT_StreamRec));
+ fds->stream.base = (unsigned char *)font_mem;
+ fds->stream.size = font_mem_size;
+ fds->stream.pos = 0;
+
+ FT_Open_Args fargs;
+ memset(&fargs, 0, sizeof(FT_Open_Args));
+ fargs.memory_base = (unsigned char *)font_mem;
+ fargs.memory_size = font_mem_size;
+ fargs.flags = FT_OPEN_MEMORY;
+ fargs.stream = &fds->stream;
+ error = FT_Open_Face(library, &fargs, 0, &fds->face);
+
+ } else {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "DynamicFont uninitialized.");
+ }
+
+ if (error == FT_Err_Unknown_File_Format) {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "Unknown font format.");
+
+ } else if (error) {
+ memdelete(fds);
+ ERR_FAIL_V_MSG(nullptr, "Error loading font.");
+ }
+
+ oversampling = TS->font_get_oversampling();
+
+ if (FT_HAS_COLOR(fds->face) && fds->face->num_fixed_sizes > 0) {
+ int best_match = 0;
+ int diff = ABS(p_size - ((int64_t)fds->face->available_sizes[0].width));
+ fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[0].width;
+ for (int i = 1; i < fds->face->num_fixed_sizes; i++) {
+ int ndiff = ABS(p_size - ((int64_t)fds->face->available_sizes[i].width));
+ if (ndiff < diff) {
+ best_match = i;
+ diff = ndiff;
+ fds->scale_color_font = float(p_size * oversampling) / fds->face->available_sizes[i].width;
+ }
+ }
+ FT_Select_Size(fds->face, best_match);
+ } else {
+ FT_Set_Pixel_Sizes(fds->face, 0, p_size * oversampling);
+ }
+
+ fds->size = p_size;
+ fds->ascent = (fds->face->size->metrics.ascender / 64.0) / oversampling * fds->scale_color_font;
+ fds->descent = (-fds->face->size->metrics.descender / 64.0) / oversampling * fds->scale_color_font;
+ fds->underline_position = -fds->face->underline_position / 64.0 / oversampling * fds->scale_color_font;
+ fds->underline_thickness = fds->face->underline_thickness / 64.0 / oversampling * fds->scale_color_font;
+ if (p_outline_size != 0) {
+ size_cache_outline[id] = fds;
+ } else {
+ size_cache[id] = fds;
+ }
+ }
+
+ return fds;
+}
+
+DynamicFontDataFallback::TexturePosition DynamicFontDataFallback::find_texture_pos_for_glyph(DynamicFontDataFallback::DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height) {
+ TexturePosition ret;
+ ret.index = -1;
+
+ int mw = p_width;
+ int mh = p_height;
+
+ for (int i = 0; i < p_data->textures.size(); i++) {
+ const CharTexture &ct = p_data->textures[i];
+
+ if (RenderingServer::get_singleton() != nullptr) {
+ if (ct.texture->get_format() != p_image_format) {
+ continue;
+ }
+ }
+
+ if (mw > ct.texture_size || mh > ct.texture_size) { //too big for this texture
+ continue;
+ }
+
+ ret.y = 0x7FFFFFFF;
+ ret.x = 0;
+
+ for (int j = 0; j < ct.texture_size - mw; j++) {
+ int max_y = 0;
+
+ for (int k = j; k < j + mw; k++) {
+ int y = ct.offsets[k];
+ if (y > max_y) {
+ max_y = y;
+ }
+ }
+
+ if (max_y < ret.y) {
+ ret.y = max_y;
+ ret.x = j;
+ }
+ }
+
+ if (ret.y == 0x7FFFFFFF || ret.y + mh > ct.texture_size) {
+ continue; //fail, could not fit it here
+ }
+
+ ret.index = i;
+ break;
+ }
+
+ if (ret.index == -1) {
+ //could not find texture to fit, create one
+ ret.x = 0;
+ ret.y = 0;
+
+ int texsize = MAX(p_data->size * oversampling * 8, 256);
+ if (mw > texsize) {
+ texsize = mw; //special case, adapt to it?
+ }
+ if (mh > texsize) {
+ texsize = mh; //special case, adapt to it?
+ }
+
+ texsize = next_power_of_2(texsize);
+
+ texsize = MIN(texsize, 4096);
+
+ CharTexture tex;
+ tex.texture_size = texsize;
+ tex.imgdata.resize(texsize * texsize * p_color_size); //grayscale alpha
+
+ {
+ //zero texture
+ uint8_t *w = tex.imgdata.ptrw();
+ ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.imgdata.size(), ret);
+ // Initialize the texture to all-white pixels to prevent artifacts when the
+ // font is displayed at a non-default scale with filtering enabled.
+ if (p_color_size == 2) {
+ for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8
+ w[i + 0] = 255;
+ w[i + 1] = 0;
+ }
+ } else if (p_color_size == 4) {
+ for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8
+ w[i + 0] = 255;
+ w[i + 1] = 255;
+ w[i + 2] = 255;
+ w[i + 3] = 0;
+ }
+ } else {
+ ERR_FAIL_V(ret);
+ }
+ }
+ tex.offsets.resize(texsize);
+ for (int i = 0; i < texsize; i++) { //zero offsets
+ tex.offsets.write[i] = 0;
+ }
+
+ p_data->textures.push_back(tex);
+ ret.index = p_data->textures.size() - 1;
+ }
+
+ return ret;
+}
+
+DynamicFontDataFallback::Character DynamicFontDataFallback::Character::not_found() {
+ Character ch;
+ return ch;
+}
+
+DynamicFontDataFallback::Character DynamicFontDataFallback::bitmap_to_character(DynamicFontDataFallback::DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance) {
+ int w = bitmap.width;
+ int h = bitmap.rows;
+
+ int mw = w + rect_margin * 2;
+ int mh = h + rect_margin * 2;
+
+ ERR_FAIL_COND_V(mw > 4096, Character::not_found());
+ ERR_FAIL_COND_V(mh > 4096, Character::not_found());
+
+ int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2;
+ Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
+
+ TexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh);
+ ERR_FAIL_COND_V(tex_pos.index < 0, Character::not_found());
+
+ //fit character in char texture
+
+ CharTexture &tex = p_data->textures.write[tex_pos.index];
+
+ {
+ uint8_t *wr = tex.imgdata.ptrw();
+
+ for (int i = 0; i < h; i++) {
+ for (int j = 0; j < w; j++) {
+ int ofs = ((i + tex_pos.y + rect_margin) * tex.texture_size + j + tex_pos.x + rect_margin) * color_size;
+ ERR_FAIL_COND_V(ofs >= tex.imgdata.size(), Character::not_found());
+ switch (bitmap.pixel_mode) {
+ case FT_PIXEL_MODE_MONO: {
+ int byte = i * bitmap.pitch + (j >> 3);
+ int bit = 1 << (7 - (j % 8));
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = (bitmap.buffer[byte] & bit) ? 255 : 0;
+ } break;
+ case FT_PIXEL_MODE_GRAY:
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = bitmap.buffer[i * bitmap.pitch + j];
+ break;
+ case FT_PIXEL_MODE_BGRA: {
+ int ofs_color = i * bitmap.pitch + (j << 2);
+ wr[ofs + 2] = bitmap.buffer[ofs_color + 0];
+ wr[ofs + 1] = bitmap.buffer[ofs_color + 1];
+ wr[ofs + 0] = bitmap.buffer[ofs_color + 2];
+ wr[ofs + 3] = bitmap.buffer[ofs_color + 3];
+ } break;
+ // TODO: FT_PIXEL_MODE_LCD
+ default:
+ ERR_FAIL_V_MSG(Character::not_found(), "Font uses unsupported pixel format: " + itos(bitmap.pixel_mode) + ".");
+ break;
+ }
+ }
+ }
+ }
+
+ //blit to image and texture
+ {
+ if (RenderingServer::get_singleton() != nullptr) {
+ Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata));
+
+ if (tex.texture.is_null()) {
+ tex.texture.instance();
+ tex.texture->create_from_image(img);
+ } else {
+ tex.texture->update(img); //update
+ }
+ }
+ }
+
+ // update height array
+ for (int k = tex_pos.x; k < tex_pos.x + mw; k++) {
+ tex.offsets.write[k] = tex_pos.y + mh;
+ }
+
+ Character chr;
+ chr.align = (Vector2(xofs, -yofs) * p_data->scale_color_font / oversampling).round();
+ chr.advance = (advance * p_data->scale_color_font / oversampling).round();
+ chr.texture_idx = tex_pos.index;
+ chr.found = true;
+
+ chr.rect_uv = Rect2(tex_pos.x + rect_margin, tex_pos.y + rect_margin, w, h);
+ chr.rect = chr.rect_uv;
+ chr.rect.position /= oversampling;
+ chr.rect.size *= (p_data->scale_color_font / oversampling);
+ return chr;
+}
+
+void DynamicFontDataFallback::update_char(int p_size, char32_t p_char) {
+ DataAtSize *fds = get_data_for_size(p_size, false);
+ ERR_FAIL_COND(fds == nullptr);
+
+ if (fds->char_map.has(p_char)) {
+ return;
+ }
+
+ Character character = Character::not_found();
+
+ FT_GlyphSlot slot = fds->face->glyph;
+ FT_UInt gl_index = FT_Get_Char_Index(fds->face, p_char);
+
+ if (gl_index == 0) {
+ fds->char_map[p_char] = character;
+ return;
+ }
+
+ int ft_hinting;
+ switch (hinting) {
+ case TextServer::HINTING_NONE:
+ ft_hinting = FT_LOAD_NO_HINTING;
+ break;
+ case TextServer::HINTING_LIGHT:
+ ft_hinting = FT_LOAD_TARGET_LIGHT;
+ break;
+ default:
+ ft_hinting = FT_LOAD_TARGET_NORMAL;
+ break;
+ }
+
+ FT_Fixed v, h;
+ FT_Get_Advance(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting, &h);
+ FT_Get_Advance(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting | FT_LOAD_VERTICAL_LAYOUT, &v);
+
+ int error = FT_Load_Glyph(fds->face, gl_index, FT_HAS_COLOR(fds->face) ? FT_LOAD_COLOR : FT_LOAD_DEFAULT | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0) | ft_hinting);
+ if (error) {
+ fds->char_map[p_char] = character;
+ return;
+ }
+
+ error = FT_Render_Glyph(fds->face->glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
+ if (!error) {
+ character = bitmap_to_character(fds, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
+ }
+
+ fds->char_map[p_char] = character;
+}
+
+void DynamicFontDataFallback::update_char_outline(int p_size, int p_outline_size, char32_t p_char) {
+ DataAtSize *fds = get_data_for_size(p_size, p_outline_size);
+ ERR_FAIL_COND(fds == nullptr);
+
+ if (fds->char_map.has(p_char)) {
+ return;
+ }
+
+ Character character = Character::not_found();
+ FT_UInt gl_index = FT_Get_Char_Index(fds->face, p_char);
+
+ if (gl_index == 0) {
+ fds->char_map[p_char] = character;
+ return;
+ }
+
+ int error = FT_Load_Glyph(fds->face, gl_index, FT_LOAD_NO_BITMAP | (force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
+ if (error) {
+ fds->char_map[p_char] = character;
+ return;
+ }
+
+ FT_Stroker stroker;
+ if (FT_Stroker_New(library, &stroker) != 0) {
+ fds->char_map[p_char] = character;
+ return;
+ }
+
+ FT_Stroker_Set(stroker, (int)(p_outline_size * oversampling * 64.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
+ FT_Glyph glyph;
+ FT_BitmapGlyph glyph_bitmap;
+
+ if (FT_Get_Glyph(fds->face->glyph, &glyph) != 0) {
+ goto cleanup_stroker;
+ }
+ if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
+ goto cleanup_glyph;
+ }
+ if (FT_Glyph_To_Bitmap(&glyph, antialiased ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO, nullptr, 1) != 0) {
+ goto cleanup_glyph;
+ }
+
+ glyph_bitmap = (FT_BitmapGlyph)glyph;
+ character = bitmap_to_character(fds, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2());
+
+cleanup_glyph:
+ FT_Done_Glyph(glyph);
+cleanup_stroker:
+ FT_Stroker_Done(stroker);
+
+ fds->char_map[p_char] = character;
+}
+
+void DynamicFontDataFallback::clear_cache() {
+ _THREAD_SAFE_METHOD_
+ for (Map<CacheID, DataAtSize *>::Element *E = size_cache.front(); E; E = E->next()) {
+ memdelete(E->get());
+ }
+ size_cache.clear();
+ for (Map<CacheID, DataAtSize *>::Element *E = size_cache_outline.front(); E; E = E->next()) {
+ memdelete(E->get());
+ }
+ size_cache_outline.clear();
+}
+
+Error DynamicFontDataFallback::load_from_file(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ if (library == nullptr) {
+ int error = FT_Init_FreeType(&library);
+ ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
+ }
+ clear_cache();
+
+ font_path = p_filename;
+ base_size = p_base_size;
+
+ valid = true;
+ DataAtSize *fds = get_data_for_size(base_size); // load base size.
+ if (fds == nullptr) {
+ valid = false;
+ ERR_FAIL_V(ERR_CANT_CREATE);
+ }
+
+ return OK;
+}
+
+Error DynamicFontDataFallback::load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ if (library == nullptr) {
+ int error = FT_Init_FreeType(&library);
+ ERR_FAIL_COND_V_MSG(error != 0, ERR_CANT_CREATE, "Error initializing FreeType.");
+ }
+ clear_cache();
+
+ font_mem = p_data;
+ font_mem_size = p_size;
+ base_size = p_base_size;
+
+ valid = true;
+ DataAtSize *fds = get_data_for_size(base_size); // load base size.
+ if (fds == nullptr) {
+ valid = false;
+ ERR_FAIL_V(ERR_CANT_CREATE);
+ }
+
+ return OK;
+}
+
+float DynamicFontDataFallback::get_height(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->ascent + fds->descent;
+}
+
+float DynamicFontDataFallback::get_ascent(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->ascent;
+}
+
+float DynamicFontDataFallback::get_descent(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->descent;
+}
+
+float DynamicFontDataFallback::get_underline_position(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->underline_position;
+}
+
+float DynamicFontDataFallback::get_underline_thickness(int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, 0.f);
+ return fds->underline_thickness;
+}
+
+void DynamicFontDataFallback::set_antialiased(bool p_antialiased) {
+ if (antialiased != p_antialiased) {
+ clear_cache();
+ antialiased = p_antialiased;
+ }
+}
+
+bool DynamicFontDataFallback::get_antialiased() const {
+ return antialiased;
+}
+
+void DynamicFontDataFallback::set_force_autohinter(bool p_enabled) {
+ if (force_autohinter != p_enabled) {
+ clear_cache();
+ force_autohinter = p_enabled;
+ }
+}
+
+bool DynamicFontDataFallback::get_force_autohinter() const {
+ return force_autohinter;
+}
+
+void DynamicFontDataFallback::set_hinting(TextServer::Hinting p_hinting) {
+ if (hinting != p_hinting) {
+ clear_cache();
+ hinting = p_hinting;
+ }
+}
+
+TextServer::Hinting DynamicFontDataFallback::get_hinting() const {
+ return hinting;
+}
+
+bool DynamicFontDataFallback::has_outline() const {
+ return true;
+}
+
+float DynamicFontDataFallback::get_base_size() const {
+ return base_size;
+}
+
+bool DynamicFontDataFallback::has_char(char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, false);
+
+ const_cast<DynamicFontDataFallback *>(this)->update_char(base_size, p_char);
+ Character ch = fds->char_map[p_char];
+
+ return (ch.found);
+}
+
+String DynamicFontDataFallback::get_supported_chars() const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(base_size);
+ ERR_FAIL_COND_V(fds == nullptr, String());
+
+ String chars;
+
+ FT_UInt gindex;
+ FT_ULong charcode = FT_Get_First_Char(fds->face, &gindex);
+ while (gindex != 0) {
+ if (charcode != 0) {
+ chars += char32_t(charcode);
+ }
+ charcode = FT_Get_Next_Char(fds->face, charcode, &gindex);
+ }
+
+ return chars;
+}
+
+Vector2 DynamicFontDataFallback::get_advance(char32_t p_char, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataFallback *>(this)->update_char(p_size, p_char);
+ Character ch = fds->char_map[p_char];
+
+ return ch.advance;
+}
+
+Vector2 DynamicFontDataFallback::get_kerning(char32_t p_char, char32_t p_next, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ FT_Vector delta;
+ FT_Get_Kerning(fds->face, FT_Get_Char_Index(fds->face, p_char), FT_Get_Char_Index(fds->face, p_next), FT_KERNING_DEFAULT, &delta);
+ return Vector2(delta.x, delta.y);
+}
+
+Vector2 DynamicFontDataFallback::draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataFallback *>(this)->update_char(p_size, p_index);
+ Character ch = fds->char_map[p_index];
+
+ Vector2 advance;
+ if (ch.found) {
+ ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2());
+
+ if (ch.texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += ch.align;
+
+ Color modulate = p_color;
+ if (FT_HAS_COLOR(fds->face)) {
+ modulate.r = modulate.g = modulate.b = 1.0;
+ }
+ if (RenderingServer::get_singleton() != nullptr) {
+ RID texture = fds->textures[ch.texture_idx].texture->get_rid();
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false);
+ }
+ }
+
+ advance = ch.advance;
+ }
+
+ return advance;
+}
+
+Vector2 DynamicFontDataFallback::draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ DataAtSize *fds = const_cast<DynamicFontDataFallback *>(this)->get_data_for_size(p_size, p_outline_size);
+ ERR_FAIL_COND_V(fds == nullptr, Vector2());
+
+ const_cast<DynamicFontDataFallback *>(this)->update_char_outline(p_size, p_outline_size, p_index);
+ Character ch = fds->char_map[p_index];
+
+ Vector2 advance;
+ if (ch.found) {
+ ERR_FAIL_COND_V(ch.texture_idx < -1 || ch.texture_idx >= fds->textures.size(), Vector2());
+
+ if (ch.texture_idx != -1) {
+ Point2 cpos = p_pos;
+ cpos += ch.align;
+
+ Color modulate = p_color;
+ if (FT_HAS_COLOR(fds->face)) {
+ modulate.r = modulate.g = modulate.b = 1.0;
+ }
+ if (RenderingServer::get_singleton() != nullptr) {
+ RID texture = fds->textures[ch.texture_idx].texture->get_rid();
+ RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, ch.rect.size), texture, ch.rect_uv, modulate, false, false);
+ }
+ }
+
+ advance = ch.advance;
+ }
+
+ return advance;
+}
+
+DynamicFontDataFallback::~DynamicFontDataFallback() {
+ clear_cache();
+ if (library != nullptr) {
+ FT_Done_FreeType(library);
+ }
+}
diff --git a/modules/text_server_fb/dynamic_font_fb.h b/modules/text_server_fb/dynamic_font_fb.h
new file mode 100644
index 0000000000..f1cd758f2c
--- /dev/null
+++ b/modules/text_server_fb/dynamic_font_fb.h
@@ -0,0 +1,169 @@
+/*************************************************************************/
+/* dynamic_font_fb.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 DYNAMIC_FONT_FALLBACK_H
+#define DYNAMIC_FONT_FALLBACK_H
+
+#include "font_fb.h"
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+struct DynamicFontDataFallback : public FontDataFallback {
+ _THREAD_SAFE_CLASS_
+
+private:
+ struct CharTexture {
+ Vector<uint8_t> imgdata;
+ int texture_size = 0;
+ Vector<int> offsets;
+ Ref<ImageTexture> texture;
+ };
+
+ struct Character {
+ bool found = false;
+ int texture_idx = 0;
+ Rect2 rect;
+ Rect2 rect_uv;
+ Vector2 align;
+ Vector2 advance = Vector2(-1, -1);
+
+ static Character not_found();
+ };
+
+ struct TexturePosition {
+ int index = 0;
+ int x = 0;
+ int y = 0;
+ };
+
+ struct CacheID {
+ union {
+ struct {
+ uint32_t size : 16;
+ uint32_t outline_size : 16;
+ };
+ uint32_t key;
+ };
+ bool operator<(CacheID right) const {
+ return key < right.key;
+ }
+ CacheID() {
+ key = 0;
+ }
+ };
+
+ struct DataAtSize {
+ FT_Face face = nullptr;
+ FT_StreamRec stream;
+
+ int size = 0;
+ float scale_color_font = 1.f;
+ float ascent = 0;
+ float descent = 0;
+ float underline_position = 0;
+ float underline_thickness = 0;
+
+ Vector<CharTexture> textures;
+ HashMap<char32_t, Character> char_map;
+
+ ~DataAtSize() {
+ if (face != nullptr) {
+ FT_Done_Face(face);
+ }
+ }
+ };
+
+ FT_Library library = nullptr;
+
+ // Source data.
+ const uint8_t *font_mem = nullptr;
+ int font_mem_size = 0;
+ String font_path;
+ Vector<uint8_t> font_mem_cache;
+
+ float rect_margin = 1.f;
+ int base_size = 16;
+ float oversampling = 1.f;
+ bool antialiased = true;
+ bool force_autohinter = false;
+ TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
+
+ Map<CacheID, DataAtSize *> size_cache;
+ Map<CacheID, DataAtSize *> size_cache_outline;
+
+ DataAtSize *get_data_for_size(int p_size, int p_outline_size = 0);
+
+ TexturePosition find_texture_pos_for_glyph(DataAtSize *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height);
+ Character bitmap_to_character(DataAtSize *p_data, FT_Bitmap bitmap, int yofs, int xofs, const Vector2 &advance);
+ _FORCE_INLINE_ void update_char(int p_size, char32_t p_char);
+ _FORCE_INLINE_ void update_char_outline(int p_size, int p_outline_size, char32_t p_char);
+
+public:
+ virtual void clear_cache() override;
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) override;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) override;
+
+ virtual float get_height(int p_size) const override;
+ virtual float get_ascent(int p_size) const override;
+ virtual float get_descent(int p_size) const override;
+
+ virtual float get_underline_position(int p_size) const override;
+ virtual float get_underline_thickness(int p_size) const override;
+
+ virtual void set_antialiased(bool p_antialiased) override;
+ virtual bool get_antialiased() const override;
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) override;
+ virtual TextServer::Hinting get_hinting() const override;
+
+ virtual void set_force_autohinter(bool p_enabeld) override;
+ virtual bool get_force_autohinter() const override;
+
+ virtual void set_distance_field_hint(bool p_distance_field) override{};
+ virtual bool get_distance_field_hint() const override { return false; };
+
+ virtual bool has_outline() const override;
+ virtual float get_base_size() const override;
+
+ virtual bool has_char(char32_t p_char) const override;
+ virtual String get_supported_chars() const override;
+
+ virtual Vector2 get_advance(char32_t p_char, int p_size) const override;
+ virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const override;
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const override;
+
+ virtual ~DynamicFontDataFallback() override;
+};
+
+#endif // DYNAMIC_FONT_FALLBACK_H
diff --git a/modules/text_server_fb/font_fb.h b/modules/text_server_fb/font_fb.h
new file mode 100644
index 0000000000..cc72919542
--- /dev/null
+++ b/modules/text_server_fb/font_fb.h
@@ -0,0 +1,80 @@
+/*************************************************************************/
+/* font_fb.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 FONT_FALLBACK_H
+#define FONT_FALLBACK_H
+
+#include "servers/text_server.h"
+
+struct FontDataFallback {
+ Map<String, bool> lang_support_overrides;
+ Map<String, bool> script_support_overrides;
+ bool valid = false;
+
+ virtual void clear_cache() = 0;
+
+ virtual Error load_from_file(const String &p_filename, int p_base_size) = 0;
+ virtual Error load_from_memory(const uint8_t *p_data, size_t p_size, int p_base_size) = 0;
+
+ virtual float get_height(int p_size) const = 0;
+ virtual float get_ascent(int p_size) const = 0;
+ virtual float get_descent(int p_size) const = 0;
+
+ virtual float get_underline_position(int p_size) const = 0;
+ virtual float get_underline_thickness(int p_size) const = 0;
+
+ virtual void set_antialiased(bool p_antialiased) = 0;
+ virtual bool get_antialiased() const = 0;
+
+ virtual void set_hinting(TextServer::Hinting p_hinting) = 0;
+ virtual TextServer::Hinting get_hinting() const = 0;
+
+ virtual void set_distance_field_hint(bool p_distance_field) = 0;
+ virtual bool get_distance_field_hint() const = 0;
+
+ virtual void set_force_autohinter(bool p_enabeld) = 0;
+ virtual bool get_force_autohinter() const = 0;
+
+ virtual bool has_outline() const = 0;
+ virtual float get_base_size() const = 0;
+
+ virtual bool has_char(char32_t p_char) const = 0;
+ virtual String get_supported_chars() const = 0;
+
+ virtual Vector2 get_advance(char32_t p_char, int p_size) const = 0;
+ virtual Vector2 get_kerning(char32_t p_char, char32_t p_next, int p_size) const = 0;
+
+ virtual Vector2 draw_glyph(RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0;
+ virtual Vector2 draw_glyph_outline(RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const = 0;
+
+ virtual ~FontDataFallback(){};
+};
+
+#endif // FONT_FALLBACK_H
diff --git a/modules/text_server_fb/register_types.cpp b/modules/text_server_fb/register_types.cpp
new file mode 100644
index 0000000000..87cbd2ac2c
--- /dev/null
+++ b/modules/text_server_fb/register_types.cpp
@@ -0,0 +1,43 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "text_server_fb.h"
+
+void preregister_text_server_fb_types() {
+ TextServerFallback::register_server();
+}
+
+void register_text_server_fb_types() {
+}
+
+void unregister_text_server_fb_types() {
+}
diff --git a/modules/mono/editor/csharp_project.h b/modules/text_server_fb/register_types.h
index 515b8d3d62..c854db92e5 100644
--- a/modules/mono/editor/csharp_project.h
+++ b/modules/text_server_fb/register_types.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* csharp_project.h */
+/* register_types.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,15 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef CSHARP_PROJECT_H
-#define CSHARP_PROJECT_H
+#ifndef TEXT_SERVER_FB_REGISTER_TYPES_H
+#define TEXT_SERVER_FB_REGISTER_TYPES_H
-#include "core/ustring.h"
+#define MODULE_TEXT_SERVER_FB_HAS_PREREGISTER
-namespace CSharpProject {
+void preregister_text_server_fb_types();
+void register_text_server_fb_types();
+void unregister_text_server_fb_types();
-void add_item(const String &p_project_path, const String &p_item_type, const String &p_include);
-
-} // namespace CSharpProject
-
-#endif // CSHARP_PROJECT_H
+#endif // TEXT_SERVER_FB_REGISTER_TYPES_H
diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp
new file mode 100644
index 0000000000..e60d269408
--- /dev/null
+++ b/modules/text_server_fb/text_server_fb.cpp
@@ -0,0 +1,1383 @@
+/*************************************************************************/
+/* text_server_fb.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "text_server_fb.h"
+
+#include "bitmap_font_fb.h"
+#include "dynamic_font_fb.h"
+
+_FORCE_INLINE_ bool is_control(char32_t p_char) {
+ return (p_char <= 0x001f) || (p_char >= 0x007f && p_char <= 0x009F);
+}
+
+_FORCE_INLINE_ bool is_whitespace(char32_t p_char) {
+ return (p_char == 0x0020) || (p_char == 0x00A0) || (p_char == 0x1680) || (p_char >= 0x2000 && p_char <= 0x200a) || (p_char == 0x202f) || (p_char == 0x205f) || (p_char == 0x3000) || (p_char == 0x2028) || (p_char == 0x2029) || (p_char >= 0x0009 && p_char <= 0x000d) || (p_char == 0x0085);
+}
+
+_FORCE_INLINE_ bool is_linebreak(char32_t p_char) {
+ return (p_char >= 0x000a && p_char <= 0x000d) || (p_char == 0x0085) || (p_char == 0x2028) || (p_char == 0x2029);
+}
+
+_FORCE_INLINE_ bool is_punct(char32_t p_char) {
+ return (p_char >= 0x0020 && p_char <= 0x002F) || (p_char >= 0x003A && p_char <= 0x0040) || (p_char >= 0x005B && p_char <= 0x0060) || (p_char >= 0x007B && p_char <= 0x007E) || (p_char >= 0x2000 && p_char <= 0x206F) || (p_char >= 0x3000 && p_char <= 0x303F);
+}
+
+/*************************************************************************/
+
+String TextServerFallback::interface_name = "Fallback";
+uint32_t TextServerFallback::interface_features = 0; // Nothing is supported.
+
+bool TextServerFallback::has_feature(Feature p_feature) {
+ return (interface_features & p_feature) == p_feature;
+}
+
+String TextServerFallback::get_name() const {
+ return interface_name;
+}
+
+void TextServerFallback::free(RID p_rid) {
+ _THREAD_SAFE_METHOD_
+ if (font_owner.owns(p_rid)) {
+ FontDataFallback *fd = font_owner.getornull(p_rid);
+ font_owner.free(p_rid);
+ memdelete(fd);
+ } else if (shaped_owner.owns(p_rid)) {
+ ShapedTextData *sd = shaped_owner.getornull(p_rid);
+ shaped_owner.free(p_rid);
+ memdelete(sd);
+ }
+}
+
+bool TextServerFallback::has(RID p_rid) {
+ _THREAD_SAFE_METHOD_
+ return font_owner.owns(p_rid) || shaped_owner.owns(p_rid);
+}
+
+bool TextServerFallback::load_support_data(const String &p_filename) {
+ return false; // No extra data used.
+}
+
+#ifdef TOOLS_ENABLED
+
+bool TextServerFallback::save_support_data(const String &p_filename) {
+ return false; // No extra data used.
+}
+
+#endif
+
+bool TextServerFallback::is_locale_right_to_left(const String &p_locale) {
+ return false; // No RTL support.
+}
+
+/*************************************************************************/
+/* Font interface */
+/*************************************************************************/
+
+RID TextServerFallback::create_font_system(const String &p_name, int p_base_size) {
+ ERR_FAIL_V_MSG(RID(), "System fonts are not supported by this text server.");
+}
+
+RID TextServerFallback::create_font_resource(const String &p_filename, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = nullptr;
+ if (p_filename.get_extension() == "ttf" || p_filename.get_extension() == "otf" || p_filename.get_extension() == "woff") {
+ fd = memnew(DynamicFontDataFallback);
+ } else if (p_filename.get_extension() == "fnt" || p_filename.get_extension() == "font") {
+ fd = memnew(BitmapFontDataFallback);
+ } else {
+ return RID();
+ }
+
+ Error err = fd->load_from_file(p_filename, p_base_size);
+ if (err != OK) {
+ memdelete(fd);
+ return RID();
+ }
+
+ return font_owner.make_rid(fd);
+}
+
+RID TextServerFallback::create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = nullptr;
+ if (p_type == "ttf" || p_type == "otf" || p_type == "woff") {
+ fd = memnew(DynamicFontDataFallback);
+ } else if (p_type == "fnt" || p_type == "font") {
+ fd = memnew(BitmapFontDataFallback);
+ } else {
+ return RID();
+ }
+
+ Error err = fd->load_from_memory(p_data, p_size, p_base_size);
+ if (err != OK) {
+ memdelete(fd);
+ return RID();
+ }
+
+ return font_owner.make_rid(fd);
+}
+
+float TextServerFallback::font_get_height(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_height(p_size);
+}
+
+float TextServerFallback::font_get_ascent(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_ascent(p_size);
+}
+
+float TextServerFallback::font_get_descent(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_descent(p_size);
+}
+
+float TextServerFallback::font_get_underline_position(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_underline_position(p_size);
+}
+
+float TextServerFallback::font_get_underline_thickness(RID p_font, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_underline_thickness(p_size);
+}
+
+void TextServerFallback::font_set_antialiased(RID p_font, bool p_antialiased) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_antialiased(p_antialiased);
+}
+
+bool TextServerFallback::font_get_antialiased(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_antialiased();
+}
+
+void TextServerFallback::font_set_distance_field_hint(RID p_font, bool p_distance_field) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_distance_field_hint(p_distance_field);
+}
+
+bool TextServerFallback::font_get_distance_field_hint(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_distance_field_hint();
+}
+
+void TextServerFallback::font_set_hinting(RID p_font, TextServer::Hinting p_hinting) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_hinting(p_hinting);
+}
+
+TextServer::Hinting TextServerFallback::font_get_hinting(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, TextServer::HINTING_NONE);
+ return fd->get_hinting();
+}
+
+void TextServerFallback::font_set_force_autohinter(RID p_font, bool p_enabeld) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->set_force_autohinter(p_enabeld);
+}
+
+bool TextServerFallback::font_get_force_autohinter(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->get_force_autohinter();
+}
+
+bool TextServerFallback::font_has_char(RID p_font, char32_t p_char) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->has_char(p_char);
+}
+
+String TextServerFallback::font_get_supported_chars(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, String());
+ return fd->get_supported_chars();
+}
+
+bool TextServerFallback::font_has_outline(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->has_outline();
+}
+
+float TextServerFallback::font_get_base_size(RID p_font) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, 0.f);
+ return fd->get_base_size();
+}
+
+bool TextServerFallback::font_is_language_supported(RID p_font, const String &p_language) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ if (fd->lang_support_overrides.has(p_language)) {
+ return fd->lang_support_overrides[p_language];
+ } else {
+ Vector<String> tags = p_language.replace("-", "_").split("_");
+ if (tags.size() > 0) {
+ if (fd->lang_support_overrides.has(tags[0])) {
+ return fd->lang_support_overrides[tags[0]];
+ }
+ }
+ return false;
+ }
+}
+
+void TextServerFallback::font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->lang_support_overrides[p_language] = p_supported;
+}
+
+bool TextServerFallback::font_get_language_support_override(RID p_font, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->lang_support_overrides[p_language];
+}
+
+void TextServerFallback::font_remove_language_support_override(RID p_font, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->lang_support_overrides.erase(p_language);
+}
+
+Vector<String> TextServerFallback::font_get_language_support_overrides(RID p_font) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector<String>());
+ Vector<String> ret;
+ for (Map<String, bool>::Element *E = fd->lang_support_overrides.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+ return ret;
+}
+
+bool TextServerFallback::font_is_script_supported(RID p_font, const String &p_script) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ if (fd->script_support_overrides.has(p_script)) {
+ return fd->script_support_overrides[p_script];
+ } else {
+ return true;
+ }
+}
+
+void TextServerFallback::font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->script_support_overrides[p_script] = p_supported;
+}
+
+bool TextServerFallback::font_get_script_support_override(RID p_font, const String &p_script) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, false);
+ return fd->script_support_overrides[p_script];
+}
+
+void TextServerFallback::font_remove_script_support_override(RID p_font, const String &p_script) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND(!fd);
+ fd->script_support_overrides.erase(p_script);
+}
+
+Vector<String> TextServerFallback::font_get_script_support_overrides(RID p_font) {
+ _THREAD_SAFE_METHOD_
+ FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector<String>());
+ Vector<String> ret;
+ for (Map<String, bool>::Element *E = fd->script_support_overrides.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+ return ret;
+}
+
+uint32_t TextServerFallback::font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector) const {
+ return (uint32_t)p_char;
+}
+
+Vector2 TextServerFallback::font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->get_advance(p_index, p_size);
+}
+
+Vector2 TextServerFallback::font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->get_kerning(p_index_a, p_index_b, p_size);
+}
+
+Vector2 TextServerFallback::font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->draw_glyph(p_canvas, p_size, p_pos, p_index, p_color);
+}
+
+Vector2 TextServerFallback::font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color) const {
+ _THREAD_SAFE_METHOD_
+ const FontDataFallback *fd = font_owner.getornull(p_font);
+ ERR_FAIL_COND_V(!fd, Vector2());
+ return fd->draw_glyph_outline(p_canvas, p_size, p_outline_size, p_pos, p_index, p_color);
+}
+
+float TextServerFallback::font_get_oversampling() const {
+ return oversampling;
+}
+
+void TextServerFallback::font_set_oversampling(float p_oversampling) {
+ _THREAD_SAFE_METHOD_
+ if (oversampling != p_oversampling) {
+ oversampling = p_oversampling;
+ List<RID> fonts;
+ font_owner.get_owned_list(&fonts);
+ for (List<RID>::Element *E = fonts.front(); E; E = E->next()) {
+ font_owner.getornull(E->get())->clear_cache();
+ }
+ }
+}
+
+Vector<String> TextServerFallback::get_system_fonts() const {
+ return Vector<String>();
+}
+
+/*************************************************************************/
+/* Shaped text buffer interface */
+/*************************************************************************/
+
+void TextServerFallback::invalidate(ShapedTextData *p_shaped) {
+ p_shaped->valid = false;
+ p_shaped->sort_valid = false;
+ p_shaped->line_breaks_valid = false;
+ p_shaped->justification_ops_valid = false;
+ p_shaped->ascent = 0.f;
+ p_shaped->descent = 0.f;
+ p_shaped->width = 0.f;
+ p_shaped->upos = 0.f;
+ p_shaped->uthk = 0.f;
+ p_shaped->glyphs.clear();
+ p_shaped->glyphs_logical.clear();
+}
+
+void TextServerFallback::full_copy(ShapedTextData *p_shaped) {
+ ShapedTextData *parent = shaped_owner.getornull(p_shaped->parent);
+
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = parent->objects.front(); E; E = E->next()) {
+ if (E->get().pos >= p_shaped->start && E->get().pos < p_shaped->end) {
+ p_shaped->objects[E->key()] = E->get();
+ }
+ }
+
+ for (int k = 0; k < parent->spans.size(); k++) {
+ ShapedTextData::Span span = parent->spans[k];
+ if (span.start >= p_shaped->end || span.end <= p_shaped->start) {
+ continue;
+ }
+ span.start = MAX(p_shaped->start, span.start);
+ span.end = MIN(p_shaped->end, span.end);
+ p_shaped->spans.push_back(span);
+ }
+
+ p_shaped->parent = RID();
+}
+
+RID TextServerFallback::create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = memnew(ShapedTextData);
+ sd->direction = p_direction;
+ sd->orientation = p_orientation;
+
+ return shaped_owner.make_rid(sd);
+}
+
+void TextServerFallback::shaped_text_clear(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+
+ sd->parent = RID();
+ sd->start = 0;
+ sd->end = 0;
+ sd->text = String();
+ sd->spans.clear();
+ sd->objects.clear();
+ invalidate(sd);
+}
+
+void TextServerFallback::shaped_text_set_direction(RID p_shaped, TextServer::Direction p_direction) {
+ if (p_direction == DIRECTION_RTL) {
+ ERR_PRINT_ONCE("Right-to-left layout is not supported by this text server.");
+ }
+}
+
+TextServer::Direction TextServerFallback::shaped_text_get_direction(RID p_shaped) const {
+ return TextServer::DIRECTION_LTR;
+}
+
+void TextServerFallback::shaped_text_set_orientation(RID p_shaped, TextServer::Orientation p_orientation) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->orientation != p_orientation) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->orientation = p_orientation;
+ invalidate(sd);
+ }
+}
+
+void TextServerFallback::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) {
+ //No BiDi support, ignore.
+}
+
+TextServer::Orientation TextServerFallback::shaped_text_get_orientation(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, TextServer::ORIENTATION_HORIZONTAL);
+ return sd->orientation;
+}
+
+void TextServerFallback::shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->preserve_invalid != p_enabled) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->preserve_invalid = p_enabled;
+ invalidate(sd);
+ }
+}
+
+bool TextServerFallback::shaped_text_get_preserve_invalid(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->preserve_invalid;
+}
+
+void TextServerFallback::shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND(!sd);
+ if (sd->preserve_control != p_enabled) {
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+ sd->preserve_control = p_enabled;
+ invalidate(sd);
+ }
+}
+
+bool TextServerFallback::shaped_text_get_preserve_control(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->preserve_control;
+}
+
+bool TextServerFallback::shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features, const String &p_language) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(p_size <= 0, false);
+
+ if (p_text.is_empty()) {
+ return true;
+ }
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+
+ ShapedTextData::Span span;
+ span.start = sd->text.length();
+ span.end = span.start + p_text.length();
+ // Pre-sort fonts, push fonts with the language support first.
+ for (int i = 0; i < p_fonts.size(); i++) {
+ if (font_is_language_supported(p_fonts[i], p_language)) {
+ span.fonts.push_back(p_fonts[i]);
+ }
+ }
+ // Push the rest valid fonts.
+ for (int i = 0; i < p_fonts.size(); i++) {
+ if (!font_is_language_supported(p_fonts[i], p_language)) {
+ span.fonts.push_back(p_fonts[i]);
+ }
+ }
+ ERR_FAIL_COND_V(span.fonts.is_empty(), false);
+ span.font_size = p_size;
+ span.language = p_language;
+
+ sd->spans.push_back(span);
+ sd->text += p_text;
+ sd->end += p_text.length();
+ invalidate(sd);
+
+ return true;
+}
+
+bool TextServerFallback::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(p_key == Variant(), false);
+ ERR_FAIL_COND_V(sd->objects.has(p_key), false);
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+
+ ShapedTextData::Span span;
+ span.start = sd->text.length();
+ span.end = span.start + p_length;
+ span.embedded_key = p_key;
+
+ ShapedTextData::EmbeddedObject obj;
+ obj.inline_align = p_inline_align;
+ obj.rect.size = p_size;
+ obj.pos = span.start;
+
+ sd->spans.push_back(span);
+ sd->text += String::chr(0xfffc).repeat(p_length);
+ sd->end += p_length;
+ sd->objects[p_key] = obj;
+ invalidate(sd);
+
+ return true;
+}
+
+bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ ERR_FAIL_COND_V(!sd->objects.has(p_key), false);
+ sd->objects[p_key].rect.size = p_size;
+ sd->objects[p_key].inline_align = p_inline_align;
+ if (sd->valid) {
+ // Recalc string metrics.
+ sd->ascent = 0;
+ sd->descent = 0;
+ sd->width = 0;
+ sd->upos = 0;
+ sd->uthk = 0;
+ int sd_size = sd->glyphs.size();
+ const FontDataFallback *fd = nullptr;
+ RID prev_rid = RID();
+
+ for (int i = 0; i < sd_size; i++) {
+ Glyph gl = sd->glyphs[i];
+ Variant key;
+ if (gl.count == 1) {
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (E->get().pos == gl.start) {
+ key = E->key();
+ break;
+ }
+ }
+ }
+ if (key != Variant()) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->objects[key].rect.position.x = sd->width;
+ sd->width += sd->objects[key].rect.size.x;
+ switch (sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.y / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y);
+ } break;
+ }
+ sd->glyphs.write[i].advance = sd->objects[key].rect.size.x;
+ } else {
+ sd->objects[key].rect.position.y = sd->width;
+ sd->width += sd->objects[key].rect.size.y;
+ switch (sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.x / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x);
+ } break;
+ }
+ sd->glyphs.write[i].advance = sd->objects[key].rect.size.y;
+ }
+ } else {
+ if (prev_rid != gl.font_rid) {
+ fd = font_owner.getornull(gl.font_rid);
+ prev_rid = gl.font_rid;
+ }
+ if (fd != nullptr) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->ascent = MAX(sd->ascent, fd->get_ascent(gl.font_size));
+ sd->descent = MAX(sd->descent, fd->get_descent(gl.font_size));
+ } else {
+ sd->ascent = MAX(sd->ascent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ sd->descent = MAX(sd->descent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ }
+ sd->upos = MAX(sd->upos, font_get_underline_position(gl.font_rid, gl.font_size));
+ sd->uthk = MAX(sd->uthk, font_get_underline_thickness(gl.font_rid, gl.font_size));
+ } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) {
+ // Glyph not found, replace with hex code box.
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f));
+ } else {
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ }
+ }
+ sd->width += gl.advance * gl.repeat;
+ }
+ }
+
+ // Align embedded objects to baseline.
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+ }
+ }
+ return true;
+}
+
+RID TextServerFallback::shaped_text_substr(RID p_shaped, int p_start, int p_length) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, RID());
+ if (sd->parent != RID()) {
+ return shaped_text_substr(sd->parent, p_start, p_length);
+ }
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID());
+ ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID());
+ ERR_FAIL_COND_V(sd->end < p_start + p_length, RID());
+
+ ShapedTextData *new_sd = memnew(ShapedTextData);
+ new_sd->parent = p_shaped;
+ new_sd->start = p_start;
+ new_sd->end = p_start + p_length;
+
+ new_sd->orientation = sd->orientation;
+ new_sd->direction = sd->direction;
+ new_sd->para_direction = sd->para_direction;
+ new_sd->line_breaks_valid = sd->line_breaks_valid;
+ new_sd->justification_ops_valid = sd->justification_ops_valid;
+ new_sd->sort_valid = false;
+ new_sd->upos = sd->upos;
+ new_sd->uthk = sd->uthk;
+
+ if (p_length > 0) {
+ new_sd->text = sd->text.substr(p_start, p_length);
+ int sd_size = sd->glyphs.size();
+ const Glyph *sd_glyphs = sd->glyphs.ptr();
+
+ for (int i = 0; i < sd_size; i++) {
+ if ((sd_glyphs[i].start >= new_sd->start) && (sd_glyphs[i].end <= new_sd->end)) {
+ Glyph gl = sd_glyphs[i];
+ Variant key;
+ bool find_embedded = false;
+ if (gl.count == 1) {
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (E->get().pos == gl.start) {
+ find_embedded = true;
+ key = E->key();
+ new_sd->objects[key] = E->get();
+ break;
+ }
+ }
+ }
+ if (find_embedded) {
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->objects[key].rect.position.x = new_sd->width;
+ new_sd->width += new_sd->objects[key].rect.size.x;
+ switch (new_sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.y / 2));
+ new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y);
+ } break;
+ }
+ } else {
+ new_sd->objects[key].rect.position.y = new_sd->width;
+ new_sd->width += new_sd->objects[key].rect.size.y;
+ switch (new_sd->objects[key].inline_align) {
+ case VALIGN_TOP: {
+ new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.x / 2));
+ new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x);
+ } break;
+ }
+ }
+ } else {
+ const FontDataFallback *fd = font_owner.getornull(gl.font_rid);
+ if (fd != nullptr) {
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->ascent = MAX(new_sd->ascent, fd->get_ascent(gl.font_size));
+ new_sd->descent = MAX(new_sd->descent, fd->get_descent(gl.font_size));
+ } else {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ new_sd->descent = MAX(new_sd->descent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ }
+ } else if (new_sd->preserve_invalid || (new_sd->preserve_control && is_control(gl.index))) {
+ // Glyph not found, replace with hex code box.
+ if (new_sd->orientation == ORIENTATION_HORIZONTAL) {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f));
+ new_sd->descent = MAX(new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f));
+ } else {
+ new_sd->ascent = MAX(new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ new_sd->descent = MAX(new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ }
+ }
+ new_sd->width += gl.advance * gl.repeat;
+ }
+ new_sd->glyphs.push_back(gl);
+ }
+ }
+
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) {
+ if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -new_sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = new_sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -new_sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = new_sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+ }
+ }
+ new_sd->valid = true;
+
+ return shaped_owner.make_rid(new_sd);
+}
+
+RID TextServerFallback::shaped_text_get_parent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, RID());
+ return sd->parent;
+}
+
+float TextServerFallback::shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (!sd->justification_ops_valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_update_justification_ops(p_shaped);
+ }
+
+ int start_pos = 0;
+ int end_pos = sd->glyphs.size() - 1;
+
+ if ((p_jst_flags & JUSTIFICATION_AFTER_LAST_TAB) == JUSTIFICATION_AFTER_LAST_TAB) {
+ int start, end, delta;
+ if (sd->para_direction == DIRECTION_LTR) {
+ start = sd->glyphs.size() - 1;
+ end = -1;
+ delta = -1;
+ } else {
+ start = 0;
+ end = sd->glyphs.size();
+ delta = +1;
+ }
+
+ for (int i = start; i != end; i += delta) {
+ if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
+ if (sd->para_direction == DIRECTION_LTR) {
+ start_pos = i;
+ break;
+ } else {
+ end_pos = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if ((p_jst_flags & JUSTIFICATION_TRIM_EDGE_SPACES) == JUSTIFICATION_TRIM_EDGE_SPACES) {
+ while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
+ sd->width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat;
+ sd->glyphs.write[start_pos].advance = 0;
+ start_pos += sd->glyphs[start_pos].count;
+ }
+ while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
+ sd->width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat;
+ sd->glyphs.write[end_pos].advance = 0;
+ end_pos -= sd->glyphs[end_pos].count;
+ }
+ }
+
+ int space_count = 0;
+ for (int i = start_pos; i <= end_pos; i++) {
+ const Glyph &gl = sd->glyphs[i];
+ if (gl.count > 0) {
+ if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
+ space_count++;
+ }
+ }
+ }
+
+ if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) {
+ float delta_width_per_space = (p_width - sd->width) / space_count;
+ for (int i = start_pos; i <= end_pos; i++) {
+ Glyph &gl = sd->glyphs.write[i];
+ if (gl.count > 0) {
+ if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) {
+ float old_adv = gl.advance;
+ gl.advance = Math::round(MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size));
+ sd->width += (gl.advance - old_adv);
+ }
+ }
+ }
+ }
+
+ return sd->width;
+}
+
+float TextServerFallback::shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (!sd->line_breaks_valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_update_breaks(p_shaped);
+ }
+
+ int tab_index = 0;
+ float off = 0.f;
+
+ int start, end, delta;
+ if (sd->para_direction == DIRECTION_LTR) {
+ start = 0;
+ end = sd->glyphs.size();
+ delta = +1;
+ } else {
+ start = sd->glyphs.size() - 1;
+ end = -1;
+ delta = -1;
+ }
+
+ Glyph *gl = sd->glyphs.ptrw();
+
+ for (int i = start; i != end; i += delta) {
+ if ((gl[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
+ float tab_off = 0.f;
+ while (tab_off <= off) {
+ tab_off += p_tab_stops[tab_index];
+ tab_index++;
+ if (tab_index >= p_tab_stops.size()) {
+ tab_index = 0;
+ }
+ }
+ float old_adv = gl[i].advance;
+ gl[i].advance = tab_off - off;
+ sd->width += gl[i].advance - old_adv;
+ off = 0;
+ continue;
+ }
+ off += gl[i].advance * gl[i].repeat;
+ }
+
+ return 0.f;
+}
+
+bool TextServerFallback::shaped_text_update_breaks(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ if (!sd->valid) {
+ shaped_text_shape(p_shaped);
+ }
+
+ if (sd->line_breaks_valid) {
+ return true; // Noting to do.
+ }
+
+ int sd_size = sd->glyphs.size();
+ for (int i = 0; i < sd_size; i++) {
+ if (sd->glyphs[i].count > 0) {
+ char32_t c = sd->text[sd->glyphs[i].start];
+ if (is_punct(c)) {
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_PUNCTUATION;
+ }
+ if (is_whitespace(c) && !is_linebreak(c)) {
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_SPACE;
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_SOFT;
+ }
+ if (is_linebreak(c)) {
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_HARD;
+ }
+ if (c == 0x0009 || c == 0x000b) {
+ sd->glyphs.write[i].flags |= GRAPHEME_IS_TAB;
+ }
+
+ i += (sd->glyphs[i].count - 1);
+ }
+ }
+ sd->line_breaks_valid = true;
+ return sd->line_breaks_valid;
+}
+
+bool TextServerFallback::shaped_text_update_justification_ops(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ if (!sd->valid) {
+ shaped_text_shape(p_shaped);
+ }
+ if (!sd->line_breaks_valid) {
+ shaped_text_update_breaks(p_shaped);
+ }
+
+ sd->justification_ops_valid = true; // Not supported by fallback server.
+ return true;
+}
+
+bool TextServerFallback::shaped_text_shape(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ if (sd->valid) {
+ return true;
+ }
+
+ if (sd->parent != RID()) {
+ full_copy(sd);
+ }
+
+ // Cleanup.
+ sd->justification_ops_valid = false;
+ sd->line_breaks_valid = false;
+ sd->ascent = 0.f;
+ sd->descent = 0.f;
+ sd->width = 0.f;
+ sd->glyphs.clear();
+
+ if (sd->text.length() == 0) {
+ sd->valid = true;
+ return true;
+ }
+
+ // "Shape" string.
+ for (int i = 0; i < sd->spans.size(); i++) {
+ const ShapedTextData::Span &span = sd->spans[i];
+ if (span.embedded_key != Variant()) {
+ // Embedded object.
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ sd->objects[span.embedded_key].rect.position.x = sd->width;
+ sd->width += sd->objects[span.embedded_key].rect.size.x;
+ switch (sd->objects[span.embedded_key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y);
+ } break;
+ }
+ } else {
+ sd->objects[span.embedded_key].rect.position.y = sd->width;
+ sd->width += sd->objects[span.embedded_key].rect.size.y;
+ switch (sd->objects[span.embedded_key].inline_align) {
+ case VALIGN_TOP: {
+ sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x);
+ } break;
+ case VALIGN_CENTER: {
+ sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2));
+ sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2));
+ } break;
+ case VALIGN_BOTTOM: {
+ sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x);
+ } break;
+ }
+ }
+ Glyph gl;
+ gl.start = span.start;
+ gl.end = span.end;
+ gl.count = 1;
+ gl.index = 0;
+ gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_VIRTUAL;
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = sd->objects[span.embedded_key].rect.size.x;
+ } else {
+ gl.advance = sd->objects[span.embedded_key].rect.size.y;
+ }
+ sd->glyphs.push_back(gl);
+ } else {
+ // Text span.
+ for (int j = span.start; j < span.end; j++) {
+ const FontDataFallback *fd = nullptr;
+
+ Glyph gl;
+ gl.start = j;
+ gl.end = j + 1;
+ gl.count = 1;
+ gl.font_size = span.font_size;
+ gl.index = (uint32_t)sd->text[j]; // Use codepoint.
+ if (gl.index == 0x0009 || gl.index == 0x000b) {
+ gl.index = 0x0020;
+ }
+ if (!sd->preserve_control && is_control(gl.index)) {
+ gl.index = 0x0020;
+ }
+ // Select first font which has character (font are already sorted by span language).
+ for (int k = 0; k < span.fonts.size(); k++) {
+ fd = font_owner.getornull(span.fonts[k]);
+ if (fd != nullptr && fd->has_char(gl.index)) {
+ gl.font_rid = span.fonts[k];
+ break;
+ }
+ }
+
+ if (gl.font_rid != RID()) {
+ if (sd->text[j] != 0 && !is_linebreak(sd->text[j])) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = fd->get_advance(gl.index, gl.font_size).x;
+ gl.x_off = 0;
+ gl.y_off = 0;
+ sd->ascent = MAX(sd->ascent, fd->get_ascent(gl.font_size));
+ sd->descent = MAX(sd->descent, fd->get_descent(gl.font_size));
+ } else {
+ gl.advance = fd->get_advance(gl.index, gl.font_size).y;
+ gl.x_off = -Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5);
+ gl.y_off = fd->get_ascent(gl.font_size);
+ sd->ascent = MAX(sd->ascent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ sd->descent = MAX(sd->descent, Math::round(fd->get_advance(gl.index, gl.font_size).x * 0.5));
+ }
+ }
+ sd->upos = MAX(sd->upos, fd->get_underline_position(gl.font_size));
+ sd->uthk = MAX(sd->uthk, fd->get_underline_thickness(gl.font_size));
+
+ // Add kerning to previous glyph.
+ if (sd->glyphs.size() > 0) {
+ Glyph &prev_gl = sd->glyphs.write[sd->glyphs.size() - 1];
+ if (prev_gl.font_rid == gl.font_rid && prev_gl.font_size == gl.font_size) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ prev_gl.advance += fd->get_kerning(prev_gl.index, gl.index, gl.font_size).x;
+ } else {
+ prev_gl.advance += fd->get_kerning(prev_gl.index, gl.index, gl.font_size).y;
+ }
+ }
+ }
+ } else if (sd->preserve_invalid || (sd->preserve_control && is_control(gl.index))) {
+ // Glyph not found, replace with hex code box.
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ gl.advance = get_hex_code_box_size(gl.font_size, gl.index).x;
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.75f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).y * 0.25f));
+ } else {
+ gl.advance = get_hex_code_box_size(gl.font_size, gl.index).y;
+ sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5f));
+ }
+ }
+ sd->width += gl.advance;
+ sd->glyphs.push_back(gl);
+ }
+ }
+ }
+
+ // Align embedded objects to baseline.
+ for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ if (sd->orientation == ORIENTATION_HORIZONTAL) {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.y = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.y = -(E->get().rect.size.y / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.y = sd->descent - E->get().rect.size.y;
+ } break;
+ }
+ } else {
+ switch (E->get().inline_align) {
+ case VALIGN_TOP: {
+ E->get().rect.position.x = -sd->ascent;
+ } break;
+ case VALIGN_CENTER: {
+ E->get().rect.position.x = -(E->get().rect.size.x / 2);
+ } break;
+ case VALIGN_BOTTOM: {
+ E->get().rect.position.x = sd->descent - E->get().rect.size.x;
+ } break;
+ }
+ }
+ }
+
+ sd->valid = true;
+ return sd->valid;
+}
+
+bool TextServerFallback::shaped_text_is_ready(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, false);
+ return sd->valid;
+}
+
+Vector<TextServer::Glyph> TextServerFallback::shaped_text_get_glyphs(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>());
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->glyphs;
+}
+
+Vector2i TextServerFallback::shaped_text_get_range(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector2i());
+ return Vector2(sd->start, sd->end);
+}
+
+Vector<TextServer::Glyph> TextServerFallback::shaped_text_sort_logical(RID p_shaped) {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Vector<TextServer::Glyph>());
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ return sd->glyphs; // Already in the logical order, return as is.
+}
+
+Array TextServerFallback::shaped_text_get_objects(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ Array ret;
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, ret);
+ for (const Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) {
+ ret.push_back(E->key());
+ }
+
+ return ret;
+}
+
+Rect2 TextServerFallback::shaped_text_get_object_rect(RID p_shaped, Variant p_key) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Rect2());
+ ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2());
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->objects[p_key].rect;
+}
+
+Size2 TextServerFallback::shaped_text_get_size(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, Size2());
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) {
+ return Size2(sd->width, sd->ascent + sd->descent);
+ } else {
+ return Size2(sd->ascent + sd->descent, sd->width);
+ }
+}
+
+float TextServerFallback::shaped_text_get_ascent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->ascent;
+}
+
+float TextServerFallback::shaped_text_get_descent(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->descent;
+}
+
+float TextServerFallback::shaped_text_get_width(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+ return sd->width;
+}
+
+float TextServerFallback::shaped_text_get_underline_position(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ return sd->upos;
+}
+
+float TextServerFallback::shaped_text_get_underline_thickness(RID p_shaped) const {
+ _THREAD_SAFE_METHOD_
+ const ShapedTextData *sd = shaped_owner.getornull(p_shaped);
+ ERR_FAIL_COND_V(!sd, 0.f);
+ if (!sd->valid) {
+ const_cast<TextServerFallback *>(this)->shaped_text_shape(p_shaped);
+ }
+
+ return sd->uthk;
+}
+
+TextServer *TextServerFallback::create_func(Error &r_error, void *p_user_data) {
+ r_error = OK;
+ return memnew(TextServerFallback());
+}
+
+void TextServerFallback::register_server() {
+ TextServerManager::register_create_function(interface_name, interface_features, create_func, nullptr);
+}
diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h
new file mode 100644
index 0000000000..d142b320e4
--- /dev/null
+++ b/modules/text_server_fb/text_server_fb.h
@@ -0,0 +1,193 @@
+/*************************************************************************/
+/* text_server_fb.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 TEXT_SERVER_FALLBACK_H
+#define TEXT_SERVER_FALLBACK_H
+
+/*************************************************************************/
+/* Fallback Text Server provides simplified TS functionality, without */
+/* BiDi, shaping and advanced font features support. */
+/*************************************************************************/
+
+#include "servers/text_server.h"
+
+#include "core/templates/rid_owner.h"
+
+#include "scene/resources/texture.h"
+
+#include "font_fb.h"
+
+class TextServerFallback : public TextServer {
+ GDCLASS(TextServerFallback, TextServer);
+ _THREAD_SAFE_CLASS_
+
+ float oversampling = 1.f;
+ mutable RID_PtrOwner<FontDataFallback> font_owner;
+ mutable RID_PtrOwner<ShapedTextData> shaped_owner;
+
+ static String interface_name;
+ static uint32_t interface_features;
+
+protected:
+ static void _bind_methods(){};
+
+ void full_copy(ShapedTextData *p_shaped);
+ void invalidate(ShapedTextData *p_shaped);
+
+public:
+ virtual bool has_feature(Feature p_feature) override;
+ virtual String get_name() const override;
+
+ virtual void free(RID p_rid) override;
+ virtual bool has(RID p_rid) override;
+ virtual bool load_support_data(const String &p_filename) override;
+
+#ifdef TOOLS_ENABLED
+ virtual String get_support_data_filename() override { return ""; };
+ virtual String get_support_data_info() override { return "Not supported"; };
+ virtual bool save_support_data(const String &p_filename) override;
+#endif
+
+ virtual bool is_locale_right_to_left(const String &p_locale) override;
+
+ /* Font interface */
+ virtual RID create_font_system(const String &p_name, int p_base_size = 16) override;
+ virtual RID create_font_resource(const String &p_filename, int p_base_size = 16) override;
+ virtual RID create_font_memory(const uint8_t *p_data, size_t p_size, const String &p_type, int p_base_size = 16) override;
+
+ virtual float font_get_height(RID p_font, int p_size) const override;
+ virtual float font_get_ascent(RID p_font, int p_size) const override;
+ virtual float font_get_descent(RID p_font, int p_size) const override;
+
+ virtual float font_get_underline_position(RID p_font, int p_size) const override;
+ virtual float font_get_underline_thickness(RID p_font, int p_size) const override;
+
+ virtual void font_set_antialiased(RID p_font, bool p_antialiased) override;
+ virtual bool font_get_antialiased(RID p_font) const override;
+
+ virtual void font_set_hinting(RID p_font, Hinting p_hinting) override;
+ virtual Hinting font_get_hinting(RID p_font) const override;
+
+ virtual void font_set_force_autohinter(RID p_font, bool p_enabeld) override;
+ virtual bool font_get_force_autohinter(RID p_font) const override;
+
+ virtual bool font_has_char(RID p_font, char32_t p_char) const override;
+ virtual String font_get_supported_chars(RID p_font) const override;
+
+ virtual void font_set_distance_field_hint(RID p_font, bool p_distance_field) override;
+ virtual bool font_get_distance_field_hint(RID p_font) const override;
+
+ virtual bool font_has_outline(RID p_font) const override;
+ virtual float font_get_base_size(RID p_font) const override;
+
+ virtual bool font_is_language_supported(RID p_font, const String &p_language) const override;
+ virtual void font_set_language_support_override(RID p_font, const String &p_language, bool p_supported) override;
+ virtual bool font_get_language_support_override(RID p_font, const String &p_language) override;
+ virtual void font_remove_language_support_override(RID p_font, const String &p_language) override;
+ Vector<String> font_get_language_support_overrides(RID p_font) override;
+
+ virtual bool font_is_script_supported(RID p_font, const String &p_script) const override;
+ virtual void font_set_script_support_override(RID p_font, const String &p_script, bool p_supported) override;
+ virtual bool font_get_script_support_override(RID p_font, const String &p_script) override;
+ virtual void font_remove_script_support_override(RID p_font, const String &p_script) override;
+ Vector<String> font_get_script_support_overrides(RID p_font) override;
+
+ virtual uint32_t font_get_glyph_index(RID p_font, char32_t p_char, char32_t p_variation_selector = 0x0000) const override;
+ virtual Vector2 font_get_glyph_advance(RID p_font, uint32_t p_index, int p_size) const override;
+ virtual Vector2 font_get_glyph_kerning(RID p_font, uint32_t p_index_a, uint32_t p_index_b, int p_size) const override;
+
+ virtual Vector2 font_draw_glyph(RID p_font, RID p_canvas, int p_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+ virtual Vector2 font_draw_glyph_outline(RID p_font, RID p_canvas, int p_size, int p_outline_size, const Vector2 &p_pos, uint32_t p_index, const Color &p_color = Color(1, 1, 1)) const override;
+
+ virtual float font_get_oversampling() const override;
+ virtual void font_set_oversampling(float p_oversampling) override;
+
+ virtual Vector<String> get_system_fonts() const override;
+
+ /* Shaped text buffer interface */
+
+ virtual RID create_shaped_text(Direction p_direction = DIRECTION_AUTO, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+
+ virtual void shaped_text_clear(RID p_shaped) override;
+
+ virtual void shaped_text_set_direction(RID p_shaped, Direction p_direction = DIRECTION_AUTO) override;
+ virtual Direction shaped_text_get_direction(RID p_shaped) const override;
+
+ virtual void shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) override;
+
+ virtual void shaped_text_set_orientation(RID p_shaped, Orientation p_orientation = ORIENTATION_HORIZONTAL) override;
+ virtual Orientation shaped_text_get_orientation(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_invalid(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_invalid(RID p_shaped) const override;
+
+ virtual void shaped_text_set_preserve_control(RID p_shaped, bool p_enabled) override;
+ virtual bool shaped_text_get_preserve_control(RID p_shaped) const override;
+
+ virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override;
+ virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override;
+ virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override;
+
+ virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override;
+ virtual RID shaped_text_get_parent(RID p_shaped) const override;
+
+ virtual float shaped_text_fit_to_width(RID p_shaped, float p_width, uint8_t /*JustificationFlag*/ p_jst_flags = JUSTIFICATION_WORD_BOUND | JUSTIFICATION_KASHIDA) override;
+ virtual float shaped_text_tab_align(RID p_shaped, const Vector<float> &p_tab_stops) override;
+
+ virtual bool shaped_text_shape(RID p_shaped) override;
+ virtual bool shaped_text_update_breaks(RID p_shaped) override;
+ virtual bool shaped_text_update_justification_ops(RID p_shaped) override;
+
+ virtual bool shaped_text_is_ready(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override;
+
+ virtual Vector2i shaped_text_get_range(RID p_shaped) const override;
+
+ virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override;
+
+ virtual Array shaped_text_get_objects(RID p_shaped) const override;
+ virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override;
+
+ virtual Size2 shaped_text_get_size(RID p_shaped) const override;
+ virtual float shaped_text_get_ascent(RID p_shaped) const override;
+ virtual float shaped_text_get_descent(RID p_shaped) const override;
+ virtual float shaped_text_get_width(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_position(RID p_shaped) const override;
+ virtual float shaped_text_get_underline_thickness(RID p_shaped) const override;
+
+ static TextServer *create_func(Error &r_error, void *p_user_data);
+ static void register_server();
+
+ TextServerFallback(){};
+ ~TextServerFallback(){};
+};
+
+#endif // TEXT_SERVER_FALLBACK_H
diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp
index fc9d727bb0..2da9159228 100644
--- a/modules/tga/image_loader_tga.cpp
+++ b/modules/tga/image_loader_tga.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,16 +30,19 @@
#include "image_loader_tga.h"
+#include "core/error/error_macros.h"
+#include "core/io/file_access_memory.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size) {
Error error;
Vector<uint8_t> pixels;
error = pixels.resize(p_pixel_size);
- if (error != OK)
+ if (error != OK) {
return error;
+ }
uint8_t *pixels_w = pixels.ptrw();
@@ -77,7 +80,6 @@ Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t
}
Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome) {
-
#define TGA_PUT_PIXEL(r, g, b, a) \
int image_data_ofs = ((y * width) + x); \
image_data_w[image_data_ofs * 4 + 0] = r; \
@@ -199,13 +201,12 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff
}
}
- p_image->create(width, height, 0, Image::FORMAT_RGBA8, image_data);
+ p_image->create(width, height, false, Image::FORMAT_RGBA8, image_data);
return OK;
}
Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
Vector<uint8_t> src_image;
int src_image_len = f->get_len();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
@@ -234,8 +235,9 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
bool has_color_map = (tga_header.image_type == TGA_TYPE_RLE_INDEXED || tga_header.image_type == TGA_TYPE_INDEXED);
bool is_monochrome = (tga_header.image_type == TGA_TYPE_RLE_MONOCHROME || tga_header.image_type == TGA_TYPE_MONOCHROME);
- if (tga_header.image_type == TGA_TYPE_NO_DATA)
+ if (tga_header.image_type == TGA_TYPE_NO_DATA) {
err = FAILED;
+ }
if (has_color_map) {
if (tga_header.color_map_length > 256 || (tga_header.color_map_depth != 24) || tga_header.color_map_type != 1) {
@@ -247,8 +249,9 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
}
}
- if (tga_header.image_width <= 0 || tga_header.image_height <= 0)
+ if (tga_header.image_width <= 0 || tga_header.image_height <= 0) {
err = FAILED;
+ }
if (!(tga_header.pixel_depth == 8 || tga_header.pixel_depth == 24 || tga_header.pixel_depth == 32)) {
err = FAILED;
@@ -286,7 +289,6 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
const uint8_t *buffer = nullptr;
if (is_encoded) {
-
err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size);
if (err == OK) {
@@ -308,9 +310,20 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
}
void ImageLoaderTGA::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("tga");
}
+static Ref<Image> _tga_mem_loader_func(const uint8_t *p_tga, int p_size) {
+ FileAccessMemory memfile;
+ Error open_memfile_error = memfile.open_custom(p_tga, p_size);
+ ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for TGA image buffer.");
+ Ref<Image> img;
+ img.instance();
+ Error load_error = ImageLoaderTGA().load_image(img, &memfile, false, 1.0f);
+ ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load TGA image.");
+ return img;
+}
+
ImageLoaderTGA::ImageLoaderTGA() {
+ Image::_tga_mem_loader_func = _tga_mem_loader_func;
}
diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h
index 6b3d33e7ef..249e33411e 100644
--- a/modules/tga/image_loader_tga.h
+++ b/modules/tga/image_loader_tga.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/tga/register_types.cpp b/modules/tga/register_types.cpp
index 0d9268ebbf..9e5fe124ef 100644
--- a/modules/tga/register_types.cpp
+++ b/modules/tga/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
static ImageLoaderTGA *image_loader_tga = nullptr;
void register_tga_types() {
-
image_loader_tga = memnew(ImageLoaderTGA);
ImageLoader::add_image_format_loader(image_loader_tga);
}
void unregister_tga_types() {
-
memdelete(image_loader_tga);
}
diff --git a/modules/tga/register_types.h b/modules/tga/register_types.h
index 94a77d295e..0dcd750250 100644
--- a/modules/tga/register_types.h
+++ b/modules/tga/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/theora/SCsub b/modules/theora/SCsub
index a01e65b4b0..6038ea086a 100644
--- a/modules/theora/SCsub
+++ b/modules/theora/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_theora = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_libtheora"]:
thirdparty_dir = "#thirdparty/libtheora/"
thirdparty_sources = [
@@ -80,7 +83,16 @@ if env["builtin_libtheora"]:
env_thirdparty = env_theora.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_theora.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_theora.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/theora/config.py b/modules/theora/config.py
index 413acce2df..b063ed51f9 100644
--- a/modules/theora/config.py
+++ b/modules/theora/config.py
@@ -1,5 +1,5 @@
def can_build(env, platform):
- return True
+ return env.module_check_dependencies("theora", ["ogg", "vorbis"])
def configure(env):
diff --git a/modules/theora/doc_classes/VideoStreamTheora.xml b/modules/theora/doc_classes/VideoStreamTheora.xml
index 92244a4d28..cb8852d5ef 100644
--- a/modules/theora/doc_classes/VideoStreamTheora.xml
+++ b/modules/theora/doc_classes/VideoStreamTheora.xml
@@ -4,7 +4,8 @@
[VideoStream] resource for Ogg Theora videos.
</brief_description>
<description>
- [VideoStream] resource handling the [url=https://www.theora.org/]Ogg Theora[/url] video format with [code].ogv[/code] extension.
+ [VideoStream] resource handling the [url=https://www.theora.org/]Ogg Theora[/url] video format with [code].ogv[/code] extension. The Theora codec is less efficient than [VideoStreamWebm]'s VP8 and VP9, but it requires less CPU resources to decode. The Theora codec is decoded on the CPU.
+ [b]Note:[/b] While Ogg Theora videos can also have an [code].ogg[/code] extension, you will have to rename the extension to [code].ogv[/code] to use those videos within Godot.
</description>
<tutorials>
</tutorials>
@@ -22,7 +23,7 @@
<argument index="0" name="file" type="String">
</argument>
<description>
- Sets the Ogg Theora video file that this [VideoStreamTheora] resource handles. The [code]file[/code] name should have the [code].o[/code] extension.
+ Sets the Ogg Theora video file that this [VideoStreamTheora] resource handles. The [code]file[/code] name should have the [code].ogv[/code] extension.
</description>
</method>
</methods>
diff --git a/modules/theora/register_types.cpp b/modules/theora/register_types.cpp
index f58e27c855..0218b8c7a4 100644
--- a/modules/theora/register_types.cpp
+++ b/modules/theora/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
static Ref<ResourceFormatLoaderTheora> resource_loader_theora;
void register_theora_types() {
-
resource_loader_theora.instance();
ResourceLoader::add_resource_format_loader(resource_loader_theora, true);
@@ -43,7 +42,6 @@ void register_theora_types() {
}
void unregister_theora_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_theora);
resource_loader_theora.unref();
}
diff --git a/modules/theora/register_types.h b/modules/theora/register_types.h
index 4f0670b2c7..654d70e417 100644
--- a/modules/theora/register_types.h
+++ b/modules/theora/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp
index b9f276fb12..243265769e 100644
--- a/modules/theora/video_stream_theora.cpp
+++ b/modules/theora/video_stream_theora.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "video_stream_theora.h"
+#include "core/config/project_settings.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "thirdparty/misc/yuv2rgb.h"
int VideoStreamPlaybackTheora::buffer_data() {
-
char *buffer = ogg_sync_buffer(&oy, 4096);
#ifdef THEORA_USE_THREAD_STREAMING
@@ -69,18 +68,20 @@ int VideoStreamPlaybackTheora::buffer_data() {
int VideoStreamPlaybackTheora::queue_page(ogg_page *page) {
if (theora_p) {
ogg_stream_pagein(&to, page);
- if (to.e_o_s)
+ if (to.e_o_s) {
theora_eos = true;
+ }
}
if (vorbis_p) {
ogg_stream_pagein(&vo, page);
- if (vo.e_o_s)
+ if (vo.e_o_s) {
vorbis_eos = true;
+ }
}
return 0;
}
-void VideoStreamPlaybackTheora::video_write(void) {
+void VideoStreamPlaybackTheora::video_write() {
th_ycbcr_buffer yuv;
th_decode_ycbcr_out(td, yuv);
@@ -93,15 +94,12 @@ void VideoStreamPlaybackTheora::video_write(void) {
//uv_offset=(ti.pic_x/2)+(yuv[1].stride)*(ti.pic_y/2);
if (px_fmt == TH_PF_444) {
-
yuv444_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2);
} else if (px_fmt == TH_PF_422) {
-
yuv422_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2);
} else if (px_fmt == TH_PF_420) {
-
yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[1].data, (uint8_t *)yuv[2].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2);
};
@@ -116,9 +114,9 @@ void VideoStreamPlaybackTheora::video_write(void) {
}
void VideoStreamPlaybackTheora::clear() {
-
- if (!file)
+ if (!file) {
return;
+ }
if (vorbis_p) {
ogg_stream_clear(&vo);
@@ -164,7 +162,6 @@ void VideoStreamPlaybackTheora::clear() {
};
void VideoStreamPlaybackTheora::set_file(const String &p_file) {
-
ERR_FAIL_COND(playing);
ogg_packet op;
th_setup_info *ts = nullptr;
@@ -209,7 +206,9 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) {
while (!stateflag) {
int ret = buffer_data();
- if (ret == 0) break;
+ if (ret == 0) {
+ break;
+ }
while (ogg_sync_pageout(&oy, &og) > 0) {
ogg_stream_state test;
@@ -231,7 +230,6 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) {
copymem(&to, &test, sizeof(test));
theora_p = 1;
} else if (!vorbis_p && vorbis_synthesis_headerin(&vi, &vc, &op) >= 0) {
-
/* it is vorbis */
if (audio_track_skip) {
vorbis_info_clear(&vi);
@@ -286,7 +284,9 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) {
return;
}
vorbis_p++;
- if (vorbis_p == 3) break;
+ if (vorbis_p == 3) {
+ break;
+ }
}
/* The header pages/packets will arrive before anything else we
@@ -372,14 +372,13 @@ float VideoStreamPlaybackTheora::get_time() const {
};
Ref<Texture2D> VideoStreamPlaybackTheora::get_texture() const {
-
return texture;
}
void VideoStreamPlaybackTheora::update(float p_delta) {
-
- if (!file)
+ if (!file) {
return;
+ }
if (!playing || paused) {
//printf("not playing\n");
@@ -413,13 +412,11 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
/* if there's pending, decoded audio, grab it */
ret = vorbis_synthesis_pcmout(&vd, &pcm);
if (ret > 0) {
-
const int AUXBUF_LEN = 4096;
int to_read = ret;
float aux_buffer[AUXBUF_LEN];
while (to_read) {
-
int m = MIN(AUXBUF_LEN / vi.channels, to_read);
int count = 0;
@@ -447,7 +444,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
audio_frames_wrote += ret - to_read;
} else {
-
/* no pending audio; is there a pending packet to decode? */
if (ogg_stream_packetout(&vo, &op) > 0) {
if (vorbis_synthesis(&vb, &op) == 0) { /* test for success! */
@@ -460,14 +456,14 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
audio_done = videobuf_time < (audio_frames_wrote / float(vi.rate));
- if (buffer_full)
+ if (buffer_full) {
break;
+ }
}
while (theora_p && !frame_done) {
/* theora is one in, one out... */
if (ogg_stream_packetout(&to, &op) > 0) {
-
if (false && pp_inc) {
pp_level += pp_inc;
th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level,
@@ -534,7 +530,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
/* are we at or past time for this video frame? */
if (videobuf_ready && videobuf_time <= get_time()) {
-
//video_write();
//videobuf_ready=0;
} else {
@@ -554,10 +549,9 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
};
void VideoStreamPlaybackTheora::play() {
-
- if (!playing)
+ if (!playing) {
time = 0;
- else {
+ } else {
stop();
}
@@ -567,9 +561,7 @@ void VideoStreamPlaybackTheora::play() {
};
void VideoStreamPlaybackTheora::stop() {
-
if (playing) {
-
clear();
set_file(file_name); //reset
}
@@ -578,86 +570,68 @@ void VideoStreamPlaybackTheora::stop() {
};
bool VideoStreamPlaybackTheora::is_playing() const {
-
return playing;
};
void VideoStreamPlaybackTheora::set_paused(bool p_paused) {
-
paused = p_paused;
};
bool VideoStreamPlaybackTheora::is_paused() const {
-
return paused;
};
-void VideoStreamPlaybackTheora::set_loop(bool p_enable){
-
-};
+void VideoStreamPlaybackTheora::set_loop(bool p_enable) {
+}
bool VideoStreamPlaybackTheora::has_loop() const {
-
return false;
};
float VideoStreamPlaybackTheora::get_length() const {
-
return 0;
};
String VideoStreamPlaybackTheora::get_stream_name() const {
-
return "";
};
int VideoStreamPlaybackTheora::get_loop_count() const {
-
return 0;
};
float VideoStreamPlaybackTheora::get_playback_position() const {
-
return get_time();
};
-void VideoStreamPlaybackTheora::seek(float p_time){
-
- // no
-};
+void VideoStreamPlaybackTheora::seek(float p_time) {
+}
void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
-
mix_callback = p_callback;
mix_udata = p_userdata;
}
int VideoStreamPlaybackTheora::get_channels() const {
-
return vi.channels;
}
void VideoStreamPlaybackTheora::set_audio_track(int p_idx) {
-
audio_track = p_idx;
}
int VideoStreamPlaybackTheora::get_mix_rate() const {
-
return vi.rate;
}
#ifdef THEORA_USE_THREAD_STREAMING
void VideoStreamPlaybackTheora::_streaming_thread(void *ud) {
-
VideoStreamPlaybackTheora *vs = (VideoStreamPlaybackTheora *)ud;
while (!vs->thread_exit) {
-
//just fill back the buffer
if (!vs->thread_eof) {
-
int to_read = vs->ring_buffer.space_left();
if (to_read) {
int read = vs->file->get_buffer(vs->read_buffer.ptr(), to_read);
@@ -673,7 +647,6 @@ void VideoStreamPlaybackTheora::_streaming_thread(void *ud) {
#endif
VideoStreamPlaybackTheora::VideoStreamPlaybackTheora() {
-
file = nullptr;
theora_p = 0;
vorbis_p = 0;
@@ -704,19 +677,18 @@ VideoStreamPlaybackTheora::VideoStreamPlaybackTheora() {
};
VideoStreamPlaybackTheora::~VideoStreamPlaybackTheora() {
-
#ifdef THEORA_USE_THREAD_STREAMING
memdelete(thread_sem);
#endif
clear();
- if (file)
+ if (file) {
memdelete(file);
+ }
};
void VideoStreamTheora::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamTheora::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamTheora::get_file);
@@ -726,7 +698,6 @@ void VideoStreamTheora::_bind_methods() {
////////////
RES ResourceFormatLoaderTheora::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
@@ -750,19 +721,17 @@ RES ResourceFormatLoaderTheora::load(const String &p_path, const String &p_origi
}
void ResourceFormatLoaderTheora::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("ogv");
}
bool ResourceFormatLoaderTheora::handles_type(const String &p_type) const {
-
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderTheora::get_resource_type(const String &p_path) const {
-
String el = p_path.get_extension().to_lower();
- if (el == "ogv")
+ if (el == "ogv") {
return "VideoStreamTheora";
+ }
return "";
}
diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h
index f98368ed8b..d2036b5cb4 100644
--- a/modules/theora/video_stream_theora.h
+++ b/modules/theora/video_stream_theora.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,7 @@
#include "core/os/file_access.h"
#include "core/os/semaphore.h"
#include "core/os/thread.h"
-#include "core/ring_buffer.h"
+#include "core/templates/ring_buffer.h"
#include "scene/resources/video_stream.h"
#include "servers/audio_server.h"
@@ -45,7 +45,6 @@
//#define THEORA_USE_THREAD_STREAMING
class VideoStreamPlaybackTheora : public VideoStreamPlayback {
-
GDCLASS(VideoStreamPlaybackTheora, VideoStreamPlayback);
enum {
@@ -63,7 +62,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback {
int buffer_data();
int queue_page(ogg_page *page);
- void video_write(void);
+ void video_write();
float get_time() const;
bool theora_eos;
@@ -126,42 +125,41 @@ protected:
void clear();
public:
- virtual void play();
- virtual void stop();
- virtual bool is_playing() const;
+ virtual void play() override;
+ virtual void stop() override;
+ virtual bool is_playing() const override;
- virtual void set_paused(bool p_paused);
- virtual bool is_paused() const;
+ virtual void set_paused(bool p_paused) override;
+ virtual bool is_paused() const override;
- virtual void set_loop(bool p_enable);
- virtual bool has_loop() const;
+ virtual void set_loop(bool p_enable) override;
+ virtual bool has_loop() const override;
- virtual float get_length() const;
+ virtual float get_length() const override;
virtual String get_stream_name() const;
virtual int get_loop_count() const;
- virtual float get_playback_position() const;
- virtual void seek(float p_time);
+ virtual float get_playback_position() const override;
+ virtual void seek(float p_time) override;
void set_file(const String &p_file);
- virtual Ref<Texture2D> get_texture() const;
- virtual void update(float p_delta);
+ virtual Ref<Texture2D> get_texture() const override;
+ virtual void update(float p_delta) override;
- virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata);
- virtual int get_channels() const;
- virtual int get_mix_rate() const;
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) override;
+ virtual int get_channels() const override;
+ virtual int get_mix_rate() const override;
- virtual void set_audio_track(int p_idx);
+ virtual void set_audio_track(int p_idx) override;
VideoStreamPlaybackTheora();
~VideoStreamPlaybackTheora();
};
class VideoStreamTheora : public VideoStream {
-
GDCLASS(VideoStreamTheora, VideoStream);
String file;
@@ -171,7 +169,7 @@ protected:
static void _bind_methods();
public:
- Ref<VideoStreamPlayback> instance_playback() {
+ Ref<VideoStreamPlayback> instance_playback() override {
Ref<VideoStreamPlaybackTheora> pb = memnew(VideoStreamPlaybackTheora);
pb->set_audio_track(audio_track);
pb->set_file(file);
@@ -180,7 +178,7 @@ public:
void set_file(const String &p_file) { file = p_file; }
String get_file() { return file; }
- void set_audio_track(int p_track) { audio_track = p_track; }
+ void set_audio_track(int p_track) override { audio_track = p_track; }
VideoStreamTheora() { audio_track = 0; }
};
diff --git a/modules/tinyexr/SCsub b/modules/tinyexr/SCsub
index 84b3b4015b..30bde96fb4 100644
--- a/modules/tinyexr/SCsub
+++ b/modules/tinyexr/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_tinyexr = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
# Not unbundled for now as they are not commonly available as shared library
thirdparty_dir = "#thirdparty/tinyexr/"
thirdparty_sources = [
@@ -20,7 +23,15 @@ env_tinyexr.Append(CPPDEFINES=["TINYEXR_USE_THREAD"])
env_thirdparty = env_tinyexr.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_tinyexr.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Godot's own source files
-env_tinyexr.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp
index 1c0f3cd03e..47214e6974 100644
--- a/modules/tinyexr/image_loader_tinyexr.cpp
+++ b/modules/tinyexr/image_loader_tinyexr.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,11 @@
#include "image_loader_tinyexr.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include "thirdparty/tinyexr/tinyexr.h"
Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
Vector<uint8_t> src_image;
int src_image_len = f->get_len();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
@@ -62,7 +61,6 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
int ret = ParseEXRVersionFromMemory(&exr_version, w, src_image_len);
if (ret != TINYEXR_SUCCESS) {
-
return ERR_FILE_CORRUPT;
}
@@ -75,8 +73,10 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
}
// Read HALF channel as FLOAT. (GH-13490)
+ bool use_float16 = false;
for (int i = 0; i < exr_header.num_channels; i++) {
if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
+ use_float16 = true;
exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
@@ -104,33 +104,10 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
idxB = c;
} else if (strcmp(exr_header.channels[c].name, "A") == 0) {
idxA = c;
- }
- }
-
- if (exr_header.num_channels == 1) {
- // Grayscale channel only.
- idxR = 0;
- idxG = 0;
- idxB = 0;
- idxA = 0;
- } else {
- // Assume RGB(A)
- if (idxR == -1) {
- ERR_PRINT("TinyEXR: R channel not found.");
- // @todo { free exr_image }
- return ERR_FILE_CORRUPT;
- }
-
- if (idxG == -1) {
- 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.");
- // @todo { free exr_image }
- return ERR_FILE_CORRUPT;
+ } else if (strcmp(exr_header.channels[c].name, "Y") == 0) {
+ idxR = c;
+ idxG = c;
+ idxB = c;
}
}
@@ -140,16 +117,27 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
Image::Format format;
int output_channels = 0;
+ int channel_size = use_float16 ? 2 : 4;
if (idxA != -1) {
-
- imgdata.resize(exr_image.width * exr_image.height * 8); //RGBA16
- format = Image::FORMAT_RGBAH;
+ imgdata.resize(exr_image.width * exr_image.height * 4 * channel_size); //RGBA
+ format = use_float16 ? Image::FORMAT_RGBAH : Image::FORMAT_RGBAF;
output_channels = 4;
- } else {
-
- imgdata.resize(exr_image.width * exr_image.height * 6); //RGB16
- format = Image::FORMAT_RGBH;
+ } else if (idxB != -1) {
+ ERR_FAIL_COND_V(idxG == -1, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(idxR == -1, ERR_FILE_CORRUPT);
+ imgdata.resize(exr_image.width * exr_image.height * 3 * channel_size); //RGB
+ format = use_float16 ? Image::FORMAT_RGBH : Image::FORMAT_RGBF;
output_channels = 3;
+ } else if (idxG != -1) {
+ ERR_FAIL_COND_V(idxR == -1, ERR_FILE_CORRUPT);
+ imgdata.resize(exr_image.width * exr_image.height * 2 * channel_size); //RG
+ format = use_float16 ? Image::FORMAT_RGH : Image::FORMAT_RGF;
+ output_channels = 2;
+ } else {
+ ERR_FAIL_COND_V(idxR == -1, ERR_FILE_CORRUPT);
+ imgdata.resize(exr_image.width * exr_image.height * 1 * channel_size); //R
+ format = use_float16 ? Image::FORMAT_RH : Image::FORMAT_RF;
+ output_channels = 1;
}
EXRTile single_image_tile;
@@ -179,54 +167,113 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
exr_tiles = exr_image.tiles;
}
+ //print_line("reading format: " + Image::get_format_name(format));
{
uint8_t *wd = imgdata.ptrw();
- uint16_t *iw = (uint16_t *)wd;
+ uint16_t *iw16 = (uint16_t *)wd;
+ float *iw32 = (float *)wd;
// Assume `out_rgba` have enough memory allocated.
for (int tile_index = 0; tile_index < num_tiles; tile_index++) {
-
const EXRTile &tile = exr_tiles[tile_index];
int tw = tile.width;
int th = tile.height;
const float *r_channel_start = reinterpret_cast<const float *>(tile.images[idxR]);
- const float *g_channel_start = reinterpret_cast<const float *>(tile.images[idxG]);
- const float *b_channel_start = reinterpret_cast<const float *>(tile.images[idxB]);
+ const float *g_channel_start = nullptr;
+ const float *b_channel_start = nullptr;
const float *a_channel_start = nullptr;
+ if (idxG != -1) {
+ g_channel_start = reinterpret_cast<const float *>(tile.images[idxG]);
+ }
+ if (idxB != -1) {
+ b_channel_start = reinterpret_cast<const float *>(tile.images[idxB]);
+ }
if (idxA != -1) {
a_channel_start = reinterpret_cast<const float *>(tile.images[idxA]);
}
- uint16_t *first_row_w = iw + (tile.offset_y * tile_height * exr_image.width + tile.offset_x * tile_width) * output_channels;
+ uint16_t *first_row_w16 = iw16 + (tile.offset_y * tile_height * exr_image.width + tile.offset_x * tile_width) * output_channels;
+ float *first_row_w32 = iw32 + (tile.offset_y * tile_height * exr_image.width + tile.offset_x * tile_width) * output_channels;
for (int y = 0; y < th; y++) {
const float *r_channel = r_channel_start + y * tile_width;
- const float *g_channel = g_channel_start + y * tile_width;
- const float *b_channel = b_channel_start + y * tile_width;
+ const float *g_channel = nullptr;
+ const float *b_channel = nullptr;
const float *a_channel = nullptr;
-
+ if (g_channel_start) {
+ g_channel = g_channel_start + y * tile_width;
+ }
+ if (b_channel_start) {
+ b_channel = b_channel_start + y * tile_width;
+ }
if (a_channel_start) {
a_channel = a_channel_start + y * tile_width;
}
- uint16_t *row_w = first_row_w + (y * exr_image.width * output_channels);
-
- for (int x = 0; x < tw; x++) {
-
- Color color(*r_channel++, *g_channel++, *b_channel++);
-
- if (p_force_linear)
- color = color.to_linear();
-
- *row_w++ = Math::make_half_float(color.r);
- *row_w++ = Math::make_half_float(color.g);
- *row_w++ = Math::make_half_float(color.b);
-
- if (idxA != -1) {
- *row_w++ = Math::make_half_float(*a_channel++);
+ if (use_float16) {
+ uint16_t *row_w = first_row_w16 + (y * exr_image.width * output_channels);
+
+ for (int x = 0; x < tw; x++) {
+ Color color;
+ color.r = *r_channel++;
+ if (g_channel) {
+ color.g = *g_channel++;
+ }
+ if (b_channel) {
+ color.b = *b_channel++;
+ }
+ if (a_channel) {
+ color.a = *a_channel++;
+ }
+
+ if (p_force_linear) {
+ color = color.to_linear();
+ }
+
+ *row_w++ = Math::make_half_float(color.r);
+ if (g_channel) {
+ *row_w++ = Math::make_half_float(color.g);
+ }
+ if (b_channel) {
+ *row_w++ = Math::make_half_float(color.b);
+ }
+ if (a_channel) {
+ *row_w++ = Math::make_half_float(color.a);
+ }
+ }
+ } else {
+ float *row_w = first_row_w32 + (y * exr_image.width * output_channels);
+
+ for (int x = 0; x < tw; x++) {
+ Color color;
+ color.r = *r_channel++;
+ if (g_channel) {
+ color.g = *g_channel++;
+ }
+ if (b_channel) {
+ color.b = *b_channel++;
+ }
+ if (a_channel) {
+ color.a = *a_channel++;
+ }
+
+ if (p_force_linear) {
+ color = color.to_linear();
+ }
+
+ *row_w++ = color.r;
+ if (g_channel) {
+ *row_w++ = color.g;
+ }
+ if (b_channel) {
+ *row_w++ = color.b;
+ }
+ if (a_channel) {
+ *row_w++ = color.a;
+ }
}
}
}
@@ -242,7 +289,6 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
}
void ImageLoaderTinyEXR::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("exr");
}
diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h
index af95989254..34390fccb0 100644
--- a/modules/tinyexr/image_loader_tinyexr.h
+++ b/modules/tinyexr/image_loader_tinyexr.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/io/image_loader.h"
class ImageLoaderTinyEXR : public ImageFormatLoader {
-
public:
virtual Error load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/tinyexr/image_saver_tinyexr.cpp b/modules/tinyexr/image_saver_tinyexr.cpp
index 05080289bd..f747763248 100644
--- a/modules/tinyexr/image_saver_tinyexr.cpp
+++ b/modules/tinyexr/image_saver_tinyexr.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -140,7 +140,6 @@ static int get_channel_count(Image::Format p_format) {
}
Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale) {
-
Image::Format format = p_img->get_format();
if (!is_supported_format(format)) {
@@ -192,7 +191,6 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale)
const uint8_t *src_r = src_data.ptr();
for (int channel_index = 0; channel_index < channel_count; ++channel_index) {
-
// De-interleave channels
PackedByteArray &dst = channels[channel_index];
@@ -201,7 +199,6 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale)
uint8_t *dst_w = dst.ptrw();
if (src_pixel_type == SRC_FLOAT && target_pixel_type == TINYEXR_PIXELTYPE_FLOAT) {
-
// Note: we don't save mipmaps
CRASH_COND(src_data.size() < pixel_count * channel_count * target_pixel_type_size);
@@ -213,7 +210,6 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale)
}
} else if (src_pixel_type == SRC_HALF && target_pixel_type == TINYEXR_PIXELTYPE_HALF) {
-
CRASH_COND(src_data.size() < pixel_count * channel_count * target_pixel_type_size);
const uint16_t *src_rp = (uint16_t *)src_r;
@@ -224,7 +220,6 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale)
}
} else if (src_pixel_type == SRC_BYTE && target_pixel_type == TINYEXR_PIXELTYPE_HALF) {
-
CRASH_COND(src_data.size() < pixel_count * channel_count);
const uint8_t *src_rp = (uint8_t *)src_r;
@@ -267,13 +262,21 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale)
header.channels = channel_infos;
header.pixel_types = pixel_types;
header.requested_pixel_types = requested_pixel_types;
+ header.compression_type = TINYEXR_COMPRESSIONTYPE_PIZ;
+
+ unsigned char *mem = nullptr;
+ const char *err = nullptr;
+
+ size_t bytes = SaveEXRImageToMemory(&image, &header, &mem, &err);
- CharString utf8_filename = p_path.utf8();
- const char *err;
- int ret = SaveEXRImageToFile(&image, &header, utf8_filename.ptr(), &err);
- if (ret != TINYEXR_SUCCESS) {
+ if (bytes == 0) {
print_error(String("Saving EXR failed. Error: {0}").format(varray(err)));
return ERR_FILE_CANT_WRITE;
+ } else {
+ FileAccessRef ref = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!ref, ERR_FILE_CANT_WRITE);
+ ref->store_buffer(mem, bytes);
+ free(mem);
}
return OK;
diff --git a/modules/tinyexr/image_saver_tinyexr.h b/modules/tinyexr/image_saver_tinyexr.h
index c7154bcfc7..e5060ef11c 100644
--- a/modules/tinyexr/image_saver_tinyexr.h
+++ b/modules/tinyexr/image_saver_tinyexr.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/tinyexr/register_types.cpp b/modules/tinyexr/register_types.cpp
index af05a411e1..ecbabc4951 100644
--- a/modules/tinyexr/register_types.cpp
+++ b/modules/tinyexr/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,6 @@
static ImageLoaderTinyEXR *image_loader_tinyexr = nullptr;
void register_tinyexr_types() {
-
image_loader_tinyexr = memnew(ImageLoaderTinyEXR);
ImageLoader::add_image_format_loader(image_loader_tinyexr);
@@ -44,7 +43,6 @@ void register_tinyexr_types() {
}
void unregister_tinyexr_types() {
-
memdelete(image_loader_tinyexr);
Image::save_exr_func = nullptr;
diff --git a/modules/tinyexr/register_types.h b/modules/tinyexr/register_types.h
index 9739488312..e401f37066 100644
--- a/modules/tinyexr/register_types.h
+++ b/modules/tinyexr/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/upnp/SCsub b/modules/upnp/SCsub
index 2e129e15ca..bc0b215be3 100644
--- a/modules/upnp/SCsub
+++ b/modules/upnp/SCsub
@@ -7,6 +7,8 @@ env_upnp = env_modules.Clone()
# Thirdparty source files
+thirdparty_obj = []
+
if env["builtin_miniupnpc"]:
thirdparty_dir = "#thirdparty/miniupnpc/"
thirdparty_sources = [
@@ -31,7 +33,16 @@ if env["builtin_miniupnpc"]:
env_thirdparty = env_upnp.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_upnp.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_upnp.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/upnp/register_types.cpp b/modules/upnp/register_types.cpp
index 270aa2d7e8..a5ee39517f 100644
--- a/modules/upnp/register_types.cpp
+++ b/modules/upnp/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "register_types.h"
-#include "core/error_macros.h"
+#include "core/error/error_macros.h"
#include "upnp.h"
#include "upnp_device.h"
void register_upnp_types() {
-
ClassDB::register_class<UPNP>();
ClassDB::register_class<UPNPDevice>();
}
diff --git a/modules/upnp/register_types.h b/modules/upnp/register_types.h
index 0c71db9ffa..768031c4d9 100644
--- a/modules/upnp/register_types.h
+++ b/modules/upnp/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/upnp/upnp.cpp b/modules/upnp/upnp.cpp
index 988bf3017d..8c3be884bd 100644
--- a/modules/upnp/upnp.cpp
+++ b/modules/upnp/upnp.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -36,7 +36,7 @@
#include <stdlib.h>
bool UPNP::is_common_device(const String &dev) const {
- return dev.empty() ||
+ return dev.is_empty() ||
dev.find("InternetGatewayDevice") >= 0 ||
dev.find("WANIPConnection") >= 0 ||
dev.find("WANPPPConnection") >= 0 ||
@@ -76,7 +76,7 @@ int UPNP::discover(int timeout, int ttl, const String &device_filter) {
struct UPNPDev *dev = devlist;
while (dev) {
- if (device_filter.empty() || strstr(dev->st, device_filter.utf8().get_data())) {
+ if (device_filter.is_empty() || strstr(dev->st, device_filter.utf8().get_data())) {
add_device_to_list(dev, devlist);
}
diff --git a/modules/upnp/upnp.h b/modules/upnp/upnp.h
index 46f44e04e5..9dfa907476 100644
--- a/modules/upnp/upnp.h
+++ b/modules/upnp/upnp.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,14 +31,13 @@
#ifndef GODOT_UPNP_H
#define GODOT_UPNP_H
-#include "core/reference.h"
+#include "core/object/reference.h"
#include "upnp_device.h"
#include <miniupnpc/miniupnpc.h>
class UPNP : public Reference {
-
GDCLASS(UPNP, Reference);
private:
@@ -58,7 +57,6 @@ protected:
public:
enum UPNPResult {
-
UPNP_RESULT_SUCCESS,
UPNP_RESULT_NOT_AUTHORIZED,
UPNP_RESULT_PORT_MAPPING_NOT_FOUND,
diff --git a/modules/upnp/upnp_device.cpp b/modules/upnp/upnp_device.cpp
index 40eb6106a0..ddc66d593c 100644
--- a/modules/upnp/upnp_device.cpp
+++ b/modules/upnp/upnp_device.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -65,7 +65,7 @@ int UPNPDevice::add_port_mapping(int port, int port_internal, String desc, Strin
itos(port).utf8().get_data(),
itos(port_internal).utf8().get_data(),
igd_our_addr.utf8().get_data(),
- desc.empty() ? nullptr : desc.utf8().get_data(),
+ desc.is_empty() ? nullptr : desc.utf8().get_data(),
proto.utf8().get_data(),
nullptr, // Remote host, always nullptr as IGDs don't support it
duration > 0 ? itos(duration).utf8().get_data() : nullptr);
diff --git a/modules/upnp/upnp_device.h b/modules/upnp/upnp_device.h
index f25d3427fc..126e761a56 100644
--- a/modules/upnp/upnp_device.h
+++ b/modules/upnp/upnp_device.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,15 +31,13 @@
#ifndef GODOT_UPNP_DEVICE_H
#define GODOT_UPNP_DEVICE_H
-#include "core/reference.h"
+#include "core/object/reference.h"
class UPNPDevice : public Reference {
-
GDCLASS(UPNPDevice, Reference);
public:
enum IGDStatus {
-
IGD_STATUS_OK,
IGD_STATUS_HTTP_ERROR,
IGD_STATUS_HTTP_EMPTY,
diff --git a/modules/vhacd/SCsub b/modules/vhacd/SCsub
index ecd432b275..1ff4122114 100644
--- a/modules/vhacd/SCsub
+++ b/modules/vhacd/SCsub
@@ -7,6 +7,8 @@ env_vhacd = env_modules.Clone()
# Thirdparty source files
+thirdparty_obj = []
+
thirdparty_dir = "#thirdparty/vhacd/"
thirdparty_sources = [
@@ -24,10 +26,19 @@ thirdparty_sources = [
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
-env_vhacd.Prepend(CPPPATH=[thirdparty_dir + "/inc"])
+env_vhacd.Prepend(CPPPATH=[thirdparty_dir + "inc"])
env_thirdparty = env_vhacd.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
+
+# Godot source files
+
+module_obj = []
+
+env_vhacd.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-env_vhacd.add_source_files(env.modules_sources, "*.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/vhacd/register_types.cpp b/modules/vhacd/register_types.cpp
index c006a9deec..daad39bdfb 100644
--- a/modules/vhacd/register_types.cpp
+++ b/modules/vhacd/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "thirdparty/vhacd/public/VHACD.h"
static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces) {
-
Vector<float> vertices;
vertices.resize(p_faces.size() * 9);
Vector<uint32_t> indices;
diff --git a/modules/vhacd/register_types.h b/modules/vhacd/register_types.h
index d02a990901..24ad9378f4 100644
--- a/modules/vhacd/register_types.h
+++ b/modules/vhacd/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py
index bd459ca344..b15479797c 100644
--- a/modules/visual_script/config.py
+++ b/modules/visual_script/config.py
@@ -8,7 +8,6 @@ def configure(env):
def get_doc_classes():
return [
- "@VisualScript",
"VisualScriptBasicTypeConstant",
"VisualScriptBuiltinFunc",
"VisualScriptClassConstant",
diff --git a/modules/visual_script/doc_classes/@VisualScript.xml b/modules/visual_script/doc_classes/@VisualScript.xml
deleted file mode 100644
index a2b966bfbb..0000000000
--- a/modules/visual_script/doc_classes/@VisualScript.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" ?>
-<class name="@VisualScript" version="4.0">
- <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>
- <methods>
- </methods>
- <constants>
- </constants>
-</class>
diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml
index db1ef2adc6..5112ea43a7 100644
--- a/modules/visual_script/doc_classes/VisualScript.xml
+++ b/modules/visual_script/doc_classes/VisualScript.xml
@@ -9,7 +9,7 @@
You are most likely to use this class via the Visual Script editor or when writing plugins for it.
</description>
<tutorials>
- <link>https://docs.godotengine.org/en/latest/getting_started/scripting/visual_script/index.html</link>
+ <link title="VisualScript tutorial index">https://docs.godotengine.org/en/latest/getting_started/scripting/visual_script/index.html</link>
</tutorials>
<methods>
<method name="add_custom_signal">
@@ -26,23 +26,23 @@
</return>
<argument index="0" name="name" type="StringName">
</argument>
+ <argument index="1" name="func_node_id" type="int">
+ </argument>
<description>
- Add a function with the specified name to the VisualScript.
+ Add a function with the specified name to the VisualScript, and assign the root [VisualScriptFunction] node's id as [code]func_node_id[/code].
</description>
</method>
<method name="add_node">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
- <argument index="2" name="node" type="VisualScriptNode">
+ <argument index="1" name="node" type="VisualScriptNode">
</argument>
- <argument index="3" name="position" type="Vector2" default="Vector2( 0, 0 )">
+ <argument index="2" name="position" type="Vector2" default="Vector2( 0, 0 )">
</argument>
<description>
- Add a node to a function of the VisualScript.
+ Add a node to the VisualScript.
</description>
</method>
<method name="add_variable">
@@ -157,15 +157,13 @@
<method name="data_connect">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="2" name="from_port" type="int">
+ <argument index="1" name="from_port" type="int">
</argument>
- <argument index="3" name="to_node" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
- <argument index="4" name="to_port" type="int">
+ <argument index="3" name="to_port" type="int">
</argument>
<description>
Connect two data ports. The value of [code]from_node[/code]'s [code]from_port[/code] would be fed into [code]to_node[/code]'s [code]to_port[/code].
@@ -174,15 +172,13 @@
<method name="data_disconnect">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="1" name="from_port" type="int">
</argument>
- <argument index="2" name="from_port" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
- <argument index="3" name="to_node" type="int">
- </argument>
- <argument index="4" name="to_port" type="int">
+ <argument index="3" name="to_port" type="int">
</argument>
<description>
Disconnect two data ports previously connected with [method data_connect].
@@ -197,37 +193,31 @@
Returns the id of a function's entry point node.
</description>
</method>
- <method name="get_function_scroll" qualifiers="const">
- <return type="Vector2">
- </return>
- <argument index="0" name="name" type="StringName">
- </argument>
- <description>
- Returns the position of the center of the screen for a given function.
- </description>
- </method>
<method name="get_node" qualifiers="const">
<return type="VisualScriptNode">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
<description>
- Returns a node given its id and its function.
+ Returns a node given its id.
</description>
</method>
<method name="get_node_position" qualifiers="const">
<return type="Vector2">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
<description>
Returns a node's position in pixels.
</description>
</method>
+ <method name="get_scroll" qualifiers="const">
+ <return type="Vector2">
+ </return>
+ <description>
+ Returns the current position of the center of the screen.
+ </description>
+ </method>
<method name="get_variable_default_value" qualifiers="const">
<return type="Variant">
</return>
@@ -267,15 +257,13 @@
<method name="has_data_connection" qualifiers="const">
<return type="bool">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="2" name="from_port" type="int">
+ <argument index="1" name="from_port" type="int">
</argument>
- <argument index="3" name="to_node" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
- <argument index="4" name="to_port" type="int">
+ <argument index="3" name="to_port" type="int">
</argument>
<description>
Returns whether the specified data ports are connected.
@@ -293,9 +281,7 @@
<method name="has_node" qualifiers="const">
<return type="bool">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
<description>
Returns whether a node exists with the given id.
@@ -304,13 +290,11 @@
<method name="has_sequence_connection" qualifiers="const">
<return type="bool">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="2" name="from_output" type="int">
+ <argument index="1" name="from_output" type="int">
</argument>
- <argument index="3" name="to_node" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
<description>
Returns whether the specified sequence ports are connected.
@@ -346,12 +330,10 @@
<method name="remove_node">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
<description>
- Remove a specific node.
+ Remove the node with the specified id.
</description>
</method>
<method name="remove_variable">
@@ -399,13 +381,11 @@
<method name="sequence_connect">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="1" name="from_output" type="int">
</argument>
- <argument index="2" name="from_output" type="int">
- </argument>
- <argument index="3" name="to_node" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
<description>
Connect two sequence ports. The execution will flow from of [code]from_node[/code]'s [code]from_output[/code] into [code]to_node[/code].
@@ -415,29 +395,16 @@
<method name="sequence_disconnect">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
- </argument>
- <argument index="1" name="from_node" type="int">
+ <argument index="0" name="from_node" type="int">
</argument>
- <argument index="2" name="from_output" type="int">
+ <argument index="1" name="from_output" type="int">
</argument>
- <argument index="3" name="to_node" type="int">
+ <argument index="2" name="to_node" type="int">
</argument>
<description>
Disconnect two sequence ports previously connected with [method sequence_connect].
</description>
</method>
- <method name="set_function_scroll">
- <return type="void">
- </return>
- <argument index="0" name="name" type="StringName">
- </argument>
- <argument index="1" name="ofs" type="Vector2">
- </argument>
- <description>
- Position the center of the screen for a function.
- </description>
- </method>
<method name="set_instance_base_type">
<return type="void">
</return>
@@ -450,14 +417,21 @@
<method name="set_node_position">
<return type="void">
</return>
- <argument index="0" name="func" type="StringName">
+ <argument index="0" name="id" type="int">
</argument>
- <argument index="1" name="id" type="int">
+ <argument index="1" name="position" type="Vector2">
</argument>
- <argument index="2" name="position" type="Vector2">
+ <description>
+ Set the node position in the VisualScript graph.
+ </description>
+ </method>
+ <method name="set_scroll">
+ <return type="void">
+ </return>
+ <argument index="0" name="ofs" type="Vector2">
</argument>
<description>
- Position a node on the screen.
+ Set the screen center to the given position.
</description>
</method>
<method name="set_variable_default_value">
@@ -496,9 +470,7 @@
</methods>
<signals>
<signal name="node_ports_changed">
- <argument index="0" name="function" type="String">
- </argument>
- <argument index="1" name="id" type="int">
+ <argument index="0" name="id" type="int">
</argument>
<description>
Emitted when the ports of a node are changed.
diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
index ef4183e6f6..4004f1a04c 100644
--- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
+++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
@@ -92,7 +92,7 @@
<constant name="MATH_STEP_DECIMALS" value="24" enum="BuiltinFunc">
Return the number of digit places after the decimal that the first non-zero digit occurs.
</constant>
- <constant name="MATH_STEPIFY" value="25" enum="BuiltinFunc">
+ <constant name="MATH_SNAPPED" value="25" enum="BuiltinFunc">
Return the input snapped to a given step.
</constant>
<constant name="MATH_LERP" value="26" enum="BuiltinFunc">
@@ -111,61 +111,61 @@
<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="32" enum="BuiltinFunc">
+ <constant name="MATH_RANDI" 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="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="34" enum="BuiltinFunc">
+ <constant name="MATH_RANDF_RANGE" value="34" enum="BuiltinFunc">
Return a random floating-point value between the two inputs.
</constant>
- <constant name="MATH_SEED" value="35" enum="BuiltinFunc">
+ <constant name="MATH_RANDI_RANGE" value="35" enum="BuiltinFunc">
+ Return a random 32-bit integer value between the two inputs.
+ </constant>
+ <constant name="MATH_SEED" value="36" enum="BuiltinFunc">
Set the seed for the random number generator.
</constant>
- <constant name="MATH_RANDSEED" value="36" enum="BuiltinFunc">
+ <constant name="MATH_RANDSEED" value="37" enum="BuiltinFunc">
Return a random value from the given seed, along with the new seed.
</constant>
- <constant name="MATH_DEG2RAD" value="37" enum="BuiltinFunc">
+ <constant name="MATH_DEG2RAD" value="38" enum="BuiltinFunc">
Convert the input from degrees to radians.
</constant>
- <constant name="MATH_RAD2DEG" value="38" enum="BuiltinFunc">
+ <constant name="MATH_RAD2DEG" value="39" enum="BuiltinFunc">
Convert the input from radians to degrees.
</constant>
- <constant name="MATH_LINEAR2DB" value="39" enum="BuiltinFunc">
+ <constant name="MATH_LINEAR2DB" value="40" enum="BuiltinFunc">
Convert the input from linear volume to decibel volume.
</constant>
- <constant name="MATH_DB2LINEAR" value="40" enum="BuiltinFunc">
+ <constant name="MATH_DB2LINEAR" value="41" enum="BuiltinFunc">
Convert the input from decibel volume to linear volume.
</constant>
- <constant name="MATH_POLAR2CARTESIAN" value="41" enum="BuiltinFunc">
+ <constant name="MATH_POLAR2CARTESIAN" value="42" 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="42" enum="BuiltinFunc">
+ <constant name="MATH_CARTESIAN2POLAR" value="43" 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="43" enum="BuiltinFunc">
+ <constant name="MATH_WRAP" value="44" enum="BuiltinFunc">
</constant>
- <constant name="MATH_WRAPF" value="44" enum="BuiltinFunc">
+ <constant name="MATH_WRAPF" value="45" enum="BuiltinFunc">
</constant>
- <constant name="LOGIC_MAX" value="45" enum="BuiltinFunc">
+ <constant name="LOGIC_MAX" value="46" enum="BuiltinFunc">
Return the greater of the two numbers, also known as their maximum.
</constant>
- <constant name="LOGIC_MIN" value="46" enum="BuiltinFunc">
+ <constant name="LOGIC_MIN" value="47" enum="BuiltinFunc">
Return the lesser of the two numbers, also known as their minimum.
</constant>
- <constant name="LOGIC_CLAMP" value="47" enum="BuiltinFunc">
+ <constant name="LOGIC_CLAMP" value="48" 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="48" enum="BuiltinFunc">
+ <constant name="LOGIC_NEAREST_PO2" value="49" enum="BuiltinFunc">
Return the nearest power of 2 to the input.
</constant>
- <constant name="OBJ_WEAKREF" value="49" enum="BuiltinFunc">
+ <constant name="OBJ_WEAKREF" value="50" enum="BuiltinFunc">
Create a [WeakRef] from the input.
</constant>
- <constant name="FUNC_FUNCREF" value="50" enum="BuiltinFunc">
- Create a [FuncRef] from the input.
- </constant>
<constant name="TYPE_CONVERT" value="51" enum="BuiltinFunc">
Convert between types.
</constant>
diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml
index 5b64d8438b..8a7254b46a 100644
--- a/modules/visual_script/doc_classes/VisualScriptLists.xml
+++ b/modules/visual_script/doc_classes/VisualScriptLists.xml
@@ -4,7 +4,7 @@
A Visual Script virtual class for in-graph editable nodes.
</brief_description>
<description>
- A Visual Script virtual class that defines the shape and the default behaviour of the nodes that have to be in-graph editable nodes.
+ A Visual Script virtual class that defines the shape and the default behavior of the nodes that have to be in-graph editable nodes.
</description>
<tutorials>
</tutorials>
diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
index f13d449064..1c22070ab1 100644
--- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
@@ -31,5 +31,7 @@
</constant>
<constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode">
</constant>
+ <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode">
+ </constant>
</constants>
</class>
diff --git a/modules/visual_script/icons/VisualScript.svg b/modules/visual_script/icons/VisualScript.svg
index f6475d590e..2352ba5d87 100644
--- a/modules/visual_script/icons/VisualScript.svg
+++ b/modules/visual_script/icons/VisualScript.svg
@@ -1,6 +1 @@
-<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>
+<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><g transform="translate(0 -1036.4)"><ellipse cx="3" cy="1039.4" fill="#6e6e6e"/><path d="m7 1-.56445 2.2578a5 5 0 0 0 -.68945.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -.28516.68555l-2.2539.5625v2h5.2715a2 2 0 0 1 -.27148-1 2 2 0 0 1 2-2 2 2 0 0 1 2 2 2 2 0 0 1 -.26953 1h5.2695v-2l-2.2578-.56445a5 5 0 0 0 -.2793-.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -.68555-.28516l-.5625-2.2539h-2zm-4 9v6h2a3 3 0 0 0 3-3v-3h-2v3a1 1 0 0 1 -1 1v-4zm8 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-2z" fill="#e0e0e0" transform="translate(0 1036.4)"/></g></svg>
diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp
index 5ea84a32c4..4c7b66e368 100644
--- a/modules/visual_script/register_types.cpp
+++ b/modules/visual_script/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "register_types.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "core/io/resource_loader.h"
#include "visual_script.h"
#include "visual_script_builtin_funcs.h"
@@ -47,7 +47,6 @@ static _VisualScriptEditor *vs_editor_singleton = nullptr;
#endif
void register_visual_script_types() {
-
visual_script_language = memnew(VisualScriptLanguage);
//script_language_gd->init();
ScriptServer::register_language(visual_script_language);
@@ -125,7 +124,6 @@ void register_visual_script_types() {
}
void unregister_visual_script_types() {
-
unregister_visual_script_nodes();
ScriptServer::unregister_language(visual_script_language);
@@ -136,6 +134,7 @@ void unregister_visual_script_types() {
memdelete(vs_editor_singleton);
}
#endif
- if (visual_script_language)
+ if (visual_script_language) {
memdelete(visual_script_language);
+ }
}
diff --git a/modules/visual_script/register_types.h b/modules/visual_script/register_types.h
index c18c2930b1..b02a93ebc1 100644
--- a/modules/visual_script/register_types.h
+++ b/modules/visual_script/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp
index fe1d82f977..fe92f59179 100644
--- a/modules/visual_script/visual_script.cpp
+++ b/modules/visual_script/visual_script.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,21 +30,18 @@
#include "visual_script.h"
+#include "core/config/project_settings.h"
#include "core/core_string_names.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "scene/main/node.h"
#include "visual_script_nodes.h"
-#include <stdint.h>
-
-//used by editor, this is not really saved
+// Used by editor, this is not really saved.
void VisualScriptNode::set_breakpoint(bool p_breakpoint) {
breakpoint = p_breakpoint;
}
bool VisualScriptNode::is_breakpoint() const {
-
return breakpoint;
}
@@ -53,56 +50,51 @@ void VisualScriptNode::ports_changed_notify() {
}
void VisualScriptNode::set_default_input_value(int p_port, const Variant &p_value) {
-
ERR_FAIL_INDEX(p_port, default_input_values.size());
default_input_values[p_port] = p_value;
#ifdef TOOLS_ENABLED
- for (Set<VisualScript *>::Element *E = scripts_used.front(); E; E = E->next()) {
- E->get()->set_edited(true);
+ if (script_used.is_valid()) {
+ script_used->set_edited(true);
}
#endif
}
Variant VisualScriptNode::get_default_input_value(int p_port) const {
-
ERR_FAIL_INDEX_V(p_port, default_input_values.size(), Variant());
return default_input_values[p_port];
}
void VisualScriptNode::_set_default_input_values(Array p_values) {
-
default_input_values = p_values;
}
void VisualScriptNode::validate_input_default_values() {
default_input_values.resize(MAX(default_input_values.size(), get_input_value_port_count())); //let it grow as big as possible, we don't want to lose values on resize
- //actually validate on save
+ // Actually validate on save.
for (int i = 0; i < get_input_value_port_count(); i++) {
-
Variant::Type expected = get_input_value_port_info(i).type;
if (expected == Variant::NIL || expected == default_input_values[i].get_type()) {
continue;
} else {
- //not the same, reconvert
+ // Not the same, reconvert.
Callable::CallError ce;
Variant existing = default_input_values[i];
const Variant *existingp = &existing;
- default_input_values[i] = Variant::construct(expected, &existingp, 1, ce, false);
+ Variant::construct(expected, default_input_values[i], &existingp, 1, ce);
if (ce.error != Callable::CallError::CALL_OK) {
//could not convert? force..
- default_input_values[i] = Variant::construct(expected, nullptr, 0, ce, false);
+ Variant::construct(expected, default_input_values[i], nullptr, 0, ce);
}
}
}
}
Array VisualScriptNode::_get_default_input_values() const {
-
- //validate on save, since on load there is little info about this
+ // Validate on save, since on load there is little info about this.
Array values = default_input_values;
values.resize(get_input_value_port_count());
@@ -114,7 +106,6 @@ String VisualScriptNode::get_text() const {
}
void VisualScriptNode::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("get_visual_script"), &VisualScriptNode::get_visual_script);
ClassDB::bind_method(D_METHOD("set_default_input_value", "port_idx", "value"), &VisualScriptNode::set_default_input_value);
ClassDB::bind_method(D_METHOD("get_default_input_value", "port_idx"), &VisualScriptNode::get_default_input_value);
@@ -127,6 +118,7 @@ void VisualScriptNode::_bind_methods() {
}
VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
+ ERR_FAIL_COND_V(get_output_value_port_count() <= p_output, TypeGuess());
PropertyInfo pinfo = get_output_value_port_info(p_output);
@@ -141,11 +133,7 @@ VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inp
}
Ref<VisualScript> VisualScriptNode::get_visual_script() const {
-
- if (scripts_used.size())
- return Ref<VisualScript>(scripts_used.front()->get());
-
- return Ref<VisualScript>();
+ return script_used;
}
VisualScriptNode::VisualScriptNode() {
@@ -157,13 +145,11 @@ VisualScriptNode::VisualScriptNode() {
/////////////////////
VisualScriptNodeInstance::VisualScriptNodeInstance() {
-
sequence_outputs = nullptr;
input_ports = nullptr;
}
VisualScriptNodeInstance::~VisualScriptNodeInstance() {
-
if (sequence_outputs) {
memdelete_arr(sequence_outputs);
}
@@ -177,40 +163,35 @@ VisualScriptNodeInstance::~VisualScriptNodeInstance() {
}
}
-void VisualScript::add_function(const StringName &p_name) {
-
+void VisualScript::add_function(const StringName &p_name, int p_func_node_id) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(functions.has(p_name));
+ ERR_FAIL_COND(variables.has(p_name));
+ ERR_FAIL_COND(custom_signals.has(p_name));
functions[p_name] = Function();
- functions[p_name].scroll = Vector2(-50, -100);
+ functions[p_name].func_id = p_func_node_id;
}
bool VisualScript::has_function(const StringName &p_name) const {
-
return functions.has(p_name);
}
-void VisualScript::remove_function(const StringName &p_name) {
+void VisualScript::remove_function(const StringName &p_name) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!functions.has(p_name));
- for (Map<int, Function::NodeData>::Element *E = functions[p_name].nodes.front(); E; E = E->next()) {
-
- E->get().node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed));
- E->get().node->scripts_used.erase(this);
- }
-
+ // Let the editor handle the node removal.
functions.erase(p_name);
}
void VisualScript::rename_function(const StringName &p_name, const StringName &p_new_name) {
-
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!functions.has(p_name));
- if (p_new_name == p_name)
+ if (p_new_name == p_name) {
return;
+ }
ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
@@ -222,80 +203,54 @@ void VisualScript::rename_function(const StringName &p_name, const StringName &p
functions.erase(p_name);
}
-void VisualScript::set_function_scroll(const StringName &p_name, const Vector2 &p_scroll) {
-
- ERR_FAIL_COND(!functions.has(p_name));
- functions[p_name].scroll = p_scroll;
+void VisualScript::set_scroll(const Vector2 &p_scroll) {
+ scroll = p_scroll;
}
-Vector2 VisualScript::get_function_scroll(const StringName &p_name) const {
-
- ERR_FAIL_COND_V(!functions.has(p_name), Vector2());
- return functions[p_name].scroll;
+Vector2 VisualScript::get_scroll() const {
+ return scroll;
}
void VisualScript::get_function_list(List<StringName> *r_functions) const {
-
- for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
- r_functions->push_back(E->key());
- }
-
- r_functions->sort_custom<StringName::AlphCompare>();
+ functions.get_key_list(r_functions);
+ // r_functions->sort_custom<StringName::AlphCompare>(); // Don't force sorting.
}
int VisualScript::get_function_node_id(const StringName &p_name) const {
-
ERR_FAIL_COND_V(!functions.has(p_name), -1);
- return functions[p_name].function_id;
+ return functions[p_name].func_id;
}
void VisualScript::_node_ports_changed(int p_id) {
-
- StringName function;
-
- for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
-
- if (E->get().nodes.has(p_id)) {
- function = E->key();
- break;
- }
- }
-
- ERR_FAIL_COND(function == StringName());
-
- Function &func = functions[function];
- Ref<VisualScriptNode> vsn = func.nodes[p_id].node;
+ Ref<VisualScriptNode> vsn = nodes[p_id].node;
vsn->validate_input_default_values();
- //must revalidate all the functions
+ // Must revalidate all the functions.
{
List<SequenceConnection> to_remove;
- for (Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) {
+ for (Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) {
if (E->get().from_node == p_id && E->get().from_output >= vsn->get_output_sequence_port_count()) {
-
to_remove.push_back(E->get());
}
if (E->get().to_node == p_id && !vsn->has_input_sequence_port()) {
-
to_remove.push_back(E->get());
}
}
while (to_remove.size()) {
- func.sequence_connections.erase(to_remove.front()->get());
+ sequence_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
}
{
-
List<DataConnection> to_remove;
- for (Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
+ for (Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
if (E->get().from_node == p_id && E->get().from_port >= vsn->get_output_value_port_count()) {
to_remove.push_back(E->get());
}
@@ -305,200 +260,136 @@ void VisualScript::_node_ports_changed(int p_id) {
}
while (to_remove.size()) {
- func.data_connections.erase(to_remove.front()->get());
+ data_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
}
#ifdef TOOLS_ENABLED
- set_edited(true); //something changed, let's set as edited
- emit_signal("node_ports_changed", function, p_id);
+ set_edited(true); // Something changed, let's set as edited.
+ emit_signal("node_ports_changed", p_id);
#endif
}
-void VisualScript::add_node(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) {
-
+void VisualScript::add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) {
ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_func));
-
- for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
+ ERR_FAIL_COND(nodes.has(p_id)); // ID can exist only one in script.
- ERR_FAIL_COND(E->get().nodes.has(p_id)); //id can exist only one in script, even for different functions
- }
-
- Function &func = functions[p_func];
-
- if (Object::cast_to<VisualScriptFunction>(*p_node)) {
- //the function indeed
- ERR_FAIL_COND_MSG(func.function_id >= 0, "A function node has already been set here.");
-
- func.function_id = p_id;
- }
-
- Function::NodeData nd;
+ NodeData nd;
nd.node = p_node;
nd.pos = p_pos;
Ref<VisualScriptNode> vsn = p_node;
vsn->connect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed), varray(p_id));
- vsn->scripts_used.insert(this);
- vsn->validate_input_default_values(); // Validate when fully loaded
+ vsn->script_used = Ref<VisualScript>(this);
+ vsn->validate_input_default_values(); // Validate when fully loaded.
- func.nodes[p_id] = nd;
+ nodes[p_id] = nd;
}
-void VisualScript::remove_node(const StringName &p_func, int p_id) {
-
+void VisualScript::remove_node(int p_id) {
ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
-
- ERR_FAIL_COND(!func.nodes.has(p_id));
+ ERR_FAIL_COND(!nodes.has(p_id));
{
List<SequenceConnection> to_remove;
- for (Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) {
+ for (Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) {
if (E->get().from_node == p_id || E->get().to_node == p_id) {
to_remove.push_back(E->get());
}
}
while (to_remove.size()) {
- func.sequence_connections.erase(to_remove.front()->get());
+ sequence_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
}
{
-
List<DataConnection> to_remove;
- for (Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
+ for (Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
if (E->get().from_node == p_id || E->get().to_node == p_id) {
to_remove.push_back(E->get());
}
}
while (to_remove.size()) {
- func.data_connections.erase(to_remove.front()->get());
+ data_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
}
- if (Object::cast_to<VisualScriptFunction>(func.nodes[p_id].node.ptr())) {
- func.function_id = -1; //revert to invalid
- }
-
- func.nodes[p_id].node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed));
- func.nodes[p_id].node->scripts_used.erase(this);
+ nodes[p_id].node->disconnect("ports_changed", callable_mp(this, &VisualScript::_node_ports_changed));
+ nodes[p_id].node->script_used.unref();
- func.nodes.erase(p_id);
+ nodes.erase(p_id);
}
-bool VisualScript::has_node(const StringName &p_func, int p_id) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), false);
- const Function &func = functions[p_func];
-
- return func.nodes.has(p_id);
+bool VisualScript::has_node(int p_id) const {
+ return nodes.has(p_id);
}
-Ref<VisualScriptNode> VisualScript::get_node(const StringName &p_func, int p_id) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), Ref<VisualScriptNode>());
- const Function &func = functions[p_func];
-
- ERR_FAIL_COND_V(!func.nodes.has(p_id), Ref<VisualScriptNode>());
+Ref<VisualScriptNode> VisualScript::get_node(int p_id) const {
+ ERR_FAIL_COND_V(!nodes.has(p_id), Ref<VisualScriptNode>());
- return func.nodes[p_id].node;
+ return nodes[p_id].node;
}
-void VisualScript::set_node_position(const StringName &p_func, int p_id, const Point2 &p_pos) {
-
+void VisualScript::set_node_position(int p_id, const Point2 &p_pos) {
ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
-
- ERR_FAIL_COND(!func.nodes.has(p_id));
- func.nodes[p_id].pos = p_pos;
+ ERR_FAIL_COND(!nodes.has(p_id));
+ nodes[p_id].pos = p_pos;
}
-Point2 VisualScript::get_node_position(const StringName &p_func, int p_id) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), Point2());
- const Function &func = functions[p_func];
-
- ERR_FAIL_COND_V(!func.nodes.has(p_id), Point2());
- return func.nodes[p_id].pos;
+Point2 VisualScript::get_node_position(int p_id) const {
+ ERR_FAIL_COND_V(!nodes.has(p_id), Point2());
+ return nodes[p_id].pos;
}
-void VisualScript::get_node_list(const StringName &p_func, List<int> *r_nodes) const {
-
- ERR_FAIL_COND(!functions.has(p_func));
- const Function &func = functions[p_func];
-
- for (const Map<int, Function::NodeData>::Element *E = func.nodes.front(); E; E = E->next()) {
- r_nodes->push_back(E->key());
- }
+void VisualScript::get_node_list(List<int> *r_nodes) const {
+ nodes.get_key_list(r_nodes);
}
-void VisualScript::sequence_connect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) {
-
+void VisualScript::sequence_connect(int p_from_node, int p_from_output, int p_to_node) {
ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
SequenceConnection sc;
sc.from_node = p_from_node;
sc.from_output = p_from_output;
sc.to_node = p_to_node;
- ERR_FAIL_COND(func.sequence_connections.has(sc));
+ ERR_FAIL_COND(sequence_connections.has(sc));
- func.sequence_connections.insert(sc);
+ sequence_connections.insert(sc);
}
-void VisualScript::sequence_disconnect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) {
-
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
-
+void VisualScript::sequence_disconnect(int p_from_node, int p_from_output, int p_to_node) {
SequenceConnection sc;
sc.from_node = p_from_node;
sc.from_output = p_from_output;
sc.to_node = p_to_node;
- ERR_FAIL_COND(!func.sequence_connections.has(sc));
+ ERR_FAIL_COND(!sequence_connections.has(sc));
- func.sequence_connections.erase(sc);
+ sequence_connections.erase(sc);
}
-bool VisualScript::has_sequence_connection(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), false);
- const Function &func = functions[p_func];
-
+bool VisualScript::has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const {
SequenceConnection sc;
sc.from_node = p_from_node;
sc.from_output = p_from_output;
sc.to_node = p_to_node;
- return func.sequence_connections.has(sc);
+ return sequence_connections.has(sc);
}
-void VisualScript::get_sequence_connection_list(const StringName &p_func, List<SequenceConnection> *r_connection) const {
-
- ERR_FAIL_COND(!functions.has(p_func));
- const Function &func = functions[p_func];
-
- for (const Set<SequenceConnection>::Element *E = func.sequence_connections.front(); E; E = E->next()) {
+void VisualScript::get_sequence_connection_list(List<SequenceConnection> *r_connection) const {
+ for (const Set<SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) {
r_connection->push_back(E->get());
}
}
-void VisualScript::data_connect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
-
+void VisualScript::data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
ERR_FAIL_COND(instances.size());
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
DataConnection dc;
dc.from_node = p_from_node;
@@ -506,76 +397,55 @@ void VisualScript::data_connect(const StringName &p_func, int p_from_node, int p
dc.to_node = p_to_node;
dc.to_port = p_to_port;
- ERR_FAIL_COND(func.data_connections.has(dc));
+ ERR_FAIL_COND(data_connections.has(dc));
- func.data_connections.insert(dc);
+ data_connections.insert(dc);
}
-void VisualScript::data_disconnect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
-
- ERR_FAIL_COND(!functions.has(p_func));
- Function &func = functions[p_func];
-
+void VisualScript::data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
DataConnection dc;
dc.from_node = p_from_node;
dc.from_port = p_from_port;
dc.to_node = p_to_node;
dc.to_port = p_to_port;
- ERR_FAIL_COND(!func.data_connections.has(dc));
+ ERR_FAIL_COND(!data_connections.has(dc));
- func.data_connections.erase(dc);
+ data_connections.erase(dc);
}
-bool VisualScript::has_data_connection(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), false);
- const Function &func = functions[p_func];
-
+bool VisualScript::has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const {
DataConnection dc;
dc.from_node = p_from_node;
dc.from_port = p_from_port;
dc.to_node = p_to_node;
dc.to_port = p_to_port;
- return func.data_connections.has(dc);
+ return data_connections.has(dc);
}
-bool VisualScript::is_input_value_port_connected(const StringName &p_func, int p_node, int p_port) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), false);
- const Function &func = functions[p_func];
-
- for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
- if (E->get().to_node == p_node && E->get().to_port == p_port)
+bool VisualScript::is_input_value_port_connected(int p_node, int p_port) const {
+ for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
+ if (E->get().to_node == p_node && E->get().to_port == p_port) {
return true;
+ }
}
-
return false;
}
-bool VisualScript::get_input_value_port_connection_source(const StringName &p_func, int p_node, int p_port, int *r_node, int *r_port) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func), false);
- const Function &func = functions[p_func];
-
- for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
+bool VisualScript::get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const {
+ for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
if (E->get().to_node == p_node && E->get().to_port == p_port) {
*r_node = E->get().from_node;
*r_port = E->get().from_port;
return true;
}
}
-
return false;
}
-void VisualScript::get_data_connection_list(const StringName &p_func, List<DataConnection> *r_connection) const {
-
- ERR_FAIL_COND(!functions.has(p_func));
- const Function &func = functions[p_func];
-
- for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
+void VisualScript::get_data_connection_list(List<DataConnection> *r_connection) const {
+ for (const Set<DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
r_connection->push_back(E->get());
}
}
@@ -585,7 +455,6 @@ void VisualScript::set_tool_enabled(bool p_enabled) {
}
void VisualScript::add_variable(const StringName &p_name, const Variant &p_default_value, bool p_export) {
-
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(variables.has(p_name));
@@ -605,12 +474,10 @@ void VisualScript::add_variable(const StringName &p_name, const Variant &p_defau
}
bool VisualScript::has_variable(const StringName &p_name) const {
-
return variables.has(p_name);
}
void VisualScript::remove_variable(const StringName &p_name) {
-
ERR_FAIL_COND(!variables.has(p_name));
variables.erase(p_name);
@@ -620,7 +487,6 @@ void VisualScript::remove_variable(const StringName &p_name) {
}
void VisualScript::set_variable_default_value(const StringName &p_name, const Variant &p_value) {
-
ERR_FAIL_COND(!variables.has(p_name));
variables[p_name].default_value = p_value;
@@ -629,13 +495,13 @@ void VisualScript::set_variable_default_value(const StringName &p_name, const Va
_update_placeholders();
#endif
}
-Variant VisualScript::get_variable_default_value(const StringName &p_name) const {
+Variant VisualScript::get_variable_default_value(const StringName &p_name) const {
ERR_FAIL_COND_V(!variables.has(p_name), Variant());
return variables[p_name].default_value;
}
-void VisualScript::set_variable_info(const StringName &p_name, const PropertyInfo &p_info) {
+void VisualScript::set_variable_info(const StringName &p_name, const PropertyInfo &p_info) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!variables.has(p_name));
variables[p_name].info = p_info;
@@ -645,14 +511,13 @@ void VisualScript::set_variable_info(const StringName &p_name, const PropertyInf
_update_placeholders();
#endif
}
-PropertyInfo VisualScript::get_variable_info(const StringName &p_name) const {
+PropertyInfo VisualScript::get_variable_info(const StringName &p_name) const {
ERR_FAIL_COND_V(!variables.has(p_name), PropertyInfo());
return variables[p_name].info;
}
void VisualScript::set_variable_export(const StringName &p_name, bool p_export) {
-
ERR_FAIL_COND(!variables.has(p_name));
variables[p_name]._export = p_export;
@@ -662,30 +527,32 @@ void VisualScript::set_variable_export(const StringName &p_name, bool p_export)
}
bool VisualScript::get_variable_export(const StringName &p_name) const {
-
ERR_FAIL_COND_V(!variables.has(p_name), false);
return variables[p_name]._export;
}
void VisualScript::_set_variable_info(const StringName &p_name, const Dictionary &p_info) {
-
PropertyInfo pinfo;
- if (p_info.has("type"))
+ if (p_info.has("type")) {
pinfo.type = Variant::Type(int(p_info["type"]));
- if (p_info.has("name"))
+ }
+ if (p_info.has("name")) {
pinfo.name = p_info["name"];
- if (p_info.has("hint"))
+ }
+ if (p_info.has("hint")) {
pinfo.hint = PropertyHint(int(p_info["hint"]));
- if (p_info.has("hint_string"))
+ }
+ if (p_info.has("hint_string")) {
pinfo.hint_string = p_info["hint_string"];
- if (p_info.has("usage"))
+ }
+ if (p_info.has("usage")) {
pinfo.usage = p_info["usage"];
+ }
set_variable_info(p_name, pinfo);
}
Dictionary VisualScript::_get_variable_info(const StringName &p_name) const {
-
PropertyInfo pinfo = get_variable_info(p_name);
Dictionary d;
d["type"] = pinfo.type;
@@ -698,26 +565,21 @@ Dictionary VisualScript::_get_variable_info(const StringName &p_name) const {
}
void VisualScript::get_variable_list(List<StringName> *r_variables) const {
-
- for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
- r_variables->push_back(E->key());
- }
-
- r_variables->sort_custom<StringName::AlphCompare>();
+ variables.get_key_list(r_variables);
+ // r_variables->sort_custom<StringName::AlphCompare>(); // Don't force it.
}
void VisualScript::set_instance_base_type(const StringName &p_type) {
-
ERR_FAIL_COND(instances.size());
base_type = p_type;
}
void VisualScript::rename_variable(const StringName &p_name, const StringName &p_new_name) {
-
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!variables.has(p_name));
- if (p_new_name == p_name)
+ if (p_new_name == p_name) {
return;
+ }
ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
@@ -727,22 +589,19 @@ void VisualScript::rename_variable(const StringName &p_name, const StringName &p
variables[p_new_name] = variables[p_name];
variables.erase(p_name);
-
- List<StringName> funcs;
- get_function_list(&funcs);
- for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { // loop through all the functions
- List<int> ids;
- get_node_list(F->get(), &ids);
- for (List<int>::Element *E = ids.front(); E; E = E->next()) {
- Ref<VisualScriptVariableGet> nodeget = get_node(F->get(), E->get());
- if (nodeget.is_valid()) {
- if (nodeget->get_variable() == p_name)
- nodeget->set_variable(p_new_name);
- } else {
- Ref<VisualScriptVariableSet> nodeset = get_node(F->get(), E->get());
- if (nodeset.is_valid()) {
- if (nodeset->get_variable() == p_name)
- nodeset->set_variable(p_new_name);
+ List<int> ids;
+ get_node_list(&ids);
+ for (List<int>::Element *E = ids.front(); E; E = E->next()) {
+ Ref<VisualScriptVariableGet> nodeget = get_node(E->get());
+ if (nodeget.is_valid()) {
+ if (nodeget->get_variable() == p_name) {
+ nodeget->set_variable(p_new_name);
+ }
+ } else {
+ Ref<VisualScriptVariableSet> nodeset = get_node(E->get());
+ if (nodeset.is_valid()) {
+ if (nodeset->get_variable() == p_name) {
+ nodeset->set_variable(p_new_name);
}
}
}
@@ -750,7 +609,6 @@ void VisualScript::rename_variable(const StringName &p_name, const StringName &p
}
void VisualScript::add_custom_signal(const StringName &p_name) {
-
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(custom_signals.has(p_name));
@@ -759,48 +617,49 @@ void VisualScript::add_custom_signal(const StringName &p_name) {
}
bool VisualScript::has_custom_signal(const StringName &p_name) const {
-
return custom_signals.has(p_name);
}
-void VisualScript::custom_signal_add_argument(const StringName &p_func, Variant::Type p_type, const String &p_name, int p_index) {
+void VisualScript::custom_signal_add_argument(const StringName &p_func, Variant::Type p_type, const String &p_name, int p_index) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
Argument arg;
arg.type = p_type;
arg.name = p_name;
- if (p_index < 0)
+ if (p_index < 0) {
custom_signals[p_func].push_back(arg);
- else
+ } else {
custom_signals[p_func].insert(0, arg);
+ }
}
-void VisualScript::custom_signal_set_argument_type(const StringName &p_func, int p_argidx, Variant::Type p_type) {
+void VisualScript::custom_signal_set_argument_type(const StringName &p_func, int p_argidx, Variant::Type p_type) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
custom_signals[p_func].write[p_argidx].type = p_type;
}
-Variant::Type VisualScript::custom_signal_get_argument_type(const StringName &p_func, int p_argidx) const {
+Variant::Type VisualScript::custom_signal_get_argument_type(const StringName &p_func, int p_argidx) const {
ERR_FAIL_COND_V(!custom_signals.has(p_func), Variant::NIL);
ERR_FAIL_INDEX_V(p_argidx, custom_signals[p_func].size(), Variant::NIL);
return custom_signals[p_func][p_argidx].type;
}
+
void VisualScript::custom_signal_set_argument_name(const StringName &p_func, int p_argidx, const String &p_name) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
custom_signals[p_func].write[p_argidx].name = p_name;
}
-String VisualScript::custom_signal_get_argument_name(const StringName &p_func, int p_argidx) const {
+String VisualScript::custom_signal_get_argument_name(const StringName &p_func, int p_argidx) const {
ERR_FAIL_COND_V(!custom_signals.has(p_func), String());
ERR_FAIL_INDEX_V(p_argidx, custom_signals[p_func].size(), String());
return custom_signals[p_func][p_argidx].name;
}
-void VisualScript::custom_signal_remove_argument(const StringName &p_func, int p_argidx) {
+void VisualScript::custom_signal_remove_argument(const StringName &p_func, int p_argidx) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
@@ -808,12 +667,11 @@ void VisualScript::custom_signal_remove_argument(const StringName &p_func, int p
}
int VisualScript::custom_signal_get_argument_count(const StringName &p_func) const {
-
ERR_FAIL_COND_V(!custom_signals.has(p_func), 0);
return custom_signals[p_func].size();
}
-void VisualScript::custom_signal_swap_argument(const StringName &p_func, int p_argidx, int p_with_argidx) {
+void VisualScript::custom_signal_swap_argument(const StringName &p_func, int p_argidx, int p_with_argidx) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
@@ -821,19 +679,19 @@ void VisualScript::custom_signal_swap_argument(const StringName &p_func, int p_a
SWAP(custom_signals[p_func].write[p_argidx], custom_signals[p_func].write[p_with_argidx]);
}
-void VisualScript::remove_custom_signal(const StringName &p_name) {
+void VisualScript::remove_custom_signal(const StringName &p_name) {
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_name));
custom_signals.erase(p_name);
}
void VisualScript::rename_custom_signal(const StringName &p_name, const StringName &p_new_name) {
-
ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_name));
- if (p_new_name == p_name)
+ if (p_new_name == p_name) {
return;
+ }
ERR_FAIL_COND(!String(p_new_name).is_valid_identifier());
@@ -846,7 +704,6 @@ void VisualScript::rename_custom_signal(const StringName &p_name, const StringNa
}
void VisualScript::get_custom_signal_list(List<StringName> *r_custom_signals) const {
-
for (const Map<StringName, Vector<Argument>>::Element *E = custom_signals.front(); E; E = E->next()) {
r_custom_signals->push_back(E->key());
}
@@ -855,61 +712,61 @@ void VisualScript::get_custom_signal_list(List<StringName> *r_custom_signals) co
}
int VisualScript::get_available_id() const {
-
- int max_id = 0;
- for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
- if (E->get().nodes.empty())
- continue;
-
- int last_id = E->get().nodes.back()->key();
- max_id = MAX(max_id, last_id + 1);
+ // This is infinitely increasing,
+ // so one might want to implement a better solution,
+ // if the there is a case for huge number of nodes to be added to visual script.
+ List<int> nds;
+ nodes.get_key_list(&nds);
+ int max = -1;
+ for (const List<int>::Element *E = nds.front(); E; E = E->next()) {
+ if (E->get() > max) {
+ max = E->get();
+ }
}
-
- return max_id;
+ return (max + 1);
}
/////////////////////////////////
bool VisualScript::can_instance() const {
-
- return true; //ScriptServer::is_scripting_enabled();
+ return true; // ScriptServer::is_scripting_enabled();
}
StringName VisualScript::get_instance_base_type() const {
-
return base_type;
}
Ref<Script> VisualScript::get_base_script() const {
- return Ref<Script>(); // no inheritance in visual script
+ return Ref<Script>(); // No inheritance in visual script.
}
#ifdef TOOLS_ENABLED
void VisualScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
-
placeholders.erase(p_placeholder);
}
void VisualScript::_update_placeholders() {
-
- if (placeholders.size() == 0)
- return; //no bother if no placeholders
+ if (placeholders.size() == 0) {
+ return; // No bother if no placeholders.
+ }
List<PropertyInfo> pinfo;
Map<StringName, Variant> values;
- for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
+ List<StringName> keys;
+ variables.get_key_list(&keys);
- if (!E->get()._export)
+ for (List<StringName>::Element *E = keys.front(); E; E = E->next()) {
+ if (!variables[E->get()]._export) {
continue;
+ }
- PropertyInfo p = E->get().info;
- p.name = String(E->key());
+ PropertyInfo p = variables[E->get()].info;
+ p.name = String(E->get());
pinfo.push_back(p);
- values[p.name] = E->get().default_value;
+ values[p.name] = variables[E->get()].default_value;
}
for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
-
E->get()->update(pinfo, values);
}
}
@@ -917,28 +774,27 @@ void VisualScript::_update_placeholders() {
#endif
ScriptInstance *VisualScript::instance_create(Object *p_this) {
-
#ifdef TOOLS_ENABLED
if (!ScriptServer::is_scripting_enabled() && !is_tool_script) {
-
PlaceHolderScriptInstance *sins = memnew(PlaceHolderScriptInstance(VisualScriptLanguage::singleton, Ref<Script>((Script *)this), p_this));
placeholders.insert(sins);
List<PropertyInfo> pinfo;
Map<StringName, Variant> values;
- for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
+ List<StringName> keys;
+ variables.get_key_list(&keys);
- if (!E->get()._export)
+ for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) {
+ if (!variables[E->get()]._export)
continue;
- PropertyInfo p = E->get().info;
- p.name = String(E->key());
+ PropertyInfo p = variables[E->get()].info;
+ p.name = String(E->get());
pinfo.push_back(p);
- values[p.name] = E->get().default_value;
+ values[p.name] = variables[E->get()].default_value;
}
-
sins->update(pinfo, values);
return sins;
@@ -958,17 +814,14 @@ ScriptInstance *VisualScript::instance_create(Object *p_this) {
}
bool VisualScript::instance_has(const Object *p_this) const {
-
return instances.has((Object *)p_this);
}
bool VisualScript::has_source_code() const {
-
return false;
}
String VisualScript::get_source_code() const {
-
return String();
}
@@ -976,33 +829,27 @@ void VisualScript::set_source_code(const String &p_code) {
}
Error VisualScript::reload(bool p_keep_state) {
-
return OK;
}
bool VisualScript::is_tool() const {
-
return is_tool_script;
}
bool VisualScript::is_valid() const {
- return true; //always valid
+ return true; // Always valid.
}
ScriptLanguage *VisualScript::get_language() const {
-
return VisualScriptLanguage::singleton;
}
bool VisualScript::has_script_signal(const StringName &p_signal) const {
-
return custom_signals.has(p_signal);
}
void VisualScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
-
for (const Map<StringName, Vector<Argument>>::Element *E = custom_signals.front(); E; E = E->next()) {
-
MethodInfo mi;
mi.name = E->key();
for (int i = 0; i < E->get().size(); i++) {
@@ -1017,22 +864,23 @@ void VisualScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
}
bool VisualScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
-
- if (!variables.has(p_property))
+ if (!variables.has(p_property)) {
return false;
+ }
r_value = variables[p_property].default_value;
return true;
}
-void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const {
- for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
+void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const {
+ List<StringName> funcs;
+ functions.get_key_list(&funcs);
+ for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) {
MethodInfo mi;
- mi.name = E->key();
- if (E->get().function_id >= 0) {
-
- Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node;
+ mi.name = E->get();
+ if (functions[E->get()].func_id >= 0) {
+ Ref<VisualScriptFunction> func = nodes[functions[E->get()].func_id].node;
if (func.is_valid()) {
for (int i = 0; i < func->get_argument_count(); i++) {
PropertyInfo arg;
@@ -1048,22 +896,20 @@ void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const {
}
bool VisualScript::has_method(const StringName &p_method) const {
-
return functions.has(p_method);
}
-MethodInfo VisualScript::get_method_info(const StringName &p_method) const {
- const Map<StringName, Function>::Element *E = functions.find(p_method);
- if (!E)
+MethodInfo VisualScript::get_method_info(const StringName &p_method) const {
+ const Function funct = functions[p_method];
+ if (funct.func_id == -1) {
return MethodInfo();
+ }
MethodInfo mi;
- mi.name = E->key();
- if (E->get().function_id >= 0) {
-
- Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node;
+ mi.name = p_method;
+ if (funct.func_id >= 0) {
+ Ref<VisualScriptFunction> func = nodes[funct.func_id].node;
if (func.is_valid()) {
-
for (int i = 0; i < func->get_argument_count(); i++) {
PropertyInfo arg;
arg.name = func->get_argument_name(i);
@@ -1081,7 +927,6 @@ MethodInfo VisualScript::get_method_info(const StringName &p_method) const {
}
void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const {
-
List<StringName> vars;
get_variable_list(&vars);
@@ -1095,29 +940,18 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const {
}
int VisualScript::get_member_line(const StringName &p_member) const {
-#ifdef TOOLS_ENABLED
- if (has_function(p_member)) {
- for (Map<int, Function::NodeData>::Element *E = functions[p_member].nodes.front(); E; E = E->next()) {
- if (Object::cast_to<VisualScriptFunction>(E->get().node.ptr()))
- return E->key();
- }
- }
-#endif
- return -1;
+ return functions[p_member].func_id; // will be -1 if not found
}
#ifdef TOOLS_ENABLED
bool VisualScript::are_subnodes_edited() const {
-
- for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
-
- for (const Map<int, Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
- if (F->get().node->is_edited()) {
- return true;
- }
+ List<int> keys;
+ nodes.get_key_list(&keys);
+ for (const List<int>::Element *F = keys.front(); F; F = F->next()) {
+ if (nodes[F->get()].node->is_edited()) {
+ return true;
}
}
-
return false;
}
#endif
@@ -1177,15 +1011,14 @@ MultiplayerAPI::RPCMode VisualScript::get_rset_mode(const StringName &p_variable
}
void VisualScript::_set_data(const Dictionary &p_data) {
-
Dictionary d = p_data;
- if (d.has("base_type"))
+ if (d.has("base_type")) {
base_type = d["base_type"];
+ }
variables.clear();
Array vars = d["variables"];
for (int i = 0; i < vars.size(); i++) {
-
Dictionary v = vars[i];
StringName name = v["name"];
add_variable(name);
@@ -1197,7 +1030,6 @@ void VisualScript::_set_data(const Dictionary &p_data) {
custom_signals.clear();
Array sigs = d["signals"];
for (int i = 0; i < sigs.size(); i++) {
-
Dictionary cs = sigs[i];
add_custom_signal(cs["name"]);
@@ -1210,87 +1042,41 @@ void VisualScript::_set_data(const Dictionary &p_data) {
Array funcs = d["functions"];
functions.clear();
- Vector2 last_pos = Vector2(-100 * funcs.size(), -100 * funcs.size()); // this is the center of the last fn box
- Vector2 last_size = Vector2(0.0, 0.0);
-
for (int i = 0; i < funcs.size(); i++) {
-
Dictionary func = funcs[i];
-
- StringName name = func["name"];
- //int id=func["function_id"];
- add_function(name);
-
- set_function_scroll(name, func["scroll"]);
-
- Array nodes = func["nodes"];
-
- if (!d.has("vs_unify") && nodes.size() > 0) {
- Vector2 top_left = nodes[1];
- Vector2 bottom_right = nodes[1];
-
- for (int j = 0; j < nodes.size(); j += 3) {
- Point2 pos = nodes[j + 1];
- if (pos.y > top_left.y) {
- top_left.y = pos.y;
- }
- if (pos.y < bottom_right.y) {
- bottom_right.y = pos.y;
- }
- if (pos.x > bottom_right.x) {
- bottom_right.x = pos.x;
- }
- if (pos.x < top_left.x) {
- top_left.x = pos.x;
- }
- }
-
- Vector2 size = Vector2(bottom_right.x - top_left.x, top_left.y - bottom_right.y);
-
- Vector2 offset = last_pos + (last_size / 2.0) + (size / 2.0); // dunno I might just keep it in one axis but diagonal feels better....
-
- last_pos = offset;
- last_size = size;
-
- for (int j = 0; j < nodes.size(); j += 3) {
- add_node(name, nodes[j], nodes[j + 2], offset + nodes[j + 1]); // also add an additional buffer if you want to
- }
-
- } else {
- for (int j = 0; j < nodes.size(); j += 3) {
- add_node(name, nodes[j], nodes[j + 2], nodes[j + 1]);
- }
+ add_function(func["name"], func["function_id"]);
+ }
+ {
+ Array nodes = d["nodes"];
+ for (int i = 0; i < nodes.size(); i += 3) {
+ add_node(nodes[i], nodes[i + 2], nodes[i + 1]);
}
- Array sequence_connections = func["sequence_connections"];
+ Array sequence_connections = d["sequence_connections"];
for (int j = 0; j < sequence_connections.size(); j += 3) {
-
- sequence_connect(name, sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]);
+ sequence_connect(sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]);
}
- Array data_connections = func["data_connections"];
-
+ Array data_connections = d["data_connections"];
for (int j = 0; j < data_connections.size(); j += 4) {
-
- data_connect(name, data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]);
+ data_connect(data_connections[j + 0], data_connections[j + 1], data_connections[j + 2], data_connections[j + 3]);
}
}
+ is_tool_script = d["is_tool_script"];
+ scroll = d["scroll"];
- if (d.has("is_tool_script"))
- is_tool_script = d["is_tool_script"];
- else
- is_tool_script = false;
-
- // Takes all the rpc methods
+ // Takes all the rpc methods.
rpc_functions.clear();
rpc_variables.clear();
- for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
- if (E->get().function_id >= 0 && E->get().nodes.find(E->get().function_id)) {
- Ref<VisualScriptFunction> vsf = E->get().nodes[E->get().function_id].node;
+ List<StringName> fns;
+ functions.get_key_list(&fns);
+ for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) {
+ if (functions[E->get()].func_id >= 0 && nodes.has(functions[E->get()].func_id)) {
+ Ref<VisualScriptFunction> vsf = nodes[functions[E->get()].func_id].node;
if (vsf.is_valid()) {
if (vsf->get_rpc_mode() != MultiplayerAPI::RPC_MODE_DISABLED) {
ScriptNetData nd;
- nd.name = E->key();
+ nd.name = E->get();
nd.mode = vsf->get_rpc_mode();
if (rpc_functions.find(nd) == -1) {
rpc_functions.push_back(nd);
@@ -1300,30 +1086,28 @@ void VisualScript::_set_data(const Dictionary &p_data) {
}
}
- // Visual script doesn't have rset :(
-
// Sort so we are 100% that they are always the same.
rpc_functions.sort_custom<SortNetData>();
}
Dictionary VisualScript::_get_data() const {
-
Dictionary d;
d["base_type"] = base_type;
- Array vars;
- for (const Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
- Dictionary var = _get_variable_info(E->key());
- var["name"] = E->key(); //make sure it's the right one
- var["default_value"] = E->get().default_value;
- var["export"] = E->get()._export;
+ Array vars;
+ List<StringName> var_names;
+ variables.get_key_list(&var_names);
+ for (const List<StringName>::Element *E = var_names.front(); E; E = E->next()) {
+ Dictionary var = _get_variable_info(E->get());
+ var["name"] = E->get(); // Make sure it's the right one.
+ var["default_value"] = variables[E->get()].default_value;
+ var["export"] = variables[E->get()]._export;
vars.push_back(var);
}
d["variables"] = vars;
Array sigs;
for (const Map<StringName, Vector<Argument>>::Element *E = custom_signals.front(); E; E = E->next()) {
-
Dictionary cs;
cs["name"] = E->key();
Array args;
@@ -1339,83 +1123,73 @@ Dictionary VisualScript::_get_data() const {
d["signals"] = sigs;
Array funcs;
-
- for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
-
+ List<StringName> func_names;
+ functions.get_key_list(&func_names);
+ for (const List<StringName>::Element *E = func_names.front(); E; E = E->next()) {
Dictionary func;
- func["name"] = E->key();
- func["function_id"] = E->get().function_id;
- func["scroll"] = E->get().scroll;
-
- Array nodes;
-
- for (const Map<int, Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
-
- nodes.push_back(F->key());
- nodes.push_back(F->get().pos);
- nodes.push_back(F->get().node);
- }
-
- func["nodes"] = nodes;
-
- Array sequence_connections;
-
- for (const Set<SequenceConnection>::Element *F = E->get().sequence_connections.front(); F; F = F->next()) {
-
- sequence_connections.push_back(F->get().from_node);
- sequence_connections.push_back(F->get().from_output);
- sequence_connections.push_back(F->get().to_node);
- }
-
- func["sequence_connections"] = sequence_connections;
-
- Array data_connections;
-
- for (const Set<DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) {
+ func["name"] = E->get();
+ func["function_id"] = functions[E->get()].func_id;
+ funcs.push_back(func);
+ }
+ d["functions"] = funcs;
- data_connections.push_back(F->get().from_node);
- data_connections.push_back(F->get().from_port);
- data_connections.push_back(F->get().to_node);
- data_connections.push_back(F->get().to_port);
- }
+ Array nds;
+ List<int> node_ids;
+ nodes.get_key_list(&node_ids);
+ for (const List<int>::Element *F = node_ids.front(); F; F = F->next()) {
+ nds.push_back(F->get());
+ nds.push_back(nodes[F->get()].pos);
+ nds.push_back(nodes[F->get()].node);
+ }
+ d["nodes"] = nds;
- func["data_connections"] = data_connections;
+ Array seqconns;
+ for (const Set<SequenceConnection>::Element *F = sequence_connections.front(); F; F = F->next()) {
+ seqconns.push_back(F->get().from_node);
+ seqconns.push_back(F->get().from_output);
+ seqconns.push_back(F->get().to_node);
+ }
+ d["sequence_connections"] = seqconns;
- funcs.push_back(func);
+ Array dataconns;
+ for (const Set<DataConnection>::Element *F = data_connections.front(); F; F = F->next()) {
+ dataconns.push_back(F->get().from_node);
+ dataconns.push_back(F->get().from_port);
+ dataconns.push_back(F->get().to_node);
+ dataconns.push_back(F->get().to_port);
}
+ d["data_connections"] = dataconns;
- d["functions"] = funcs;
d["is_tool_script"] = is_tool_script;
- d["vs_unify"] = true;
+ d["scroll"] = scroll;
return d;
}
void VisualScript::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("add_function", "name"), &VisualScript::add_function);
+ ClassDB::bind_method(D_METHOD("add_function", "name", "func_node_id"), &VisualScript::add_function);
ClassDB::bind_method(D_METHOD("has_function", "name"), &VisualScript::has_function);
ClassDB::bind_method(D_METHOD("remove_function", "name"), &VisualScript::remove_function);
ClassDB::bind_method(D_METHOD("rename_function", "name", "new_name"), &VisualScript::rename_function);
- ClassDB::bind_method(D_METHOD("set_function_scroll", "name", "ofs"), &VisualScript::set_function_scroll);
- ClassDB::bind_method(D_METHOD("get_function_scroll", "name"), &VisualScript::get_function_scroll);
+ ClassDB::bind_method(D_METHOD("set_scroll", "ofs"), &VisualScript::set_scroll);
+ ClassDB::bind_method(D_METHOD("get_scroll"), &VisualScript::get_scroll);
- ClassDB::bind_method(D_METHOD("add_node", "func", "id", "node", "position"), &VisualScript::add_node, DEFVAL(Point2()));
- ClassDB::bind_method(D_METHOD("remove_node", "func", "id"), &VisualScript::remove_node);
+ ClassDB::bind_method(D_METHOD("add_node", "id", "node", "position"), &VisualScript::add_node, DEFVAL(Point2()));
+ ClassDB::bind_method(D_METHOD("remove_node", "id"), &VisualScript::remove_node);
ClassDB::bind_method(D_METHOD("get_function_node_id", "name"), &VisualScript::get_function_node_id);
- ClassDB::bind_method(D_METHOD("get_node", "func", "id"), &VisualScript::get_node);
- ClassDB::bind_method(D_METHOD("has_node", "func", "id"), &VisualScript::has_node);
- ClassDB::bind_method(D_METHOD("set_node_position", "func", "id", "position"), &VisualScript::set_node_position);
- ClassDB::bind_method(D_METHOD("get_node_position", "func", "id"), &VisualScript::get_node_position);
+ ClassDB::bind_method(D_METHOD("get_node", "id"), &VisualScript::get_node);
+ ClassDB::bind_method(D_METHOD("has_node", "id"), &VisualScript::has_node);
+ ClassDB::bind_method(D_METHOD("set_node_position", "id", "position"), &VisualScript::set_node_position);
+ ClassDB::bind_method(D_METHOD("get_node_position", "id"), &VisualScript::get_node_position);
- ClassDB::bind_method(D_METHOD("sequence_connect", "func", "from_node", "from_output", "to_node"), &VisualScript::sequence_connect);
- ClassDB::bind_method(D_METHOD("sequence_disconnect", "func", "from_node", "from_output", "to_node"), &VisualScript::sequence_disconnect);
- ClassDB::bind_method(D_METHOD("has_sequence_connection", "func", "from_node", "from_output", "to_node"), &VisualScript::has_sequence_connection);
+ ClassDB::bind_method(D_METHOD("sequence_connect", "from_node", "from_output", "to_node"), &VisualScript::sequence_connect);
+ ClassDB::bind_method(D_METHOD("sequence_disconnect", "from_node", "from_output", "to_node"), &VisualScript::sequence_disconnect);
+ ClassDB::bind_method(D_METHOD("has_sequence_connection", "from_node", "from_output", "to_node"), &VisualScript::has_sequence_connection);
- ClassDB::bind_method(D_METHOD("data_connect", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_connect);
- ClassDB::bind_method(D_METHOD("data_disconnect", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_disconnect);
- ClassDB::bind_method(D_METHOD("has_data_connection", "func", "from_node", "from_port", "to_node", "to_port"), &VisualScript::has_data_connection);
+ ClassDB::bind_method(D_METHOD("data_connect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_connect);
+ ClassDB::bind_method(D_METHOD("data_disconnect", "from_node", "from_port", "to_node", "to_port"), &VisualScript::data_disconnect);
+ ClassDB::bind_method(D_METHOD("has_data_connection", "from_node", "from_port", "to_node", "to_port"), &VisualScript::has_data_connection);
ClassDB::bind_method(D_METHOD("add_variable", "name", "default_value", "export"), &VisualScript::add_variable, DEFVAL(Variant()), DEFVAL(false));
ClassDB::bind_method(D_METHOD("has_variable", "name"), &VisualScript::has_variable);
@@ -1451,26 +1225,21 @@ void VisualScript::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
- ADD_SIGNAL(MethodInfo("node_ports_changed", PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("node_ports_changed", PropertyInfo(Variant::INT, "id")));
}
VisualScript::VisualScript() {
-
base_type = "Object";
is_tool_script = false;
}
bool VisualScript::inherits_script(const Ref<Script> &p_script) const {
- return this == p_script.ptr(); //there is no inheritance in visual scripts, so this is enough
+ return this == p_script.ptr(); // There is no inheritance in visual scripts, so this is enough.
}
-StringName VisualScript::get_default_func() const {
- return StringName("f_312843592");
-}
-
-Set<int> VisualScript::get_output_sequence_ports_connected(const String &edited_func, int from_node) {
+Set<int> VisualScript::get_output_sequence_ports_connected(int from_node) {
List<VisualScript::SequenceConnection> *sc = memnew(List<VisualScript::SequenceConnection>);
- get_sequence_connection_list(edited_func, sc);
+ get_sequence_connection_list(sc);
Set<int> connected;
for (List<VisualScript::SequenceConnection>::Element *E = sc->front(); E; E = E->next()) {
if (E->get().from_node == from_node) {
@@ -1482,19 +1251,21 @@ Set<int> VisualScript::get_output_sequence_ports_connected(const String &edited_
}
VisualScript::~VisualScript() {
-
- while (!functions.empty()) {
- remove_function(functions.front()->key());
+ // Remove all nodes and stuff that hold data refs.
+ List<int> nds;
+ nodes.get_key_list(&nds);
+ for (const List<int>::Element *E = nds.front(); E; E = E->next()) {
+ remove_node(E->get());
}
}
////////////////////////////////////////////
bool VisualScriptInstance::set(const StringName &p_name, const Variant &p_value) {
-
Map<StringName, Variant>::Element *E = variables.find(p_name);
- if (!E)
+ if (!E) {
return false;
+ }
E->get() = p_value;
@@ -1502,56 +1273,53 @@ bool VisualScriptInstance::set(const StringName &p_name, const Variant &p_value)
}
bool VisualScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
-
const Map<StringName, Variant>::Element *E = variables.find(p_name);
- if (!E)
+ if (!E) {
return false;
+ }
r_ret = E->get();
return true;
}
-void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
-
- for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) {
- if (!E->get()._export)
+void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
+ List<StringName> vars;
+ script->variables.get_key_list(&vars);
+ for (const List<StringName>::Element *E = vars.front(); E; E = E->next()) {
+ if (!script->variables[E->get()]._export) {
continue;
- PropertyInfo p = E->get().info;
- p.name = String(E->key());
+ }
+ PropertyInfo p = script->variables[E->get()].info;
+ p.name = String(E->get());
p.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
p_properties->push_back(p);
}
}
-Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
- const Map<StringName, VisualScript::Variable>::Element *E = script->variables.find(p_name);
- if (!E) {
- if (r_is_valid)
+Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
+ if (!script->variables.has(p_name)) {
+ if (r_is_valid) {
*r_is_valid = false;
+ }
ERR_FAIL_V(Variant::NIL);
}
- if (r_is_valid)
+ if (r_is_valid) {
*r_is_valid = true;
+ }
- return E->get().info.type;
+ return script->variables[p_name].info.type;
}
void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
-
- for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) {
-
- if (E->key() == script->get_default_func()) {
- continue;
- }
-
+ List<StringName> fns;
+ script->functions.get_key_list(&fns);
+ for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) {
MethodInfo mi;
- mi.name = E->key();
- if (E->get().function_id >= 0 && E->get().nodes.has(E->get().function_id)) {
-
- Ref<VisualScriptFunction> vsf = E->get().nodes[E->get().function_id].node;
+ mi.name = E->get();
+ if (script->functions[E->get()].func_id >= 0 && script->nodes.has(script->functions[E->get()].func_id)) {
+ Ref<VisualScriptFunction> vsf = script->nodes[script->functions[E->get()].func_id].node;
if (vsf.is_valid()) {
-
for (int i = 0; i < vsf->get_argument_count(); i++) {
PropertyInfo arg;
arg.name = vsf->get_argument_name(i);
@@ -1560,20 +1328,16 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
mi.arguments.push_back(arg);
}
- if (!vsf->is_sequenced()) { //assumed constant if not sequenced
+ if (!vsf->is_sequenced()) { // Assumed constant if not sequenced.
mi.flags |= METHOD_FLAG_CONST;
}
}
}
-
p_list->push_back(mi);
}
}
-bool VisualScriptInstance::has_method(const StringName &p_method) const {
-
- if (p_method == script->get_default_func())
- return false;
+bool VisualScriptInstance::has_method(const StringName &p_method) const {
return script->functions.has(p_method);
}
@@ -1581,36 +1345,34 @@ bool VisualScriptInstance::has_method(const StringName &p_method) const {
#define VSDEBUG(m_text)
void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Callable::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node) {
-
ERR_FAIL_COND(node->pass_idx == -1);
- if (pass_stack[node->pass_idx] == p_pass)
+ if (pass_stack[node->pass_idx] == p_pass) {
return;
+ }
pass_stack[node->pass_idx] = p_pass;
- if (!node->dependencies.empty()) {
-
+ if (!node->dependencies.is_empty()) {
int dc = node->dependencies.size();
VisualScriptNodeInstance **deps = node->dependencies.ptrw();
for (int i = 0; i < dc; i++) {
-
_dependency_step(deps[i], p_pass, pass_stack, input_args, output_args, variant_stack, r_error, error_str, r_error_node);
- if (r_error.error != Callable::CallError::CALL_OK)
+ if (r_error.error != Callable::CallError::CALL_OK) {
return;
+ }
}
}
for (int i = 0; i < node->input_port_count; i++) {
-
int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK;
if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
- //is a default value (unassigned input port)
+ // Is a default value (unassigned input port).
input_args[i] = &default_values[index];
} else {
- //regular temporary in stack
+ // Rregular temporary in stack.
input_args[i] = &variant_stack[index];
}
}
@@ -1621,19 +1383,18 @@ void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int
Variant *working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr;
node->step(input_args, output_args, VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE, working_mem, r_error, error_str);
- //ignore return
+ // Ignore return.
if (r_error.error != Callable::CallError::CALL_OK) {
*r_error_node = node;
}
}
Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p_stack, int p_stack_size, VisualScriptNodeInstance *p_node, int p_flow_stack_pos, int p_pass, bool p_resuming_yield, Callable::CallError &r_error) {
-
Map<StringName, Function>::Element *F = functions.find(p_method);
ERR_FAIL_COND_V(!F, Variant());
Function *f = &F->get();
- //this call goes separate, so it can e yielded and suspended
+ // This call goes separate, so it can e yielded and suspended.
Variant *variant_stack = (Variant *)p_stack;
bool *sequence_bits = (bool *)(variant_stack + f->max_stack);
const Variant **input_args = (const Variant **)(sequence_bits + f->node_count);
@@ -1659,35 +1420,31 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
#endif
while (true) {
-
- p_pass++; //increment pass
+ p_pass++; // Increment pass.
current_node_id = node->get_id();
VSDEBUG("==========AT NODE: " + itos(current_node_id) + " base: " + node->get_base_node()->get_class_name());
VSDEBUG("AT STACK POS: " + itos(flow_stack_pos));
- //setup working mem
+ // Setup working mem.
working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)nullptr;
VSDEBUG("WORKING MEM: " + itos(node->working_mem_idx));
if (current_node_id == f->node) {
- //if function node, set up function arguments from beginning of stack
+ // If function node, set up function arguments from beginning of stack.
for (int i = 0; i < f->argument_count; i++) {
input_args[i] = &variant_stack[i];
}
} else {
+ // Run dependencies first.
- //run dependencies first
-
- if (!node->dependencies.empty()) {
-
+ if (!node->dependencies.is_empty()) {
int dc = node->dependencies.size();
VisualScriptNodeInstance **deps = node->dependencies.ptrw();
for (int i = 0; i < dc; i++) {
-
_dependency_step(deps[i], p_pass, pass_stack, input_args, output_args, variant_stack, r_error, error_str, &node);
if (r_error.error != Callable::CallError::CALL_OK) {
error = true;
@@ -1698,20 +1455,18 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
if (!error) {
-
- //setup input pointers normally
+ // Setup input pointers normally.
VSDEBUG("INPUT PORTS: " + itos(node->input_port_count));
for (int i = 0; i < node->input_port_count; i++) {
-
int index = node->input_ports[i] & VisualScriptNodeInstance::INPUT_MASK;
if (node->input_ports[i] & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
- //is a default value (unassigned input port)
+ // Is a default value (unassigned input port).
input_args[i] = &default_values[index];
VSDEBUG("\tPORT " + itos(i) + " DEFAULT VAL");
} else {
- //regular temporary in stack
+ // Regular temporary in stack.
input_args[i] = &variant_stack[index];
VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(index));
}
@@ -1719,10 +1474,11 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
}
- if (error)
+ if (error) {
break;
+ }
- //setup output pointers
+ // Setup output pointers.
VSDEBUG("OUTPUT PORTS: " + itos(node->output_port_count));
for (int i = 0; i < node->output_port_count; i++) {
@@ -1730,15 +1486,15 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(node->output_ports[i]));
}
- //do step
+ // Do step.
VisualScriptNodeInstance::StartMode start_mode;
{
if (p_resuming_yield) {
start_mode = VisualScriptNodeInstance::START_MODE_RESUME_YIELD;
- p_resuming_yield = false; // should resume only the first time
+ p_resuming_yield = false; // Should resume only the first time.
} else if (flow_stack && (flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT)) {
- //if there is a push bit, it means we are continuing a sequence
+ // If there is a push bit, it means we are continuing a sequence.
start_mode = VisualScriptNodeInstance::START_MODE_CONTINUE_SEQUENCE;
} else {
start_mode = VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE;
@@ -1750,13 +1506,13 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
int ret = node->step(input_args, output_args, start_mode, working_mem, r_error, error_str);
if (r_error.error != Callable::CallError::CALL_OK) {
- //use error from step
+ // Use error from step.
error = true;
break;
}
if (ret & VisualScriptNodeInstance::STEP_YIELD_BIT) {
- //yielded!
+ // Yielded!
if (node->get_working_memory_size() == 0) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("A node yielded without working memory, please read the docs on how to yield properly!");
@@ -1766,14 +1522,13 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
} else {
Ref<VisualScriptFunctionState> state = *working_mem;
if (!state.is_valid()) {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("Node yielded, but did not return a function state in the first working memory.");
error = true;
break;
}
- //step 1, capture all state
+ // Step 1, capture all state.
state->instance_id = get_owner_ptr()->get_instance_id();
state->script_id = get_script()->get_instance_id();
state->instance = this;
@@ -1785,11 +1540,11 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
state->stack.resize(p_stack_size);
state->pass = p_pass;
copymem(state->stack.ptrw(), p_stack, p_stack_size);
- //step 2, run away, return directly
+ // Step 2, run away, return directly.
r_error.error = Callable::CallError::CALL_OK;
#ifdef DEBUG_ENABLED
- //will re-enter later, so exiting
+ // Will re-enter later, so exiting.
if (EngineDebugger::is_active()) {
VisualScriptLanguage::singleton->exit_function();
}
@@ -1805,15 +1560,17 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
bool do_break = false;
if (EngineDebugger::get_script_debugger()->get_lines_left() > 0) {
-
- if (EngineDebugger::get_script_debugger()->get_depth() <= 0)
+ if (EngineDebugger::get_script_debugger()->get_depth() <= 0) {
EngineDebugger::get_script_debugger()->set_lines_left(EngineDebugger::get_script_debugger()->get_lines_left() - 1);
- if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0)
+ }
+ if (EngineDebugger::get_script_debugger()->get_lines_left() <= 0) {
do_break = true;
+ }
}
- if (EngineDebugger::get_script_debugger()->is_breakpoint(current_node_id, source))
+ if (EngineDebugger::get_script_debugger()->is_breakpoint(current_node_id, source)) {
do_break = true;
+ }
if (do_break) {
VisualScriptLanguage::singleton->debug_break("Breakpoint", true);
@@ -1828,23 +1585,22 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
if (ret & VisualScriptNodeInstance::STEP_EXIT_FUNCTION_BIT) {
if (node->get_working_memory_size() == 0) {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("Return value must be assigned to first element of node working memory! Fix your node please.");
error = true;
} else {
- //assign from working memory, first element
+ // Assign from working memory, first element.
return_value = *working_mem;
}
VSDEBUG("EXITING FUNCTION - VALUE " + String(return_value));
- break; //exit function requested, bye
+ break; // Exit function requested, bye
}
- VisualScriptNodeInstance *next = nullptr; //next node
+ VisualScriptNodeInstance *next = nullptr; // Next node.
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 no exit bit was set, and has sequence outputs, guess next node.
if (output >= node->sequence_output_count) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("Node returned an invalid sequence output: ") + itos(output);
@@ -1853,31 +1609,25 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
next = node->sequence_outputs[output];
- if (next) {
- VSDEBUG("GOT NEXT NODE - " + itos(next->get_id()));
- } else {
- VSDEBUG("GOT NEXT NODE - NULL");
- }
+ VSDEBUG("GOT NEXT NODE - " + (next ? itos(next->get_id()) : "NULL"));
}
if (flow_stack) {
-
- //update flow stack pos (may have changed)
+ // Update flow stack pos (may have changed).
flow_stack[flow_stack_pos] = current_node_id;
- //add stack push bit if requested
+ // Add stack push bit if requested.
if (ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) {
-
flow_stack[flow_stack_pos] |= VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT;
- sequence_bits[node->sequence_index] = true; //remember sequence bit
+ sequence_bits[node->sequence_index] = true; // Remember sequence bit.
VSDEBUG("NEXT SEQ - FLAG BIT");
} else {
- sequence_bits[node->sequence_index] = false; //forget sequence bit
+ sequence_bits[node->sequence_index] = false; // Forget sequence bit.
VSDEBUG("NEXT SEQ - NORMAL");
}
if (ret & VisualScriptNodeInstance::STEP_FLAG_GO_BACK_BIT) {
- //go back request
+ // Go back request.
if (flow_stack_pos > 0) {
flow_stack_pos--;
@@ -1885,22 +1635,20 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
VSDEBUG("NEXT IS GO BACK");
} else {
VSDEBUG("NEXT IS GO BACK, BUT NO NEXT SO EXIT");
- break; //simply exit without value or error
+ break; // Simply exit without value or error.
}
} else if (next) {
-
if (sequence_bits[next->sequence_index]) {
- // what happened here is that we are entering a node that is in the middle of doing a sequence (pushed stack) from the front
+ // What happened here is that we are entering a node that is in the middle of doing a sequence (pushed stack) from the front
// because each node has a working memory, we can't really do a sub-sequence
// as a result, the sequence will be restarted and the stack will roll back to find where this node
- // started the sequence
+ // started the sequence.
bool found = false;
for (int i = flow_stack_pos; i >= 0; i--) {
-
if ((flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK) == next->get_id()) {
- flow_stack_pos = i; //roll back and remove bit
+ flow_stack_pos = i; // Roll back and remove bit.
flow_stack[i] = next->get_id();
sequence_bits[next->sequence_index] = false;
found = true;
@@ -1918,7 +1666,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
VSDEBUG("RE-ENTERED A LOOP, RETURNED STACK POS TO - " + itos(flow_stack_pos));
} else {
- // check for stack overflow
+ // Check for stack overflow.
if (flow_stack_pos + 1 >= flow_max) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("Stack overflow with stack depth: ") + itos(output);
@@ -1935,15 +1683,13 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
} else {
- //no next node, try to go back in stack to pushed bit
+ // No next node, try to go back in stack to pushed bit.
bool found = false;
for (int i = flow_stack_pos; i >= 0; i--) {
-
VSDEBUG("FS " + itos(i) + " - " + itos(flow_stack[i]));
if (flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_PUSHED_BIT) {
-
node = instances[flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK];
flow_stack_pos = i;
found = true;
@@ -1953,27 +1699,24 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
if (!found) {
VSDEBUG("NO NEXT NODE, NO GO BACK, EXITING");
- break; //done, couldn't find a push stack bit
+ break; // Done, couldn't find a push stack bit.
}
VSDEBUG("NO NEXT NODE, GO BACK TO: " + itos(flow_stack_pos));
}
} else {
-
- node = next; //stackless mode, simply assign next node
+ node = next; // Stackless mode, simply assign next node.
}
}
if (error) {
-
- //error
- // function, file, line, error, explanation
+ // Error
+ // Function, file, line, error, explanation.
String err_file = script->get_path();
String err_func = p_method;
- int err_line = current_node_id; //not a line but it works as one
+ int err_line = current_node_id; // Not a line but it works as one.
if (node && (r_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD || error_str == String())) {
-
if (error_str != String()) {
error_str += " ";
}
@@ -1996,13 +1739,11 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
// debugger break did not happen
if (!VisualScriptLanguage::singleton->debug_break(error_str, false)) {
-
_err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, error_str.utf8().get_data(), ERR_HANDLER_SCRIPT);
}
//}
} else {
-
//return_value=
}
@@ -2012,7 +1753,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
#endif
- //clean up variant stack
+ // Clean up variant stack.
for (int i = 0; i < f->max_stack; i++) {
variant_stack[i].~Variant();
}
@@ -2021,7 +1762,6 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
}
Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
r_error.error = Callable::CallError::CALL_OK; //ok by default
Map<StringName, Function>::Element *F = functions.find(p_method);
@@ -2061,7 +1801,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p
int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)nullptr;
for (int i = 0; i < f->node_count; i++) {
- sequence_bits[i] = false; //all starts as false
+ sequence_bits[i] = false; // All starts as false.
}
zeromem(pass_stack, f->pass_stack_size * sizeof(int));
@@ -2095,12 +1835,12 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p
return Variant();
}
- //allocate variant stack
+ // Allocate variant stack.
for (int i = 0; i < f->max_stack; i++) {
memnew_placement(&variant_stack[i], Variant);
}
- //allocate function arguments (must be copied for yield to work properly)
+ // Allocate function arguments (must be copied for yield to work properly).
for (int i = 0; i < p_argcount; i++) {
variant_stack[i] = *p_args[i];
}
@@ -2109,13 +1849,12 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p
}
void VisualScriptInstance::notification(int p_notification) {
-
- //do nothing as this is called using virtual
+ // Do nothing as this is called using virtual.
Variant what = p_notification;
const Variant *whatp = &what;
Callable::CallError ce;
- call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); //do as call
+ call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); // Do as call.
}
String VisualScriptInstance::to_string(bool *r_valid) {
@@ -2124,22 +1863,24 @@ String VisualScriptInstance::to_string(bool *r_valid) {
Variant ret = call(CoreStringNames::get_singleton()->_to_string, nullptr, 0, ce);
if (ce.error == Callable::CallError::CALL_OK) {
if (ret.get_type() != Variant::STRING) {
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
ERR_FAIL_V_MSG(String(), "Wrong type for " + CoreStringNames::get_singleton()->_to_string + ", must be a String.");
}
- if (r_valid)
+ if (r_valid) {
*r_valid = true;
+ }
return ret.operator String();
}
}
- if (r_valid)
+ if (r_valid) {
*r_valid = false;
+ }
return String();
}
Ref<Script> VisualScriptInstance::get_script() const {
-
return script;
}
@@ -2184,7 +1925,6 @@ MultiplayerAPI::RPCMode VisualScriptInstance::get_rset_mode(const StringName &p_
}
void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_owner) {
-
script = p_script;
owner = p_owner;
source = p_script->get_path();
@@ -2193,216 +1933,259 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o
max_output_args = 0;
if (Object::cast_to<Node>(p_owner)) {
- //turn on these if they exist and base is a node
+ // Turn on these if they exist and base is a node.
Node *node = Object::cast_to<Node>(p_owner);
- if (p_script->functions.has("_process"))
+ if (p_script->functions.has("_process")) {
node->set_process(true);
- if (p_script->functions.has("_physics_process"))
+ }
+ if (p_script->functions.has("_physics_process")) {
node->set_physics_process(true);
- if (p_script->functions.has("_input"))
+ }
+ if (p_script->functions.has("_input")) {
node->set_process_input(true);
- if (p_script->functions.has("_unhandled_input"))
+ }
+ if (p_script->functions.has("_unhandled_input")) {
node->set_process_unhandled_input(true);
- if (p_script->functions.has("_unhandled_key_input"))
+ }
+ if (p_script->functions.has("_unhandled_key_input")) {
node->set_process_unhandled_key_input(true);
- }
-
- for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) {
- variables[E->key()] = E->get().default_value;
- }
-
- for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) {
-
- if (E->key() == script->get_default_func()) {
- continue;
}
+ }
- Function function;
- function.node = E->get().function_id;
- function.max_stack = 0;
- function.flow_stack_size = 0;
- function.pass_stack_size = 0;
- function.node_count = 0;
-
- Map<StringName, int> local_var_indices;
-
- if (function.node < 0) {
- VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E->key()));
-
- ERR_CONTINUE(function.node < 0);
+ // Setup variables.
+ {
+ List<StringName> keys;
+ script->variables.get_key_list(&keys);
+ for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) {
+ variables[E->get()] = script->variables[E->get()].default_value;
}
+ }
- {
- Ref<VisualScriptFunction> func_node = script->get_node(E->key(), E->get().function_id);
-
- if (func_node.is_null()) {
- VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->key()));
+ // Setup functions from sequence trees.
+ {
+ List<StringName> keys;
+ script->functions.get_key_list(&keys);
+ for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) {
+ const VisualScript::Function vsfn = p_script->functions[E->get()];
+ Function function;
+ function.node = vsfn.func_id;
+ function.max_stack = 0;
+ function.flow_stack_size = 0;
+ function.pass_stack_size = 0;
+ function.node_count = 0;
+
+ Map<StringName, int> local_var_indices;
+
+ if (function.node < 0) {
+ VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E->get()));
+ ERR_CONTINUE(function.node < 0);
}
- ERR_CONTINUE(!func_node.is_valid());
-
- function.argument_count = func_node->get_argument_count();
- function.max_stack += function.argument_count;
- function.flow_stack_size = func_node->is_stack_less() ? 0 : func_node->get_stack_size();
- max_input_args = MAX(max_input_args, function.argument_count);
- }
-
- //multiple passes are required to set up this complex thing..
+ {
+ Ref<VisualScriptFunction> func_node = script->get_node(vsfn.func_id);
- //first create the nodes
- for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
-
- Ref<VisualScriptNode> node = F->get().node;
-
- VisualScriptNodeInstance *instance = node->instance(this); //create instance
- ERR_FAIL_COND(!instance);
-
- instance->base = node.ptr();
-
- instance->id = F->key();
- instance->input_port_count = node->get_input_value_port_count();
- instance->input_ports = nullptr;
- instance->output_port_count = node->get_output_value_port_count();
- instance->output_ports = nullptr;
- instance->sequence_output_count = node->get_output_sequence_port_count();
- instance->sequence_index = function.node_count++;
- instance->sequence_outputs = nullptr;
- instance->pass_idx = -1;
+ if (func_node.is_null()) {
+ VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->get()));
+ }
- if (instance->input_port_count) {
- instance->input_ports = memnew_arr(int, instance->input_port_count);
- for (int i = 0; i < instance->input_port_count; i++) {
+ ERR_CONTINUE(!func_node.is_valid());
- instance->input_ports[i] = -1; //if not assigned, will become default value
- }
+ function.argument_count = func_node->get_argument_count();
+ function.max_stack += function.argument_count;
+ function.flow_stack_size = func_node->is_stack_less() ? 0 : func_node->get_stack_size();
+ max_input_args = MAX(max_input_args, function.argument_count);
}
-
- if (instance->output_port_count) {
- instance->output_ports = memnew_arr(int, instance->output_port_count);
- for (int i = 0; i < instance->output_port_count; i++) {
- instance->output_ports[i] = -1; //if not assigned, will output to trash
+ // Function nodes graphs.
+ Set<VisualScript::SequenceConnection> seqconns;
+ Set<VisualScript::DataConnection> dataconns;
+ Set<int> node_ids;
+ node_ids.insert(function.node);
+ {
+ List<int> nd_queue;
+ nd_queue.push_back(function.node);
+ while (!nd_queue.is_empty()) {
+ for (const Set<VisualScript::SequenceConnection>::Element *F = script->sequence_connections.front(); F; F = F->next()) {
+ if (nd_queue.front()->get() == F->get().from_node && !node_ids.has(F->get().to_node)) {
+ nd_queue.push_back(F->get().to_node);
+ node_ids.insert(F->get().to_node);
+ }
+ if (nd_queue.front()->get() == F->get().from_node && !seqconns.has(F->get())) {
+ seqconns.insert(F->get());
+ }
+ }
+ nd_queue.pop_front();
}
- }
-
- if (instance->sequence_output_count) {
- instance->sequence_outputs = memnew_arr(VisualScriptNodeInstance *, instance->sequence_output_count);
- for (int i = 0; i < instance->sequence_output_count; i++) {
- instance->sequence_outputs[i] = nullptr; //if it remains null, flow ends here
+ HashMap<int, HashMap<int, Pair<int, int>>> dc_lut; // :: to -> to_port -> (from, from_port)
+ for (const Set<VisualScript::DataConnection>::Element *F = script->data_connections.front(); F; F = F->next()) {
+ dc_lut[F->get().to_node][F->get().to_port] = Pair<int, int>(F->get().from_node, F->get().from_port);
+ }
+ for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) {
+ nd_queue.push_back(F->get());
+ }
+ List<int> dc_keys;
+ while (!nd_queue.is_empty()) {
+ int ky = nd_queue.front()->get();
+ dc_lut[ky].get_key_list(&dc_keys);
+ for (const List<int>::Element *F = dc_keys.front(); F; F = F->next()) {
+ VisualScript::DataConnection dc;
+ dc.from_node = dc_lut[ky][F->get()].first;
+ dc.from_port = dc_lut[ky][F->get()].second;
+ dc.to_node = ky;
+ dc.to_port = F->get();
+ dataconns.insert(dc);
+ nd_queue.push_back(dc.from_node);
+ node_ids.insert(dc.from_node);
+ }
+ dc_keys.clear(); // Necessary as get_key_list does a push_back not a set.
+ nd_queue.pop_front();
}
}
- if (Object::cast_to<VisualScriptLocalVar>(node.ptr()) || Object::cast_to<VisualScriptLocalVarSet>(*node)) {
- //working memory is shared only for this node, for the same variables
- Ref<VisualScriptLocalVar> vslv = node;
-
- StringName var_name;
-
- if (Object::cast_to<VisualScriptLocalVar>(*node))
- var_name = String(Object::cast_to<VisualScriptLocalVar>(*node)->get_var_name()).strip_edges();
- else
- var_name = String(Object::cast_to<VisualScriptLocalVarSet>(*node)->get_var_name()).strip_edges();
-
- if (!local_var_indices.has(var_name)) {
- local_var_indices[var_name] = function.max_stack;
- function.max_stack++;
+ //Multiple passes are required to set up this complex thing..
+ //First create the nodes.
+ for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) {
+ Ref<VisualScriptNode> node = script->nodes[F->get()].node;
+
+ VisualScriptNodeInstance *instance = node->instance(this); // Create instance.
+ ERR_FAIL_COND(!instance);
+
+ instance->base = node.ptr();
+
+ instance->id = F->get();
+ instance->input_port_count = node->get_input_value_port_count();
+ instance->input_ports = NULL;
+ instance->output_port_count = node->get_output_value_port_count();
+ instance->output_ports = NULL;
+ instance->sequence_output_count = node->get_output_sequence_port_count();
+ instance->sequence_index = function.node_count++;
+ instance->sequence_outputs = NULL;
+ instance->pass_idx = -1;
+
+ if (instance->input_port_count) {
+ instance->input_ports = memnew_arr(int, instance->input_port_count);
+ for (int i = 0; i < instance->input_port_count; i++) {
+ instance->input_ports[i] = -1; // If not assigned, will become default value.
+ }
}
- instance->working_mem_idx = local_var_indices[var_name];
+ if (instance->output_port_count) {
+ instance->output_ports = memnew_arr(int, instance->output_port_count);
+ for (int i = 0; i < instance->output_port_count; i++) {
+ instance->output_ports[i] = -1; // If not assigned, will output to trash.
+ }
+ }
- } else if (instance->get_working_memory_size()) {
- instance->working_mem_idx = function.max_stack;
- function.max_stack += instance->get_working_memory_size();
- } else {
- instance->working_mem_idx = -1; //no working mem
- }
+ if (instance->sequence_output_count) {
+ instance->sequence_outputs = memnew_arr(VisualScriptNodeInstance *, instance->sequence_output_count);
+ for (int i = 0; i < instance->sequence_output_count; i++) {
+ instance->sequence_outputs[i] = NULL; // If it remains null, flow ends here.
+ }
+ }
- max_input_args = MAX(max_input_args, instance->input_port_count);
- max_output_args = MAX(max_output_args, instance->output_port_count);
+ if (Object::cast_to<VisualScriptLocalVar>(node.ptr()) || Object::cast_to<VisualScriptLocalVarSet>(*node)) {
+ // Working memory is shared only for this node, for the same variables.
+ Ref<VisualScriptLocalVar> vslv = node;
- instances[F->key()] = instance;
- }
+ StringName var_name;
- function.trash_pos = function.max_stack++; //create pos for trash
+ if (Object::cast_to<VisualScriptLocalVar>(*node))
+ var_name = String(Object::cast_to<VisualScriptLocalVar>(*node)->get_var_name()).strip_edges();
+ else
+ var_name = String(Object::cast_to<VisualScriptLocalVarSet>(*node)->get_var_name()).strip_edges();
- //second pass, do data connections
+ if (!local_var_indices.has(var_name)) {
+ local_var_indices[var_name] = function.max_stack;
+ function.max_stack++;
+ }
- for (const Set<VisualScript::DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) {
+ instance->working_mem_idx = local_var_indices[var_name];
- VisualScript::DataConnection dc = F->get();
- ERR_CONTINUE(!instances.has(dc.from_node));
- VisualScriptNodeInstance *from = instances[dc.from_node];
- ERR_CONTINUE(!instances.has(dc.to_node));
- VisualScriptNodeInstance *to = instances[dc.to_node];
- ERR_CONTINUE(dc.from_port >= from->output_port_count);
- ERR_CONTINUE(dc.to_port >= to->input_port_count);
+ } else if (instance->get_working_memory_size()) {
+ instance->working_mem_idx = function.max_stack;
+ function.max_stack += instance->get_working_memory_size();
+ } else {
+ instance->working_mem_idx = -1; //no working mem
+ }
- if (from->output_ports[dc.from_port] == -1) {
+ max_input_args = MAX(max_input_args, instance->input_port_count);
+ max_output_args = MAX(max_output_args, instance->output_port_count);
- int stack_pos = function.max_stack++;
- from->output_ports[dc.from_port] = stack_pos;
+ instances[F->get()] = instance;
}
- if (from->get_sequence_output_count() == 0 && to->dependencies.find(from) == -1) {
- //if the node we are reading from has no output sequence, we must call step() before reading from it.
- if (from->pass_idx == -1) {
- from->pass_idx = function.pass_stack_size;
- function.pass_stack_size++;
+ function.trash_pos = function.max_stack++; // create pos for trash
+
+ // Second pass, do data connections.
+ for (const Set<VisualScript::DataConnection>::Element *F = dataconns.front(); F; F = F->next()) {
+ VisualScript::DataConnection dc = F->get();
+ ERR_CONTINUE(!instances.has(dc.from_node));
+ VisualScriptNodeInstance *from = instances[dc.from_node];
+ ERR_CONTINUE(!instances.has(dc.to_node));
+ VisualScriptNodeInstance *to = instances[dc.to_node];
+ ERR_CONTINUE(dc.from_port >= from->output_port_count);
+ ERR_CONTINUE(dc.to_port >= to->input_port_count);
+
+ if (from->output_ports[dc.from_port] == -1) {
+ int stack_pos = function.max_stack++;
+ from->output_ports[dc.from_port] = stack_pos;
}
- to->dependencies.push_back(from);
- }
-
- to->input_ports[dc.to_port] = from->output_ports[dc.from_port]; //read from wherever the stack is
- }
-
- //third pass, do sequence connections
-
- for (const Set<VisualScript::SequenceConnection>::Element *F = E->get().sequence_connections.front(); F; F = F->next()) {
- VisualScript::SequenceConnection sc = F->get();
- ERR_CONTINUE(!instances.has(sc.from_node));
- VisualScriptNodeInstance *from = instances[sc.from_node];
- ERR_CONTINUE(!instances.has(sc.to_node));
- VisualScriptNodeInstance *to = instances[sc.to_node];
- ERR_CONTINUE(sc.from_output >= from->sequence_output_count);
-
- from->sequence_outputs[sc.from_output] = to;
- }
+ if (from->get_sequence_output_count() == 0 && to->dependencies.find(from) == -1) {
+ // If the node we are reading from has no output sequence, we must call step() before reading from it.
+ if (from->pass_idx == -1) {
+ from->pass_idx = function.pass_stack_size;
+ function.pass_stack_size++;
+ }
+ to->dependencies.push_back(from);
+ }
- //fourth pass:
- // 1) unassigned input ports to default values
- // 2) connect unassigned output ports to trash
+ to->input_ports[dc.to_port] = from->output_ports[dc.from_port]; // Read from wherever the stack is.
+ }
- for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
+ // Third pass, do sequence connections.
+ for (const Set<VisualScript::SequenceConnection>::Element *F = seqconns.front(); F; F = F->next()) {
+ VisualScript::SequenceConnection sc = F->get();
+ ERR_CONTINUE(!instances.has(sc.from_node));
+ VisualScriptNodeInstance *from = instances[sc.from_node];
+ ERR_CONTINUE(!instances.has(sc.to_node));
+ VisualScriptNodeInstance *to = instances[sc.to_node];
+ ERR_CONTINUE(sc.from_output >= from->sequence_output_count);
- ERR_CONTINUE(!instances.has(F->key()));
+ from->sequence_outputs[sc.from_output] = to;
+ }
- Ref<VisualScriptNode> node = F->get().node;
- VisualScriptNodeInstance *instance = instances[F->key()];
+ //fourth pass:
+ // 1) unassigned input ports to default values
+ // 2) connect unassigned output ports to trash
+ for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) {
+ ERR_CONTINUE(!instances.has(F->get()));
- // connect to default values
- for (int i = 0; i < instance->input_port_count; i++) {
- if (instance->input_ports[i] == -1) {
+ Ref<VisualScriptNode> node = script->nodes[F->get()].node;
+ VisualScriptNodeInstance *instance = instances[F->get()];
- //unassigned, connect to default val
- instance->input_ports[i] = default_values.size() | VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT;
- default_values.push_back(node->get_default_input_value(i));
+ // Connect to default values.
+ for (int i = 0; i < instance->input_port_count; i++) {
+ if (instance->input_ports[i] == -1) {
+ // Unassigned, connect to default val.
+ instance->input_ports[i] = default_values.size() | VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT;
+ default_values.push_back(node->get_default_input_value(i));
+ }
}
- }
- // connect to trash
- for (int i = 0; i < instance->output_port_count; i++) {
- if (instance->output_ports[i] == -1) {
- instance->output_ports[i] = function.trash_pos; //trash is same for all
+ // Connect to trash.
+ for (int i = 0; i < instance->output_port_count; i++) {
+ if (instance->output_ports[i] == -1) {
+ instance->output_ports[i] = function.trash_pos; //trash is same for all
+ }
}
}
- }
- functions[E->key()] = function;
+ functions[E->get()] = function;
+ }
}
}
ScriptLanguage *VisualScriptInstance::get_language() {
-
return VisualScriptLanguage::singleton;
}
@@ -2410,7 +2193,6 @@ VisualScriptInstance::VisualScriptInstance() {
}
VisualScriptInstance::~VisualScriptInstance() {
-
{
MutexLock lock(VisualScriptLanguage::singleton->lock);
@@ -2427,7 +2209,6 @@ VisualScriptInstance::~VisualScriptInstance() {
/////////////////////
Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
-
ERR_FAIL_COND_V(function == StringName(), Variant());
#ifdef DEBUG_ENABLED
@@ -2448,7 +2229,6 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int
} else if (p_argcount == 1) {
//noooneee, reserved for me, me and only me.
} else {
-
for (int i = 0; i < p_argcount - 1; i++) {
args.push_back(*p_args[i]);
}
@@ -2467,7 +2247,7 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int
Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index;
- *working_mem = args; //arguments go to working mem.
+ *working_mem = args; // Arguments go to working mem.
Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error);
function = StringName(); //invalidate
@@ -2475,22 +2255,19 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int
}
void VisualScriptFunctionState::connect_to_signal(Object *p_obj, const String &p_signal, Array p_binds) {
-
Vector<Variant> binds;
for (int i = 0; i < p_binds.size(); i++) {
binds.push_back(p_binds[i]);
}
binds.push_back(Ref<VisualScriptFunctionState>(this)); //add myself on the back to avoid dying from unreferencing
- p_obj->connect_compat(p_signal, this, "_signal_callback", binds, CONNECT_ONESHOT);
+ p_obj->connect(p_signal, Callable(this, "_signal_callback"), binds, CONNECT_ONESHOT);
}
bool VisualScriptFunctionState::is_valid() const {
-
return function != StringName();
}
Variant VisualScriptFunctionState::resume(Array p_args) {
-
ERR_FAIL_COND_V(function == StringName(), Variant());
#ifdef DEBUG_ENABLED
@@ -2504,7 +2281,7 @@ Variant VisualScriptFunctionState::resume(Array p_args) {
Variant *working_mem = ((Variant *)stack.ptr()) + working_mem_index;
- *working_mem = p_args; //arguments go to working mem.
+ *working_mem = p_args; // Arguments go to working mem.
Variant ret = instance->_call_internal(function, stack.ptrw(), stack.size(), node, flow_stack_pos, pass, true, r_error);
function = StringName(); //invalidate
@@ -2512,7 +2289,6 @@ Variant VisualScriptFunctionState::resume(Array p_args) {
}
void VisualScriptFunctionState::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("connect_to_signal", "obj", "signals", "args"), &VisualScriptFunctionState::connect_to_signal);
ClassDB::bind_method(D_METHOD("resume", "args"), &VisualScriptFunctionState::resume, DEFVAL(Variant()));
ClassDB::bind_method(D_METHOD("is_valid"), &VisualScriptFunctionState::is_valid);
@@ -2523,7 +2299,6 @@ VisualScriptFunctionState::VisualScriptFunctionState() {
}
VisualScriptFunctionState::~VisualScriptFunctionState() {
-
if (function != StringName()) {
Variant *s = ((Variant *)stack.ptr());
for (int i = 0; i < variant_stack_size; i++) {
@@ -2535,37 +2310,39 @@ VisualScriptFunctionState::~VisualScriptFunctionState() {
///////////////////////////////////////////////
String VisualScriptLanguage::get_name() const {
-
return "VisualScript";
}
/* LANGUAGE FUNCTIONS */
void VisualScriptLanguage::init() {
}
-String VisualScriptLanguage::get_type() const {
+String VisualScriptLanguage::get_type() const {
return "VisualScript";
}
-String VisualScriptLanguage::get_extension() const {
+String VisualScriptLanguage::get_extension() const {
return "vs";
}
-Error VisualScriptLanguage::execute_file(const String &p_path) {
+Error VisualScriptLanguage::execute_file(const String &p_path) {
return OK;
}
+
void VisualScriptLanguage::finish() {
}
/* EDITOR FUNCTIONS */
void VisualScriptLanguage::get_reserved_words(List<String> *p_words) const {
}
+
void VisualScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
}
+
void VisualScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
}
-Ref<Script> VisualScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
+Ref<Script> VisualScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
Ref<VisualScript> script;
script.instance();
script->set_instance_base_type(p_base_class_name);
@@ -2573,7 +2350,6 @@ Ref<Script> VisualScriptLanguage::get_template(const String &p_class_name, const
}
bool VisualScriptLanguage::is_using_templates() {
-
return true;
}
@@ -2583,42 +2359,41 @@ void VisualScriptLanguage::make_template(const String &p_class_name, const Strin
}
bool VisualScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
-
return false;
}
-Script *VisualScriptLanguage::create_script() const {
+Script *VisualScriptLanguage::create_script() const {
return memnew(VisualScript);
}
-bool VisualScriptLanguage::has_named_classes() const {
+bool VisualScriptLanguage::has_named_classes() const {
return false;
}
-bool VisualScriptLanguage::supports_builtin_mode() const {
+bool VisualScriptLanguage::supports_builtin_mode() const {
return true;
}
-int VisualScriptLanguage::find_function(const String &p_function, const String &p_code) const {
+int VisualScriptLanguage::find_function(const String &p_function, const String &p_code) const {
return -1;
}
-String VisualScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
+String VisualScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
return String();
}
void VisualScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
}
+
void VisualScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
}
/* DEBUGGER FUNCTIONS */
bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, const String &p_error) {
- //break because of parse error
+ // Break because of parse error.
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
-
_debug_parse_err_node = p_node;
_debug_parse_err_file = p_file;
_debug_error = p_error;
@@ -2630,9 +2405,7 @@ bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, c
}
bool VisualScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
-
if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
-
_debug_parse_err_node = -1;
_debug_parse_err_file = "";
_debug_error = p_error;
@@ -2644,21 +2417,21 @@ bool VisualScriptLanguage::debug_break(const String &p_error, bool p_allow_conti
}
String VisualScriptLanguage::debug_get_error() const {
-
return _debug_error;
}
int VisualScriptLanguage::debug_get_stack_level_count() const {
-
- if (_debug_parse_err_node >= 0)
+ if (_debug_parse_err_node >= 0) {
return 1;
+ }
return _debug_call_stack_pos;
}
-int VisualScriptLanguage::debug_get_stack_level_line(int p_level) const {
- if (_debug_parse_err_node >= 0)
+int VisualScriptLanguage::debug_get_stack_level_line(int p_level) const {
+ if (_debug_parse_err_node >= 0) {
return _debug_parse_err_node;
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
@@ -2666,28 +2439,31 @@ int VisualScriptLanguage::debug_get_stack_level_line(int p_level) const {
return *(_call_stack[l].current_id);
}
-String VisualScriptLanguage::debug_get_stack_level_function(int p_level) const {
- if (_debug_parse_err_node >= 0)
+String VisualScriptLanguage::debug_get_stack_level_function(int p_level) const {
+ if (_debug_parse_err_node >= 0) {
return "";
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
int l = _debug_call_stack_pos - p_level - 1;
return *_call_stack[l].function;
}
-String VisualScriptLanguage::debug_get_stack_level_source(int p_level) const {
- if (_debug_parse_err_node >= 0)
+String VisualScriptLanguage::debug_get_stack_level_source(int p_level) const {
+ if (_debug_parse_err_node >= 0) {
return _debug_parse_err_file;
+ }
ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
int l = _debug_call_stack_pos - p_level - 1;
return _call_stack[l].instance->get_script_ptr()->get_path();
}
-void VisualScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
- if (_debug_parse_err_node >= 0)
+void VisualScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
+ if (_debug_parse_err_node >= 0) {
return;
+ }
ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
@@ -2724,7 +2500,6 @@ void VisualScriptLanguage::debug_get_stack_level_locals(int p_level, List<String
}
for (int i = 0; i < node->output_port_count; i++) {
-
String name = node->get_base_node()->get_output_value_port_info(i).name;
if (name == String()) {
name = "out_" + itos(i);
@@ -2753,23 +2528,24 @@ void VisualScriptLanguage::debug_get_stack_level_locals(int p_level, List<String
f->debug_get_stack_member_state(*_call_stack[l].line,&locals);
for( List<Pair<StringName,int> >::Element *E = locals.front();E;E=E->next() ) {
-
p_locals->push_back(E->get().first);
p_values->push_back(_call_stack[l].stack[E->get().second]);
}
*/
}
-void VisualScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
- if (_debug_parse_err_node >= 0)
+void VisualScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
+ if (_debug_parse_err_node >= 0) {
return;
+ }
ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
int l = _debug_call_stack_pos - p_level - 1;
Ref<VisualScript> vs = _call_stack[l].instance->get_script();
- if (vs.is_null())
+ if (vs.is_null()) {
return;
+ }
List<StringName> vars;
vs->get_variable_list(&vars);
@@ -2783,48 +2559,48 @@ void VisualScriptLanguage::debug_get_stack_level_members(int p_level, List<Strin
}
void VisualScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
-
- //no globals are really reachable in gdscript
+ // No globals are really reachable in gdscript.
}
-String VisualScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
+String VisualScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
return "";
}
void VisualScriptLanguage::reload_all_scripts() {
}
+
void VisualScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
}
+
/* LOADER FUNCTIONS */
void VisualScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("vs");
}
+
void VisualScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
}
+
void VisualScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const {
}
void VisualScriptLanguage::profiling_start() {
}
+
void VisualScriptLanguage::profiling_stop() {
}
int VisualScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
-
return 0;
}
int VisualScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
-
return 0;
}
VisualScriptLanguage *VisualScriptLanguage::singleton = nullptr;
void VisualScriptLanguage::add_register_func(const String &p_name, VisualScriptNodeRegisterFunc p_func) {
-
ERR_FAIL_COND(register_funcs.has(p_name));
register_funcs[p_name] = p_func;
}
@@ -2835,21 +2611,18 @@ void VisualScriptLanguage::remove_register_func(const String &p_name) {
}
Ref<VisualScriptNode> VisualScriptLanguage::create_node_from_name(const String &p_name) {
-
ERR_FAIL_COND_V(!register_funcs.has(p_name), Ref<VisualScriptNode>());
return register_funcs[p_name](p_name);
}
void VisualScriptLanguage::get_registered_node_names(List<String> *r_names) {
-
for (Map<String, VisualScriptNodeRegisterFunc>::Element *E = register_funcs.front(); E; E = E->next()) {
r_names->push_back(E->key());
}
}
VisualScriptLanguage::VisualScriptLanguage() {
-
notification = "_notification";
_step = "_step";
_subcall = "_subcall";
@@ -2862,7 +2635,7 @@ VisualScriptLanguage::VisualScriptLanguage() {
ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/visual_script/max_call_stack", PropertyInfo(Variant::INT, "debug/settings/visual_script/max_call_stack", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); //minimum is 1024
if (EngineDebugger::is_active()) {
- //debugging enabled!
+ // Debugging enabled!
_debug_max_call_stack = dmcs;
_call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
@@ -2873,7 +2646,6 @@ VisualScriptLanguage::VisualScriptLanguage() {
}
VisualScriptLanguage::~VisualScriptLanguage() {
-
if (_call_stack) {
memdelete_arr(_call_stack);
}
diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h
index c154e56703..bdb3c3a16b 100644
--- a/modules/visual_script/visual_script.h
+++ b/modules/visual_script/visual_script.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,8 +33,9 @@
#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
+#include "core/doc_data.h"
+#include "core/object/script_language.h"
#include "core/os/thread.h"
-#include "core/script_language.h"
class VisualScriptInstance;
class VisualScriptNodeInstance;
@@ -45,7 +46,7 @@ class VisualScriptNode : public Resource {
friend class VisualScript;
- Set<VisualScript *> scripts_used;
+ Ref<VisualScript> script_used;
Array default_input_values;
bool breakpoint;
@@ -82,14 +83,13 @@ public:
virtual String get_text() const;
virtual String get_category() const = 0;
- //used by editor, this is not really saved
+ // Used by editor, this is not really saved.
void set_breakpoint(bool p_breakpoint);
bool is_breakpoint() const;
virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) = 0;
struct TypeGuess {
-
Variant::Type type;
StringName gdclass;
Ref<Script> script;
@@ -106,9 +106,9 @@ public:
class VisualScriptNodeInstance {
friend class VisualScriptInstance;
- friend class VisualScriptLanguage; //for debugger
+ friend class VisualScriptLanguage; // For debugger.
- enum { //input argument addressing
+ enum { // Input argument addressing.
INPUT_SHIFT = 1 << 24,
INPUT_MASK = INPUT_SHIFT - 1,
INPUT_DEFAULT_VALUE_BIT = INPUT_SHIFT, // from unassigned input port, using default value (edited by user)
@@ -138,13 +138,13 @@ public:
enum {
STEP_SHIFT = 1 << 24,
STEP_MASK = STEP_SHIFT - 1,
- STEP_FLAG_PUSH_STACK_BIT = STEP_SHIFT, //push bit to stack
- STEP_FLAG_GO_BACK_BIT = STEP_SHIFT << 1, //go back to previous node
- STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, //do not advance past this node
- STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, //return from function
- STEP_YIELD_BIT = STEP_SHIFT << 4, //yield (will find VisualScriptFunctionState state in first working memory)
+ STEP_FLAG_PUSH_STACK_BIT = STEP_SHIFT, // push bit to stack
+ STEP_FLAG_GO_BACK_BIT = STEP_SHIFT << 1, // go back to previous node
+ STEP_NO_ADVANCE_BIT = STEP_SHIFT << 2, // do not advance past this node
+ STEP_EXIT_FUNCTION_BIT = STEP_SHIFT << 3, // return from function
+ STEP_YIELD_BIT = STEP_SHIFT << 4, // yield (will find VisualScriptFunctionState state in first working memory)
- FLOW_STACK_PUSHED_BIT = 1 << 30, //in flow stack, means bit was pushed (must go back here if end of sequence)
+ FLOW_STACK_PUSHED_BIT = 1 << 30, // in flow stack, means bit was pushed (must go back here if end of sequence)
FLOW_STACK_MASK = FLOW_STACK_PUSHED_BIT - 1
};
@@ -157,7 +157,7 @@ public:
virtual int get_working_memory_size() const { return 0; }
- virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) = 0; //do a step, return which sequence port to go out
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) = 0; // Do a step, return which sequence port to go out.
Ref<VisualScriptNode> get_base_node() { return Ref<VisualScriptNode>(base); }
@@ -166,16 +166,13 @@ public:
};
class VisualScript : public Script {
-
GDCLASS(VisualScript, Script);
RES_BASE_EXTENSION("vs");
public:
struct SequenceConnection {
-
union {
-
struct {
uint64_t from_node : 24;
uint64_t from_output : 16;
@@ -185,15 +182,12 @@ public:
};
bool operator<(const SequenceConnection &p_connection) const {
-
return id < p_connection.id;
}
};
struct DataConnection {
-
union {
-
struct {
uint64_t from_node : 24;
uint64_t from_port : 8;
@@ -204,7 +198,6 @@ public:
};
bool operator<(const DataConnection &p_connection) const {
-
return id < p_connection.id;
}
};
@@ -218,34 +211,32 @@ private:
Variant::Type type;
};
- struct Function {
- struct NodeData {
- Point2 pos;
- Ref<VisualScriptNode> node;
- };
-
- Map<int, NodeData> nodes;
-
- Set<SequenceConnection> sequence_connections;
+ struct NodeData {
+ Point2 pos;
+ Ref<VisualScriptNode> node;
+ };
- Set<DataConnection> data_connections;
+ HashMap<int, NodeData> nodes; // Can be a sparse map.
- int function_id;
+ Set<SequenceConnection> sequence_connections;
+ Set<DataConnection> data_connections;
- Vector2 scroll;
+ Vector2 scroll;
- Function() { function_id = -1; }
+ struct Function {
+ int func_id;
+ Function() { func_id = -1; }
};
struct Variable {
PropertyInfo info;
Variant default_value;
bool _export;
- // add getter & setter options here
+ // Add getter & setter options here.
};
- Map<StringName, Function> functions;
- Map<StringName, Variable> variables;
+ HashMap<StringName, Function> functions;
+ HashMap<StringName, Variable> variables;
Map<StringName, Vector<Argument>> custom_signals;
Vector<ScriptNetData> rpc_functions;
Vector<ScriptNetData> rpc_variables;
@@ -256,8 +247,8 @@ private:
#ifdef TOOLS_ENABLED
Set<PlaceHolderScriptInstance *> placeholders;
- //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
- virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
+ // void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
+ virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) override;
void _update_placeholders();
#endif
@@ -272,39 +263,40 @@ protected:
static void _bind_methods();
public:
- bool inherits_script(const Ref<Script> &p_script) const;
+ bool inherits_script(const Ref<Script> &p_script) const override;
- // TODO: Remove it in future when breaking changes are acceptable
- StringName get_default_func() const;
- void add_function(const StringName &p_name);
+ void set_scroll(const Vector2 &p_scroll);
+ Vector2 get_scroll() const;
+
+ void add_function(const StringName &p_name, int p_func_node_id);
bool has_function(const StringName &p_name) const;
void remove_function(const StringName &p_name);
void rename_function(const StringName &p_name, const StringName &p_new_name);
- void set_function_scroll(const StringName &p_name, const Vector2 &p_scroll);
- Vector2 get_function_scroll(const StringName &p_name) const;
void get_function_list(List<StringName> *r_functions) const;
int get_function_node_id(const StringName &p_name) const;
void set_tool_enabled(bool p_enabled);
- void add_node(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2());
- void remove_node(const StringName &p_func, int p_id);
- bool has_node(const StringName &p_func, int p_id) const;
- Ref<VisualScriptNode> get_node(const StringName &p_func, int p_id) const;
- void set_node_position(const StringName &p_func, int p_id, const Point2 &p_pos);
- Point2 get_node_position(const StringName &p_func, int p_id) const;
- void get_node_list(const StringName &p_func, List<int> *r_nodes) const;
-
- void sequence_connect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node);
- void sequence_disconnect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node);
- bool has_sequence_connection(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) const;
- void get_sequence_connection_list(const StringName &p_func, List<SequenceConnection> *r_connection) const;
-
- void data_connect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port);
- void data_disconnect(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port);
- bool has_data_connection(const StringName &p_func, int p_from_node, int p_from_port, int p_to_node, int p_to_port) const;
- void get_data_connection_list(const StringName &p_func, List<DataConnection> *r_connection) const;
- bool is_input_value_port_connected(const StringName &p_func, int p_node, int p_port) const;
- bool get_input_value_port_connection_source(const StringName &p_func, int p_node, int p_port, int *r_node, int *r_port) const;
+ void add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos = Point2());
+ void remove_node(int p_id);
+ bool has_node(int p_id) const;
+ Ref<VisualScriptNode> get_node(int p_id) const;
+ void set_node_position(int p_id, const Point2 &p_pos);
+ Point2 get_node_position(int p_id) const;
+ void get_node_list(List<int> *r_nodes) const;
+
+ void sequence_connect(int p_from_node, int p_from_output, int p_to_node);
+ void sequence_disconnect(int p_from_node, int p_from_output, int p_to_node);
+ bool has_sequence_connection(int p_from_node, int p_from_output, int p_to_node) const;
+ void get_sequence_connection_list(List<SequenceConnection> *r_connection) const;
+ Set<int> get_output_sequence_ports_connected(int from_node);
+
+ void data_connect(int p_from_node, int p_from_port, int p_to_node, int p_to_port);
+ void data_disconnect(int p_from_node, int p_from_port, int p_to_node, int p_to_port);
+ bool has_data_connection(int p_from_node, int p_from_port, int p_to_node, int p_to_port) const;
+ void get_data_connection_list(List<DataConnection> *r_connection) const;
+
+ bool is_input_value_port_connected(int p_node, int p_port) const;
+ bool get_input_value_port_connection_source(int p_node, int p_port, int *r_node, int *r_port) const;
void add_variable(const StringName &p_name, const Variant &p_default_value = Variant(), bool p_export = false);
bool has_variable(const StringName &p_name) const;
@@ -338,47 +330,54 @@ public:
void set_instance_base_type(const StringName &p_type);
- virtual bool can_instance() const;
+ virtual bool can_instance() const override;
- virtual Ref<Script> get_base_script() const;
- virtual StringName get_instance_base_type() const;
- virtual ScriptInstance *instance_create(Object *p_this);
- virtual bool instance_has(const Object *p_this) const;
+ virtual Ref<Script> get_base_script() const override;
+ virtual StringName get_instance_base_type() const override;
+ virtual ScriptInstance *instance_create(Object *p_this) override;
+ virtual bool instance_has(const Object *p_this) const override;
- virtual bool has_source_code() const;
- virtual String get_source_code() const;
- virtual void set_source_code(const String &p_code);
- virtual Error reload(bool p_keep_state = false);
+ virtual bool has_source_code() const override;
+ virtual String get_source_code() const override;
+ virtual void set_source_code(const String &p_code) override;
+ virtual Error reload(bool p_keep_state = false) override;
- virtual bool is_tool() const;
- virtual bool is_valid() const;
+#ifdef TOOLS_ENABLED
+ virtual const Vector<DocData::ClassDoc> &get_documentation() const override {
+ static Vector<DocData::ClassDoc> docs;
+ return docs;
+ }
+#endif // TOOLS_ENABLED
- virtual ScriptLanguage *get_language() const;
+ virtual bool is_tool() const override;
+ virtual bool is_valid() const override;
- virtual bool has_script_signal(const StringName &p_signal) const;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
+ virtual ScriptLanguage *get_language() const override;
- virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const;
- virtual void get_script_method_list(List<MethodInfo> *p_list) const;
+ virtual bool has_script_signal(const StringName &p_signal) const override;
+ virtual void get_script_signal_list(List<MethodInfo> *r_signals) const override;
- virtual bool has_method(const StringName &p_method) const;
- virtual MethodInfo get_method_info(const StringName &p_method) const;
+ virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const override;
+ virtual void get_script_method_list(List<MethodInfo> *p_list) const override;
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
+ virtual bool has_method(const StringName &p_method) const override;
+ virtual MethodInfo get_method_info(const StringName &p_method) const override;
- virtual int get_member_line(const StringName &p_member) const;
+ virtual void get_script_property_list(List<PropertyInfo> *p_list) const override;
- virtual Vector<ScriptNetData> get_rpc_methods() const;
- virtual uint16_t get_rpc_method_id(const StringName &p_method) const;
- virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual int get_member_line(const StringName &p_member) const override;
- virtual Vector<ScriptNetData> get_rset_properties() const;
- virtual uint16_t get_rset_property_id(const StringName &p_property) const;
- virtual StringName get_rset_property(const uint16_t p_rset_property_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const;
- virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const;
+ virtual Vector<ScriptNetData> get_rpc_methods() const override;
+ virtual uint16_t get_rpc_method_id(const StringName &p_method) const override;
+ virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override;
+
+ virtual Vector<ScriptNetData> get_rset_properties() const override;
+ virtual uint16_t get_rset_property_id(const StringName &p_property) const override;
+ virtual StringName get_rset_property(const uint16_t p_rset_property_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const override;
+ virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override;
#ifdef TOOLS_ENABLED
virtual bool are_subnodes_edited() const;
@@ -392,7 +391,7 @@ class VisualScriptInstance : public ScriptInstance {
Object *owner;
Ref<VisualScript> script;
- Map<StringName, Variant> variables; //using variable path, not script
+ Map<StringName, Variant> variables; // Using variable path, not script.
Map<int, VisualScriptNodeInstance *> instances;
struct Function {
@@ -415,9 +414,8 @@ class VisualScriptInstance : public ScriptInstance {
void _dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Callable::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node);
Variant _call_internal(const StringName &p_method, void *p_stack, int p_stack_size, VisualScriptNodeInstance *p_node, int p_flow_stack_pos, int p_pass, bool p_resuming_yield, Callable::CallError &r_error);
- //Map<StringName,Function> functions;
- friend class VisualScriptFunctionState; //for yield
- friend class VisualScriptLanguage; //for debugger
+ friend class VisualScriptFunctionState; // For yield.
+ friend class VisualScriptLanguage; // For debugger.
public:
virtual bool set(const StringName &p_name, const Variant &p_value);
virtual bool get(const StringName &p_name, Variant &r_ret) const;
@@ -431,20 +429,20 @@ public:
String to_string(bool *r_valid);
bool set_variable(const StringName &p_variable, const Variant &p_value) {
-
Map<StringName, Variant>::Element *E = variables.find(p_variable);
- if (!E)
+ if (!E) {
return false;
+ }
E->get() = p_value;
return true;
}
bool get_variable(const StringName &p_variable, Variant *r_variable) const {
-
const Map<StringName, Variant>::Element *E = variables.find(p_variable);
- if (!E)
+ if (!E) {
return false;
+ }
*r_variable = E->get();
return true;
@@ -476,7 +474,6 @@ public:
};
class VisualScriptFunctionState : public Reference {
-
GDCLASS(VisualScriptFunctionState, Reference);
friend class VisualScriptInstance;
@@ -507,11 +504,9 @@ public:
typedef Ref<VisualScriptNode> (*VisualScriptNodeRegisterFunc)(const String &p_type);
class VisualScriptLanguage : public ScriptLanguage {
-
Map<String, VisualScriptNodeRegisterFunc> register_funcs;
struct CallLevel {
-
Variant *stack;
Variant **work_mem;
const StringName *function;
@@ -540,15 +535,16 @@ public:
bool debug_break_parse(const String &p_file, int p_node, const String &p_error);
_FORCE_INLINE_ void enter_function(VisualScriptInstance *p_instance, const StringName *p_function, Variant *p_stack, Variant **p_work_mem, int *current_id) {
+ if (Thread::get_main_id() != Thread::get_caller_id()) {
+ return; // No support for other threads than main for now.
+ }
- if (Thread::get_main_id() != Thread::get_caller_id())
- return; //no support for other threads than main for now
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0)
+ if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() + 1);
+ }
if (_debug_call_stack_pos >= _debug_max_call_stack) {
- //stack overflow
+ // Stack overflow.
_debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")";
EngineDebugger::get_script_debugger()->debug(this);
return;
@@ -563,15 +559,15 @@ public:
}
_FORCE_INLINE_ void exit_function() {
+ if (Thread::get_main_id() != Thread::get_caller_id()) {
+ return; // No support for other threads than main for now.
+ }
- if (Thread::get_main_id() != Thread::get_caller_id())
- return; //no support for other threads than main for now
-
- if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0)
+ if (EngineDebugger::get_script_debugger()->get_lines_left() > 0 && EngineDebugger::get_script_debugger()->get_depth() >= 0) {
EngineDebugger::get_script_debugger()->set_depth(EngineDebugger::get_script_debugger()->get_depth() - 1);
+ }
if (_debug_call_stack_pos == 0) {
-
_debug_error = "Stack Underflow (Engine Bug)";
EngineDebugger::get_script_debugger()->debug(this);
return;
@@ -642,10 +638,9 @@ public:
~VisualScriptLanguage();
};
-//aid for registering
+// Aid for registering.
template <class T>
static Ref<VisualScriptNode> create_node_generic(const String &p_name) {
-
Ref<T> node;
node.instance();
return node;
diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp
index bb291b1cb6..2558c1d7ec 100644
--- a/modules/visual_script/visual_script_builtin_funcs.cpp
+++ b/modules/visual_script/visual_script_builtin_funcs.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,13 +30,12 @@
#include "visual_script_builtin_funcs.h"
-#include "core/class_db.h"
-#include "core/func_ref.h"
#include "core/io/marshalls.h"
#include "core/math/math_funcs.h"
+#include "core/object/class_db.h"
+#include "core/object/reference.h"
#include "core/os/os.h"
-#include "core/reference.h"
-#include "core/variant_parser.h"
+#include "core/variant/variant_parser.h"
const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX] = {
"sin",
@@ -64,7 +63,7 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"is_inf",
"ease",
"step_decimals",
- "stepify",
+ "snapped",
"lerp",
"inverse_lerp",
"range_lerp",
@@ -73,7 +72,8 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"randomize",
"randi",
"randf",
- "rand_range",
+ "randf_range",
+ "randi_range",
"seed",
"rand_seed",
"deg2rad",
@@ -89,7 +89,6 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"clamp",
"nearest_po2",
"weakref",
- "funcref",
"convert",
"typeof",
"type_exists",
@@ -110,30 +109,26 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
};
VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String &p_string) {
-
for (int i = 0; i < FUNC_MAX; i++) {
- if (p_string == func_name[i])
+ if (p_string == func_name[i]) {
return BuiltinFunc(i);
+ }
}
return FUNC_MAX;
}
String VisualScriptBuiltinFunc::get_func_name(BuiltinFunc p_func) {
-
ERR_FAIL_INDEX_V(p_func, FUNC_MAX, String());
return func_name[p_func];
}
int VisualScriptBuiltinFunc::get_output_sequence_port_count() const {
-
return has_input_sequence_port() ? 1 : 0;
}
bool VisualScriptBuiltinFunc::has_input_sequence_port() const {
-
switch (func) {
-
case MATH_RANDOMIZE:
case TEXT_PRINT:
case TEXT_PRINTERR:
@@ -145,11 +140,9 @@ bool VisualScriptBuiltinFunc::has_input_sequence_port() const {
}
int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
-
switch (p_func) {
-
case MATH_RANDOMIZE:
- case MATH_RAND:
+ case MATH_RANDI:
case MATH_RANDF:
return 0;
case MATH_SIN:
@@ -199,13 +192,13 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
case MATH_POSMOD:
case MATH_POW:
case MATH_EASE:
- case MATH_STEPIFY:
- case MATH_RANDOM:
+ case MATH_SNAPPED:
+ case MATH_RANDF_RANGE:
+ case MATH_RANDI_RANGE:
case MATH_POLAR2CARTESIAN:
case MATH_CARTESIAN2POLAR:
case LOGIC_MAX:
case LOGIC_MIN:
- case FUNC_FUNCREF:
case TYPE_CONVERT:
case COLORN:
return 2;
@@ -228,11 +221,10 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
}
int VisualScriptBuiltinFunc::get_input_value_port_count() const {
-
return get_func_argument_count(func);
}
-int VisualScriptBuiltinFunc::get_output_value_port_count() const {
+int VisualScriptBuiltinFunc::get_output_value_port_count() const {
switch (func) {
case MATH_RANDOMIZE:
case TEXT_PRINT:
@@ -250,14 +242,11 @@ int VisualScriptBuiltinFunc::get_output_value_port_count() const {
}
String VisualScriptBuiltinFunc::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const {
-
switch (func) {
-
case MATH_SIN:
case MATH_COS:
case MATH_TAN:
@@ -280,96 +269,113 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::FLOAT, "s");
} break;
case MATH_ATAN2: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "y");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "x");
+ }
} break;
case MATH_FMOD:
case MATH_FPOSMOD:
case LOGIC_MAX:
case LOGIC_MIN: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "a");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "b");
+ }
} break;
case MATH_POSMOD: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::INT, "a");
- else
+ } else {
return PropertyInfo(Variant::INT, "b");
+ }
} break;
case MATH_POW: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "base");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "exp");
+ }
} break;
case MATH_EASE: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "s");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "curve");
+ }
} break;
case MATH_STEP_DECIMALS: {
return PropertyInfo(Variant::FLOAT, "step");
} break;
- case MATH_STEPIFY: {
- if (p_idx == 0)
+ case MATH_SNAPPED: {
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "s");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "steps");
+ }
} break;
case MATH_LERP:
case MATH_LERP_ANGLE:
case MATH_INVERSE_LERP:
case MATH_SMOOTHSTEP: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "from");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::FLOAT, "to");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "weight");
+ }
} break;
case MATH_RANGE_LERP: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "value");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::FLOAT, "istart");
- else if (p_idx == 2)
+ } else if (p_idx == 2) {
return PropertyInfo(Variant::FLOAT, "istop");
- else if (p_idx == 3)
+ } else if (p_idx == 3) {
return PropertyInfo(Variant::FLOAT, "ostart");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "ostop");
+ }
} break;
case MATH_MOVE_TOWARD: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "from");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::FLOAT, "to");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "delta");
+ }
} break;
case MATH_DECTIME: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "value");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::FLOAT, "amount");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "step");
+ }
} break;
case MATH_RANDOMIZE:
- case MATH_RAND:
+ case MATH_RANDI:
case MATH_RANDF: {
-
} break;
- case MATH_RANDOM: {
- if (p_idx == 0)
+ case MATH_RANDF_RANGE: {
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "from");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "to");
+ }
+ } break;
+ case MATH_RANDI_RANGE: {
+ if (p_idx == 0) {
+ return PropertyInfo(Variant::INT, "from");
+ } else {
+ return PropertyInfo(Variant::INT, "to");
+ }
} break;
case MATH_SEED:
case MATH_RANDSEED: {
@@ -388,33 +394,37 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::FLOAT, "db");
} break;
case MATH_POLAR2CARTESIAN: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "r");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "th");
+ }
} break;
case MATH_CARTESIAN2POLAR: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "x");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "y");
+ }
} break;
case MATH_WRAP: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::INT, "value");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::INT, "min");
- else
+ } else {
return PropertyInfo(Variant::INT, "max");
+ }
} break;
case MATH_WRAPF:
case LOGIC_CLAMP: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::FLOAT, "value");
- else if (p_idx == 1)
+ } else if (p_idx == 1) {
return PropertyInfo(Variant::FLOAT, "min");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "max");
+ }
} break;
case LOGIC_NEAREST_PO2: {
return PropertyInfo(Variant::INT, "value");
@@ -422,17 +432,12 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
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)
+ if (p_idx == 0) {
return PropertyInfo(Variant::NIL, "what");
- else
+ } else {
return PropertyInfo(Variant::STRING, "type");
+ }
} break;
case TYPE_OF: {
return PropertyInfo(Variant::NIL, "what");
@@ -453,29 +458,30 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::NIL, "value");
} break;
case STR_TO_VAR: {
-
return PropertyInfo(Variant::STRING, "string");
} break;
case VAR_TO_STR:
case VAR_TO_BYTES: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::NIL, "var");
- else
+ } else {
return PropertyInfo(Variant::BOOL, "full_objects");
+ }
} break;
case BYTES_TO_VAR: {
-
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::PACKED_BYTE_ARRAY, "bytes");
- else
+ } else {
return PropertyInfo(Variant::BOOL, "allow_objects");
+ }
} break;
case COLORN: {
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::STRING, "name");
- else
+ } else {
return PropertyInfo(Variant::FLOAT, "alpha");
+ }
} break;
case FUNC_MAX: {
}
@@ -485,10 +491,8 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
}
PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) const {
-
Variant::Type t = Variant::NIL;
switch (func) {
-
case MATH_SIN:
case MATH_COS:
case MATH_TAN:
@@ -533,7 +537,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
case MATH_STEP_DECIMALS: {
t = Variant::INT;
} break;
- case MATH_STEPIFY:
+ case MATH_SNAPPED:
case MATH_LERP:
case MATH_LERP_ANGLE:
case MATH_INVERSE_LERP:
@@ -545,25 +549,25 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
} break;
case MATH_RANDOMIZE: {
-
} break;
- case MATH_RAND: {
-
+ case MATH_RANDI: {
t = Variant::INT;
} break;
case MATH_RANDF:
- case MATH_RANDOM: {
+ case MATH_RANDF_RANGE: {
t = Variant::FLOAT;
} break;
+ case MATH_RANDI_RANGE: {
+ t = Variant::INT;
+ } break;
case MATH_SEED: {
-
} break;
case MATH_RANDSEED: {
-
- if (p_idx == 0)
+ if (p_idx == 0) {
return PropertyInfo(Variant::INT, "rnd");
- else
+ } else {
return PropertyInfo(Variant::INT, "seed");
+ }
} break;
case MATH_DEG2RAD:
case MATH_RAD2DEG:
@@ -582,24 +586,16 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
case LOGIC_MAX:
case LOGIC_MIN:
case LOGIC_CLAMP: {
-
} break;
case LOGIC_NEAREST_PO2: {
t = Variant::NIL;
} break;
case OBJ_WEAKREF: {
-
- t = Variant::OBJECT;
-
- } break;
- case FUNC_FUNCREF: {
-
t = Variant::OBJECT;
} break;
case TYPE_CONVERT: {
-
} break;
case TEXT_ORD:
case TYPE_OF: {
@@ -607,41 +603,37 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
} break;
case TYPE_EXISTS: {
-
t = Variant::BOOL;
} break;
case TEXT_CHAR:
case TEXT_STR: {
-
t = Variant::STRING;
} break;
case TEXT_PRINT: {
-
} break;
case TEXT_PRINTERR: {
-
} break;
case TEXT_PRINTRAW: {
-
} break;
case VAR_TO_STR: {
t = Variant::STRING;
} break;
case STR_TO_VAR: {
-
} break;
case VAR_TO_BYTES: {
- if (p_idx == 0)
+ if (p_idx == 0) {
t = Variant::PACKED_BYTE_ARRAY;
- else
+ } else {
t = Variant::BOOL;
+ }
} break;
case BYTES_TO_VAR: {
- if (p_idx == 1)
+ if (p_idx == 1) {
t = Variant::BOOL;
+ }
} break;
case COLORN: {
t = Variant::COLOR;
@@ -655,18 +647,16 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
/*
String VisualScriptBuiltinFunc::get_caption() const {
-
return "BuiltinFunc";
}
+
*/
String VisualScriptBuiltinFunc::get_caption() const {
-
return func_name[func];
}
void VisualScriptBuiltinFunc::set_func(BuiltinFunc p_which) {
-
ERR_FAIL_INDEX(p_which, FUNC_MAX);
func = p_which;
_change_notify();
@@ -686,197 +676,159 @@ VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::get_func() {
}
void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Callable::CallError &r_error, String &r_error_str) {
-
switch (p_func) {
case VisualScriptBuiltinFunc::MATH_SIN: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::sin((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_COS: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::cos((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_TAN: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::tan((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_SINH: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::sinh((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_COSH: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::cosh((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_TANH: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::tanh((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ASIN: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::asin((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ACOS: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::acos((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ATAN: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::atan((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ATAN2: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
*r_return = Math::atan2((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_SQRT: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::sqrt((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_FMOD: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
*r_return = Math::fmod((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_FPOSMOD: {
-
VALIDATE_ARG_NUM(0);
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);
*r_return = Math::floor((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_CEIL: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::ceil((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ROUND: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::round((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ABS: {
-
if (p_inputs[0]->get_type() == Variant::INT) {
-
int64_t i = *p_inputs[0];
*r_return = ABS(i);
} else if (p_inputs[0]->get_type() == Variant::FLOAT) {
-
real_t r = *p_inputs[0];
*r_return = Math::abs(r);
} else {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
r_error.expected = Variant::FLOAT;
}
} break;
case VisualScriptBuiltinFunc::MATH_SIGN: {
-
if (p_inputs[0]->get_type() == Variant::INT) {
-
int64_t i = *p_inputs[0];
*r_return = i < 0 ? -1 : (i > 0 ? +1 : 0);
} else if (p_inputs[0]->get_type() == Variant::FLOAT) {
-
real_t r = *p_inputs[0];
*r_return = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
} else {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
r_error.expected = Variant::FLOAT;
}
} break;
case VisualScriptBuiltinFunc::MATH_POW: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
*r_return = Math::pow((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_LOG: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::log((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_EXP: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::exp((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ISNAN: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::is_nan((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ISINF: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::is_inf((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_EASE: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
*r_return = Math::ease((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_STEP_DECIMALS: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::step_decimals((double)*p_inputs[0]);
} break;
- case VisualScriptBuiltinFunc::MATH_STEPIFY: {
-
+ case VisualScriptBuiltinFunc::MATH_SNAPPED: {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
- *r_return = Math::stepify((double)*p_inputs[0], (double)*p_inputs[1]);
+ *r_return = Math::snapped((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_LERP: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
*r_return = Math::lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
case VisualScriptBuiltinFunc::MATH_LERP_ANGLE: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
*r_return = Math::lerp_angle((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
case VisualScriptBuiltinFunc::MATH_INVERSE_LERP: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
*r_return = Math::inverse_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
case VisualScriptBuiltinFunc::MATH_RANGE_LERP: {
-
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
@@ -891,14 +843,12 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
*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);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
@@ -908,27 +858,29 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
Math::randomize();
} break;
- case VisualScriptBuiltinFunc::MATH_RAND: {
+ case VisualScriptBuiltinFunc::MATH_RANDI: {
*r_return = Math::rand();
} break;
case VisualScriptBuiltinFunc::MATH_RANDF: {
*r_return = Math::randf();
} break;
- case VisualScriptBuiltinFunc::MATH_RANDOM: {
-
+ case VisualScriptBuiltinFunc::MATH_RANDF_RANGE: {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
*r_return = Math::random((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
+ case VisualScriptBuiltinFunc::MATH_RANDI_RANGE: {
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ *r_return = Math::random((int)*p_inputs[0], (int)*p_inputs[1]);
+ } break;
case VisualScriptBuiltinFunc::MATH_SEED: {
-
VALIDATE_ARG_NUM(0);
uint64_t seed = *p_inputs[0];
Math::seed(seed);
} break;
case VisualScriptBuiltinFunc::MATH_RANDSEED: {
-
VALIDATE_ARG_NUM(0);
uint64_t seed = *p_inputs[0];
int ret = Math::rand_from_seed(&seed);
@@ -939,22 +891,18 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} break;
case VisualScriptBuiltinFunc::MATH_DEG2RAD: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::deg2rad((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_RAD2DEG: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::rad2deg((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_LINEAR2DB: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::linear2db((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_DB2LINEAR: {
-
VALIDATE_ARG_NUM(0);
*r_return = Math::db2linear((double)*p_inputs[0]);
} break;
@@ -985,9 +933,7 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
*r_return = Math::wrapf((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
case VisualScriptBuiltinFunc::LOGIC_MAX: {
-
if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {
-
int64_t a = *p_inputs[0];
int64_t b = *p_inputs[1];
*r_return = MAX(a, b);
@@ -1003,9 +949,7 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} break;
case VisualScriptBuiltinFunc::LOGIC_MIN: {
-
if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT) {
-
int64_t a = *p_inputs[0];
int64_t b = *p_inputs[1];
*r_return = MIN(a, b);
@@ -1020,9 +964,7 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
}
} break;
case VisualScriptBuiltinFunc::LOGIC_CLAMP: {
-
if (p_inputs[0]->get_type() == Variant::INT && p_inputs[1]->get_type() == Variant::INT && p_inputs[2]->get_type() == Variant::INT) {
-
int64_t a = *p_inputs[0];
int64_t b = *p_inputs[1];
int64_t c = *p_inputs[2];
@@ -1040,15 +982,12 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
}
} break;
case VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2: {
-
VALIDATE_ARG_NUM(0);
int64_t num = *p_inputs[0];
*r_return = next_power_of_2(num);
} break;
case VisualScriptBuiltinFunc::OBJ_WEAKREF: {
-
if (p_inputs[0]->get_type() != Variant::OBJECT) {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
r_error.expected = Variant::OBJECT;
@@ -1057,10 +996,8 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
}
if (p_inputs[0]->is_ref()) {
-
REF r = *p_inputs[0];
if (!r.is_valid()) {
-
return;
}
@@ -1070,7 +1007,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} else {
Object *obj = *p_inputs[0];
if (!obj) {
-
return;
}
Ref<WeakRef> wref = memnew(WeakRef);
@@ -1079,39 +1015,10 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
}
} break;
- case VisualScriptBuiltinFunc::FUNC_FUNCREF: {
-
- if (p_inputs[0]->get_type() != Variant::OBJECT) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 0;
- r_error.expected = Variant::OBJECT;
-
- return;
- }
- if (p_inputs[1]->get_type() != Variant::STRING && p_inputs[1]->get_type() != Variant::NODE_PATH) {
-
- r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument = 1;
- r_error.expected = Variant::STRING;
-
- return;
- }
-
- Ref<FuncRef> fr = memnew(FuncRef);
-
- fr->set_instance(*p_inputs[0]);
- fr->set_function(*p_inputs[1]);
-
- *r_return = fr;
-
- } break;
case VisualScriptBuiltinFunc::TYPE_CONVERT: {
-
VALIDATE_ARG_NUM(1);
int type = *p_inputs[1];
if (type < 0 || type >= Variant::VARIANT_MAX) {
-
r_error_str = RTR("Invalid type argument to convert(), use TYPE_* constants.");
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
@@ -1119,29 +1026,24 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
return;
} else {
-
- *r_return = Variant::construct(Variant::Type(type), p_inputs, 1, r_error);
+ Variant::construct(Variant::Type(type), *r_return, p_inputs, 1, r_error);
}
} break;
case VisualScriptBuiltinFunc::TYPE_OF: {
-
*r_return = p_inputs[0]->get_type();
} break;
case VisualScriptBuiltinFunc::TYPE_EXISTS: {
-
*r_return = ClassDB::class_exists(*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::TEXT_CHAR: {
-
- CharType result[2] = { *p_inputs[0], 0 };
+ char32_t result[2] = { *p_inputs[0], 0 };
*r_return = String(result);
} break;
case VisualScriptBuiltinFunc::TEXT_ORD: {
-
if (p_inputs[0]->get_type() != Variant::STRING) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
@@ -1165,39 +1067,33 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} break;
case VisualScriptBuiltinFunc::TEXT_STR: {
-
String str = *p_inputs[0];
*r_return = str;
} break;
case VisualScriptBuiltinFunc::TEXT_PRINT: {
-
String str = *p_inputs[0];
print_line(str);
} break;
case VisualScriptBuiltinFunc::TEXT_PRINTERR: {
-
String str = *p_inputs[0];
print_error(str);
} break;
case VisualScriptBuiltinFunc::TEXT_PRINTRAW: {
-
String str = *p_inputs[0];
OS::get_singleton()->print("%s", str.utf8().get_data());
} break;
case VisualScriptBuiltinFunc::VAR_TO_STR: {
-
String vars;
VariantWriter::write_to_string(*p_inputs[0], vars);
*r_return = vars;
} break;
case VisualScriptBuiltinFunc::STR_TO_VAR: {
-
if (p_inputs[0]->get_type() != Variant::STRING) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
@@ -1223,7 +1119,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} break;
case VisualScriptBuiltinFunc::VAR_TO_BYTES: {
-
if (p_inputs[1]->get_type() != Variant::BOOL) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 1;
@@ -1250,7 +1145,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
*r_return = barr;
} break;
case VisualScriptBuiltinFunc::BYTES_TO_VAR: {
-
if (p_inputs[0]->get_type() != Variant::PACKED_BYTE_ARRAY) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
r_error.argument = 0;
@@ -1283,7 +1177,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
} break;
case VisualScriptBuiltinFunc::COLORN: {
-
VALIDATE_ARG_NUM(1);
Color color = Color::named(*p_inputs[0]);
@@ -1309,14 +1202,12 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
VisualScriptBuiltinFunc::exec_func(func, p_inputs, p_outputs[0], r_error, r_error_str);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptBuiltinFunc::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceBuiltinFunc *instance = memnew(VisualScriptNodeInstanceBuiltinFunc);
instance->node = this;
instance->instance = p_instance;
@@ -1325,16 +1216,15 @@ VisualScriptNodeInstance *VisualScriptBuiltinFunc::instance(VisualScriptInstance
}
void VisualScriptBuiltinFunc::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_func", "which"), &VisualScriptBuiltinFunc::set_func);
ClassDB::bind_method(D_METHOD("get_func"), &VisualScriptBuiltinFunc::get_func);
String cc;
for (int i = 0; i < FUNC_MAX; i++) {
-
- if (i > 0)
+ if (i > 0) {
cc += ",";
+ }
cc += func_name[i];
}
ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, cc), "set_func", "get_func");
@@ -1364,16 +1254,17 @@ void VisualScriptBuiltinFunc::_bind_methods() {
BIND_ENUM_CONSTANT(MATH_ISINF);
BIND_ENUM_CONSTANT(MATH_EASE);
BIND_ENUM_CONSTANT(MATH_STEP_DECIMALS);
- BIND_ENUM_CONSTANT(MATH_STEPIFY);
+ BIND_ENUM_CONSTANT(MATH_SNAPPED);
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);
+ BIND_ENUM_CONSTANT(MATH_RANDI);
BIND_ENUM_CONSTANT(MATH_RANDF);
- BIND_ENUM_CONSTANT(MATH_RANDOM);
+ BIND_ENUM_CONSTANT(MATH_RANDF_RANGE);
+ BIND_ENUM_CONSTANT(MATH_RANDI_RANGE);
BIND_ENUM_CONSTANT(MATH_SEED);
BIND_ENUM_CONSTANT(MATH_RANDSEED);
BIND_ENUM_CONSTANT(MATH_DEG2RAD);
@@ -1389,7 +1280,6 @@ void VisualScriptBuiltinFunc::_bind_methods() {
BIND_ENUM_CONSTANT(LOGIC_CLAMP);
BIND_ENUM_CONSTANT(LOGIC_NEAREST_PO2);
BIND_ENUM_CONSTANT(OBJ_WEAKREF);
- BIND_ENUM_CONSTANT(FUNC_FUNCREF);
BIND_ENUM_CONSTANT(TYPE_CONVERT);
BIND_ENUM_CONSTANT(TYPE_OF);
BIND_ENUM_CONSTANT(TYPE_EXISTS);
@@ -1411,24 +1301,20 @@ void VisualScriptBuiltinFunc::_bind_methods() {
}
VisualScriptBuiltinFunc::VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func) {
-
this->func = func;
}
VisualScriptBuiltinFunc::VisualScriptBuiltinFunc() {
-
func = MATH_SIN;
}
template <VisualScriptBuiltinFunc::BuiltinFunc func>
static Ref<VisualScriptNode> create_builtin_func_node(const String &p_name) {
-
Ref<VisualScriptBuiltinFunc> node = memnew(VisualScriptBuiltinFunc(func));
return node;
}
void register_visual_script_builtin_func_node() {
-
VisualScriptLanguage::singleton->add_register_func("functions/built_in/sin", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SIN>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/cos", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_COS>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/tan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_TAN>);
@@ -1458,7 +1344,7 @@ void register_visual_script_builtin_func_node() {
VisualScriptLanguage::singleton->add_register_func("functions/built_in/ease", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EASE>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/step_decimals", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_STEP_DECIMALS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/stepify", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_STEPIFY>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/snapped", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SNAPPED>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp_angle", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP_ANGLE>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/inverse_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_INVERSE_LERP>);
@@ -1467,9 +1353,10 @@ void register_visual_script_builtin_func_node() {
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>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/randi", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDI>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/randf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/random", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOM>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/randf_range", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDF_RANGE>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/randi_range", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDI_RANGE>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/seed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SEED>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/randseed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDSEED>);
@@ -1488,7 +1375,6 @@ void register_visual_script_builtin_func_node() {
VisualScriptLanguage::singleton->add_register_func("functions/built_in/nearest_po2", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/weakref", create_builtin_func_node<VisualScriptBuiltinFunc::OBJ_WEAKREF>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/funcref", create_builtin_func_node<VisualScriptBuiltinFunc::FUNC_FUNCREF>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/convert", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_CONVERT>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/typeof", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_OF>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/type_exists", create_builtin_func_node<VisualScriptBuiltinFunc::TYPE_EXISTS>);
diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h
index d950f858d4..eaa2ef41e2 100644
--- a/modules/visual_script/visual_script_builtin_funcs.h
+++ b/modules/visual_script/visual_script_builtin_funcs.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "visual_script.h"
class VisualScriptBuiltinFunc : public VisualScriptNode {
-
GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode);
public:
@@ -64,16 +63,17 @@ public:
MATH_ISINF,
MATH_EASE,
MATH_STEP_DECIMALS,
- MATH_STEPIFY,
+ MATH_SNAPPED,
MATH_LERP,
MATH_INVERSE_LERP,
MATH_RANGE_LERP,
MATH_MOVE_TOWARD,
MATH_DECTIME,
MATH_RANDOMIZE,
- MATH_RAND,
+ MATH_RANDI,
MATH_RANDF,
- MATH_RANDOM,
+ MATH_RANDF_RANGE,
+ MATH_RANDI_RANGE,
MATH_SEED,
MATH_RANDSEED,
MATH_DEG2RAD,
@@ -89,7 +89,6 @@ public:
LOGIC_CLAMP,
LOGIC_NEAREST_PO2,
OBJ_WEAKREF,
- FUNC_FUNCREF,
TYPE_CONVERT,
TYPE_OF,
TYPE_EXISTS,
@@ -123,25 +122,25 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
+ virtual String get_caption() const override;
//virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_category() const override { return "functions"; }
void set_func(BuiltinFunc p_which);
BuiltinFunc get_func();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func);
VisualScriptBuiltinFunc();
diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp
index 9a4076bec4..1e82259e59 100644
--- a/modules/visual_script/visual_script_editor.cpp
+++ b/modules/visual_script/visual_script_editor.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,10 +31,10 @@
#include "visual_script_editor.h"
#include "core/input/input.h"
-#include "core/object.h"
+#include "core/object/class_db.h"
+#include "core/object/script_language.h"
#include "core/os/keyboard.h"
-#include "core/script_language.h"
-#include "core/variant.h"
+#include "core/variant/variant.h"
#include "editor/editor_node.h"
#include "editor/editor_resource_preview.h"
#include "editor/editor_scale.h"
@@ -46,7 +46,6 @@
#ifdef TOOLS_ENABLED
class VisualScriptEditorSignalEdit : public Object {
-
GDCLASS(VisualScriptEditorSignalEdit, Object);
StringName sig;
@@ -62,22 +61,21 @@ protected:
}
void _sig_changed() {
-
_change_notify();
emit_signal("changed");
}
bool _set(const StringName &p_name, const Variant &p_value) {
-
- if (sig == StringName())
+ if (sig == StringName()) {
return false;
+ }
if (p_name == "argument_count") {
-
int new_argc = p_value;
int argc = script->custom_signal_get_argument_count(sig);
- if (argc == new_argc)
+ if (argc == new_argc) {
return true;
+ }
undo_redo->create_action(TTR("Change Signal Arguments"));
@@ -87,9 +85,7 @@ protected:
undo_redo->add_undo_method(script.ptr(), "custom_signal_add_argument", sig, script->custom_signal_get_argument_name(sig, i), script->custom_signal_get_argument_type(sig, i), -1);
}
} else if (new_argc > argc) {
-
for (int i = argc; i < new_argc; i++) {
-
undo_redo->add_do_method(script.ptr(), "custom_signal_add_argument", sig, Variant::NIL, "arg" + itos(i + 1), -1);
undo_redo->add_undo_method(script.ptr(), "custom_signal_remove_argument", sig, argc);
}
@@ -107,7 +103,6 @@ protected:
ERR_FAIL_INDEX_V(idx, script->custom_signal_get_argument_count(sig), false);
String what = String(p_name).get_slice("/", 2);
if (what == "type") {
-
int old_type = script->custom_signal_get_argument_type(sig, idx);
int new_type = p_value;
undo_redo->create_action(TTR("Change Argument Type"));
@@ -119,7 +114,6 @@ protected:
}
if (what == "name") {
-
String old_name = script->custom_signal_get_argument_name(sig, idx);
String new_name = p_value;
undo_redo->create_action(TTR("Change Argument name"));
@@ -134,9 +128,9 @@ protected:
}
bool _get(const StringName &p_name, Variant &r_ret) const {
-
- if (sig == StringName())
+ if (sig == StringName()) {
return false;
+ }
if (p_name == "argument_count") {
r_ret = script->custom_signal_get_argument_count(sig);
@@ -159,9 +153,9 @@ protected:
return false;
}
void _get_property_list(List<PropertyInfo> *p_list) const {
-
- if (sig == StringName())
+ if (sig == StringName()) {
return;
+ }
p_list->push_back(PropertyInfo(Variant::INT, "argument_count", PROPERTY_HINT_RANGE, "0,256"));
String argt = "Variant";
@@ -177,7 +171,6 @@ protected:
public:
void edit(const StringName &p_sig) {
-
sig = p_sig;
_change_notify();
}
@@ -186,7 +179,6 @@ public:
};
class VisualScriptEditorVariableEdit : public Object {
-
GDCLASS(VisualScriptEditorVariableEdit, Object);
StringName var;
@@ -203,20 +195,18 @@ protected:
}
void _var_changed() {
-
_change_notify();
emit_signal("changed");
}
void _var_value_changed() {
-
- _change_notify("value"); //so the whole tree is not redrawn, makes editing smoother in general
+ _change_notify("value"); // So the whole tree is not redrawn, makes editing smoother in general.
emit_signal("changed");
}
bool _set(const StringName &p_name, const Variant &p_value) {
-
- if (var == StringName())
+ if (var == StringName()) {
return false;
+ }
if (String(p_name) == "value") {
undo_redo->create_action(TTR("Set Variable Default Value"));
@@ -232,12 +222,24 @@ protected:
Dictionary d = script->call("get_variable_info", var);
if (String(p_name) == "type") {
-
Dictionary dc = d.duplicate();
dc["type"] = p_value;
undo_redo->create_action(TTR("Set Variable Type"));
undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
+
+ // Setting the default value.
+ Variant::Type type = (Variant::Type)(int)p_value;
+ if (type != Variant::NIL) {
+ Variant default_value;
+ Callable::CallError ce;
+ Variant::construct(type, default_value, nullptr, 0, ce);
+ if (ce.error == Callable::CallError::CALL_OK) {
+ undo_redo->add_do_method(script.ptr(), "set_variable_default_value", var, default_value);
+ undo_redo->add_undo_method(script.ptr(), "set_variable_default_value", var, dc["value"]);
+ }
+ }
+
undo_redo->add_do_method(this, "_var_changed");
undo_redo->add_undo_method(this, "_var_changed");
undo_redo->commit_action();
@@ -245,7 +247,6 @@ protected:
}
if (String(p_name) == "hint") {
-
Dictionary dc = d.duplicate();
dc["hint"] = p_value;
undo_redo->create_action(TTR("Set Variable Type"));
@@ -258,7 +259,6 @@ protected:
}
if (String(p_name) == "hint_string") {
-
Dictionary dc = d.duplicate();
dc["hint_string"] = p_value;
undo_redo->create_action(TTR("Set Variable Type"));
@@ -280,9 +280,9 @@ protected:
}
bool _get(const StringName &p_name, Variant &r_ret) const {
-
- if (var == StringName())
+ if (var == StringName()) {
return false;
+ }
if (String(p_name) == "value") {
r_ret = script->get_variable_default_value(var);
@@ -312,9 +312,9 @@ protected:
return false;
}
void _get_property_list(List<PropertyInfo> *p_list) const {
-
- if (var == StringName())
+ if (var == StringName()) {
return;
+ }
String argt = "Variant";
for (int i = 1; i < Variant::VARIANT_MAX; i++) {
@@ -322,7 +322,7 @@ protected:
}
p_list->push_back(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt));
p_list->push_back(PropertyInfo(script->get_variable_info(var).type, "value", script->get_variable_info(var).hint, script->get_variable_info(var).hint_string, PROPERTY_USAGE_DEFAULT));
- // Update this when PropertyHint changes
+ // Update this when PropertyHint changes.
p_list->push_back(PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_ENUM, "None,Range,ExpRange,Enum,ExpEasing,Length,SpriteFrame,KeyAccel,Flags,Layers2dRender,Layers2dPhysics,Layer3dRender,Layer3dPhysics,File,Dir,GlobalFile,GlobalDir,ResourceType,MultilineText,PlaceholderText,ColorNoAlpha,ImageCompressLossy,ImageCompressLossLess,ObjectId,String,NodePathToEditedNode,MethodOfVariantType,MethodOfBaseType,MethodOfInstance,MethodOfScript,PropertyOfVariantType,PropertyOfBaseType,PropertyOfInstance,PropertyOfScript,ObjectTooBig,NodePathValidTypes"));
p_list->push_back(PropertyInfo(Variant::STRING, "hint_string"));
p_list->push_back(PropertyInfo(Variant::BOOL, "export"));
@@ -330,7 +330,6 @@ protected:
public:
void edit(const StringName &p_var) {
-
var = p_var;
_change_notify();
}
@@ -340,141 +339,256 @@ public:
static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) {
Color color;
- if (dark_theme)
+ if (dark_theme) {
switch (p_type) {
- 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::FLOAT: 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::VECTOR2I: color = Color(0.74, 0.57, 0.95); break;
- case Variant::RECT2: color = Color(0.95, 0.57, 0.65); break;
- case Variant::RECT2I: color = Color(0.95, 0.57, 0.65); break;
- case Variant::VECTOR3: color = Color(0.84, 0.49, 0.93); break;
- case Variant::VECTOR3I: 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::PACKED_BYTE_ARRAY: color = Color(0.67, 0.96, 0.78); break;
- case Variant::PACKED_INT32_ARRAY: color = Color(0.69, 0.86, 0.96); break;
- case Variant::PACKED_FLOAT32_ARRAY: color = Color(0.59, 0.91, 0.97); break;
- case Variant::PACKED_INT64_ARRAY: color = Color(0.69, 0.86, 0.96); break;
- case Variant::PACKED_FLOAT64_ARRAY: color = Color(0.59, 0.91, 0.97); break;
- case Variant::PACKED_STRING_ARRAY: color = Color(0.62, 0.77, 0.95); break;
- case Variant::PACKED_VECTOR2_ARRAY: color = Color(0.82, 0.7, 0.96); break;
- case Variant::PACKED_VECTOR3_ARRAY: color = Color(0.87, 0.61, 0.95); break;
- case Variant::PACKED_COLOR_ARRAY: color = Color(0.91, 1.0, 0.59); 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::FLOAT:
+ 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::VECTOR2I:
+ color = Color(0.74, 0.57, 0.95);
+ break;
+ case Variant::RECT2:
+ color = Color(0.95, 0.57, 0.65);
+ break;
+ case Variant::RECT2I:
+ color = Color(0.95, 0.57, 0.65);
+ break;
+ case Variant::VECTOR3:
+ color = Color(0.84, 0.49, 0.93);
+ break;
+ case Variant::VECTOR3I:
+ 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::PACKED_BYTE_ARRAY:
+ color = Color(0.67, 0.96, 0.78);
+ break;
+ case Variant::PACKED_INT32_ARRAY:
+ color = Color(0.69, 0.86, 0.96);
+ break;
+ case Variant::PACKED_FLOAT32_ARRAY:
+ color = Color(0.59, 0.91, 0.97);
+ break;
+ case Variant::PACKED_INT64_ARRAY:
+ color = Color(0.69, 0.86, 0.96);
+ break;
+ case Variant::PACKED_FLOAT64_ARRAY:
+ color = Color(0.59, 0.91, 0.97);
+ break;
+ case Variant::PACKED_STRING_ARRAY:
+ color = Color(0.62, 0.77, 0.95);
+ break;
+ case Variant::PACKED_VECTOR2_ARRAY:
+ color = Color(0.82, 0.7, 0.96);
+ break;
+ case Variant::PACKED_VECTOR3_ARRAY:
+ color = Color(0.87, 0.61, 0.95);
+ break;
+ case Variant::PACKED_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
+ } else {
switch (p_type) {
- 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::FLOAT: 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::VECTOR2I: color = Color(0.68, 0.46, 0.93); break;
- case Variant::RECT2: color = Color(0.93, 0.46, 0.56); break;
- case Variant::RECT2I: color = Color(0.93, 0.46, 0.56); break;
- case Variant::VECTOR3: color = Color(0.86, 0.42, 0.93); break;
- case Variant::VECTOR3I: 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::PACKED_BYTE_ARRAY: color = Color(0.38, 0.92, 0.6); break;
- case Variant::PACKED_INT32_ARRAY: color = Color(0.38, 0.73, 0.92); break;
- case Variant::PACKED_FLOAT32_ARRAY: color = Color(0.25, 0.83, 0.95); break;
- case Variant::PACKED_INT64_ARRAY: color = Color(0.38, 0.73, 0.92); break;
- case Variant::PACKED_FLOAT64_ARRAY: color = Color(0.25, 0.83, 0.95); break;
- case Variant::PACKED_STRING_ARRAY: color = Color(0.38, 0.62, 0.92); break;
- case Variant::PACKED_VECTOR2_ARRAY: color = Color(0.62, 0.36, 0.92); break;
- case Variant::PACKED_VECTOR3_ARRAY: color = Color(0.79, 0.35, 0.92); break;
- case Variant::PACKED_COLOR_ARRAY: color = Color(0.57, 0.73, 0.0); 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::FLOAT:
+ 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::VECTOR2I:
+ color = Color(0.68, 0.46, 0.93);
+ break;
+ case Variant::RECT2:
+ color = Color(0.93, 0.46, 0.56);
+ break;
+ case Variant::RECT2I:
+ color = Color(0.93, 0.46, 0.56);
+ break;
+ case Variant::VECTOR3:
+ color = Color(0.86, 0.42, 0.93);
+ break;
+ case Variant::VECTOR3I:
+ 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::PACKED_BYTE_ARRAY:
+ color = Color(0.38, 0.92, 0.6);
+ break;
+ case Variant::PACKED_INT32_ARRAY:
+ color = Color(0.38, 0.73, 0.92);
+ break;
+ case Variant::PACKED_FLOAT32_ARRAY:
+ color = Color(0.25, 0.83, 0.95);
+ break;
+ case Variant::PACKED_INT64_ARRAY:
+ color = Color(0.38, 0.73, 0.92);
+ break;
+ case Variant::PACKED_FLOAT64_ARRAY:
+ color = Color(0.25, 0.83, 0.95);
+ break;
+ case Variant::PACKED_STRING_ARRAY:
+ color = Color(0.38, 0.62, 0.92);
+ break;
+ case Variant::PACKED_VECTOR2_ARRAY:
+ color = Color(0.62, 0.36, 0.92);
+ break;
+ case Variant::PACKED_VECTOR3_ARRAY:
+ color = Color(0.79, 0.35, 0.92);
+ break;
+ case Variant::PACKED_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);
}
+ }
return color;
}
void VisualScriptEditor::_update_graph_connections() {
-
graph->clear_connections();
- List<StringName> funcs;
- script->get_function_list(&funcs);
+ List<VisualScript::SequenceConnection> sequence_conns;
+ script->get_sequence_connection_list(&sequence_conns);
- if (funcs.size() <= 0) {
- updating_graph = false;
- return;
+ for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
+ graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0);
}
- for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) {
+ List<VisualScript::DataConnection> data_conns;
+ script->get_data_connection_list(&data_conns);
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(F->get(), &sequence_conns);
+ for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) {
+ VisualScript::DataConnection dc = E->get();
- for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
+ Ref<VisualScriptNode> from_node = script->get_node(E->get().from_node);
+ Ref<VisualScriptNode> to_node = script->get_node(E->get().to_node);
- graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0);
+ if (to_node->has_input_sequence_port()) {
+ dc.to_port++;
}
- List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(F->get(), &data_conns);
-
- for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) {
-
- VisualScript::DataConnection dc = E->get();
+ dc.from_port += from_node->get_output_sequence_port_count();
- Ref<VisualScriptNode> from_node = script->get_node(F->get(), E->get().from_node);
- Ref<VisualScriptNode> to_node = script->get_node(F->get(), E->get().to_node);
-
- if (to_node->has_input_sequence_port()) {
- dc.to_port++;
- }
-
- dc.from_port += from_node->get_output_sequence_port_count();
-
- graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port);
- }
+ graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port);
}
}
void VisualScriptEditor::_update_graph(int p_only_id) {
-
- if (updating_graph)
+ if (updating_graph) {
return;
+ }
updating_graph = true;
@@ -482,30 +596,18 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
if (p_only_id >= 0) {
if (graph->has_node(itos(p_only_id))) {
Node *gid = graph->get_node(itos(p_only_id));
- if (gid)
+ if (gid) {
memdelete(gid);
+ }
}
} else {
-
for (int i = 0; i < graph->get_child_count(); i++) {
-
if (Object::cast_to<GraphNode>(graph->get_child(i))) {
memdelete(graph->get_child(i));
i--;
}
}
}
-
- List<StringName> funcs;
- script->get_function_list(&funcs);
-
- if (funcs.size() <= 0) {
- graph->hide();
- select_func_text->show();
- updating_graph = false;
- return;
- }
-
graph->show();
select_func_text->hide();
@@ -545,358 +647,350 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
};
Ref<Texture2D> seq_port = Control::get_theme_icon("VisualShaderPort", "EditorIcons");
+ List<int> node_ids;
+ script->get_node_list(&node_ids);
- for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) { // loop through all the functions
-
- List<int> ids;
- script->get_node_list(F->get(), &ids);
- StringName editor_icons = "EditorIcons";
+ List<int> ids;
+ script->get_node_list(&ids);
+ StringName editor_icons = "EditorIcons";
- for (List<int>::Element *E = ids.front(); E; E = E->next()) {
-
- if (p_only_id >= 0 && p_only_id != E->get())
- continue;
+ for (List<int>::Element *E = ids.front(); E; E = E->next()) {
+ if (p_only_id >= 0 && p_only_id != E->get()) {
+ continue;
+ }
- Ref<VisualScriptNode> node = script->get_node(F->get(), E->get());
- Vector2 pos = script->get_node_position(F->get(), E->get());
+ Ref<VisualScriptNode> node = script->get_node(E->get());
+ Vector2 pos = script->get_node_position(E->get());
- GraphNode *gnode = memnew(GraphNode);
- gnode->set_title(node->get_caption());
- gnode->set_offset(pos * EDSCALE);
- if (error_line == E->get()) {
- gnode->set_overlay(GraphNode::OVERLAY_POSITION);
- } else if (node->is_breakpoint()) {
- gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT);
- }
+ GraphNode *gnode = memnew(GraphNode);
+ gnode->set_title(node->get_caption());
+ gnode->set_position_offset(pos * EDSCALE);
+ if (error_line == E->get()) {
+ gnode->set_overlay(GraphNode::OVERLAY_POSITION);
+ } else if (node->is_breakpoint()) {
+ gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT);
+ }
- gnode->set_meta("__vnode", node);
- gnode->set_name(itos(E->get()));
- gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E->get()));
- gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E->get()), CONNECT_DEFERRED);
+ gnode->set_meta("__vnode", node);
+ gnode->set_name(itos(E->get()));
+ gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E->get()));
+ gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E->get()), CONNECT_DEFERRED);
- if (E->get() != script->get_function_node_id(F->get())) {
- //function can't be erased
+ {
+ Ref<VisualScriptFunction> v = node;
+ if (!v.is_valid()) {
gnode->set_show_close_button(true);
}
+ }
- bool has_gnode_text = false;
+ bool has_gnode_text = false;
- Ref<VisualScriptLists> nd_list = node;
- bool is_vslist = nd_list.is_valid();
- if (is_vslist) {
- HBoxContainer *hbnc = memnew(HBoxContainer);
+ Ref<VisualScriptLists> nd_list = node;
+ bool is_vslist = nd_list.is_valid();
+ if (is_vslist) {
+ HBoxContainer *hbnc = memnew(HBoxContainer);
+ if (nd_list->is_input_port_editable()) {
+ has_gnode_text = true;
+ Button *btn = memnew(Button);
+ btn->set_text(TTR("Add Input Port"));
+ hbnc->add_child(btn);
+ btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E->get()), CONNECT_DEFERRED);
+ }
+ if (nd_list->is_output_port_editable()) {
if (nd_list->is_input_port_editable()) {
- has_gnode_text = true;
- Button *btn = memnew(Button);
- btn->set_text(TTR("Add Input Port"));
- hbnc->add_child(btn);
- btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E->get()), CONNECT_DEFERRED);
- }
- if (nd_list->is_output_port_editable()) {
- if (nd_list->is_input_port_editable())
- hbnc->add_spacer();
- has_gnode_text = true;
- Button *btn = memnew(Button);
- btn->set_text(TTR("Add Output Port"));
- hbnc->add_child(btn);
- btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E->get()), CONNECT_DEFERRED);
+ hbnc->add_spacer();
}
- gnode->add_child(hbnc);
- } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) {
has_gnode_text = true;
- LineEdit *line_edit = memnew(LineEdit);
- line_edit->set_text(node->get_text());
- line_edit->set_expand_to_text_length(true);
- line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts"));
- gnode->add_child(line_edit);
- line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get()));
- } else {
- String text = node->get_text();
- if (!text.empty()) {
- has_gnode_text = true;
- Label *label = memnew(Label);
- label->set_text(text);
- gnode->add_child(label);
- }
+ Button *btn = memnew(Button);
+ btn->set_text(TTR("Add Output Port"));
+ hbnc->add_child(btn);
+ btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E->get()), CONNECT_DEFERRED);
+ }
+ gnode->add_child(hbnc);
+ } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) {
+ has_gnode_text = true;
+ LineEdit *line_edit = memnew(LineEdit);
+ line_edit->set_text(node->get_text());
+ line_edit->set_expand_to_text_length(true);
+ line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts"));
+ gnode->add_child(line_edit);
+ line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get()));
+ } else {
+ String text = node->get_text();
+ if (!text.is_empty()) {
+ has_gnode_text = true;
+ Label *label = memnew(Label);
+ label->set_text(text);
+ gnode->add_child(label);
}
+ }
+
+ if (Object::cast_to<VisualScriptComment>(node.ptr())) {
+ Ref<VisualScriptComment> vsc = node;
+ gnode->set_comment(true);
+ gnode->set_resizable(true);
+ gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE);
+ gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E->get()));
+ }
- if (Object::cast_to<VisualScriptComment>(node.ptr())) {
- Ref<VisualScriptComment> vsc = node;
- gnode->set_comment(true);
- gnode->set_resizable(true);
- gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE);
- gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E->get()));
+ if (node_styles.has(node->get_category())) {
+ Ref<StyleBoxFlat> sbf = node_styles[node->get_category()];
+ if (gnode->is_comment()) {
+ sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode");
}
- if (node_styles.has(node->get_category())) {
- Ref<StyleBoxFlat> sbf = node_styles[node->get_category()];
- if (gnode->is_comment())
- sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode");
-
- Color c = sbf->get_border_color();
- Color ic = c;
- c.a = 1;
- if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) {
- Color mono_color;
- if (((c.r + c.g + c.b) / 3) < 0.7) {
- mono_color = Color(1.0, 1.0, 1.0);
- ic = Color(0.0, 0.0, 0.0, 0.7);
- } else {
- mono_color = Color(0.0, 0.0, 0.0);
- ic = Color(1.0, 1.0, 1.0, 0.7);
- }
- mono_color.a = 0.85;
- c = mono_color;
+ Color c = sbf->get_border_color();
+ Color ic = c;
+ c.a = 1;
+ if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) {
+ Color mono_color;
+ if (((c.r + c.g + c.b) / 3) < 0.7) {
+ mono_color = Color(1.0, 1.0, 1.0);
+ ic = Color(0.0, 0.0, 0.0, 0.7);
+ } else {
+ mono_color = Color(0.0, 0.0, 0.0);
+ ic = Color(1.0, 1.0, 1.0, 0.7);
}
- gnode->add_theme_color_override("title_color", c);
- c.a = 0.7;
- gnode->add_theme_color_override("close_color", c);
- gnode->add_theme_color_override("resizer_color", ic);
- gnode->add_theme_style_override("frame", sbf);
+ mono_color.a = 0.85;
+ c = mono_color;
}
+ gnode->add_theme_color_override("title_color", c);
+ c.a = 0.7;
+ gnode->add_theme_color_override("close_color", c);
+ gnode->add_theme_color_override("resizer_color", ic);
+ gnode->add_theme_style_override("frame", sbf);
+ }
- const Color mono_color = get_theme_color("mono_color", "Editor");
+ const Color mono_color = get_theme_color("mono_color", "Editor");
- int slot_idx = 0;
+ int slot_idx = 0;
- bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String();
- if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) {
- // IF has_gnode_text is true BUT we have no sequence ports to draw (in here),
- // we still draw the disabled default ones to shift up the slots by one,
- // so the slots DON'T start with the content text.
+ bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String();
+ if ((node->has_input_sequence_port() || single_seq_output) || has_gnode_text) {
+ // IF has_gnode_text is true BUT we have no sequence ports to draw (in here),
+ // we still draw the disabled default ones to shift up the slots by one,
+ // so the slots DON'T start with the content text.
- // IF has_gnode_text is false, but we DO want to draw default sequence ports,
- // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly.
- if (!has_gnode_text) {
- Label *dummy = memnew(Label);
- dummy->set_text(" ");
- gnode->add_child(dummy);
- }
- gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
- slot_idx++;
+ // IF has_gnode_text is false, but we DO want to draw default sequence ports,
+ // we draw a dummy text to take up the position of the sequence nodes, so all the other ports are still aligned correctly.
+ if (!has_gnode_text) {
+ Label *dummy = memnew(Label);
+ dummy->set_text(" ");
+ gnode->add_child(dummy);
}
+ gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, mono_color, single_seq_output, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
+ slot_idx++;
+ }
- int mixed_seq_ports = 0;
-
- if (!single_seq_output) {
+ int mixed_seq_ports = 0;
- if (node->has_mixed_input_and_sequence_ports()) {
- mixed_seq_ports = node->get_output_sequence_port_count();
- } else {
- for (int i = 0; i < node->get_output_sequence_port_count(); i++) {
-
- Label *text2 = memnew(Label);
- text2->set_text(node->get_output_sequence_port_text(i));
- text2->set_align(Label::ALIGN_RIGHT);
- gnode->add_child(text2);
- gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
- slot_idx++;
- }
+ if (!single_seq_output) {
+ if (node->has_mixed_input_and_sequence_ports()) {
+ mixed_seq_ports = node->get_output_sequence_port_count();
+ } else {
+ for (int i = 0; i < node->get_output_sequence_port_count(); i++) {
+ Label *text2 = memnew(Label);
+ text2->set_text(node->get_output_sequence_port_text(i));
+ text2->set_align(Label::ALIGN_RIGHT);
+ gnode->add_child(text2);
+ gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, mono_color, seq_port, seq_port);
+ slot_idx++;
}
}
+ }
- for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) {
-
- bool left_ok = false;
- Variant::Type left_type = Variant::NIL;
- String left_name;
+ for (int i = 0; i < MAX(node->get_output_value_port_count(), MAX(mixed_seq_ports, node->get_input_value_port_count())); i++) {
+ bool left_ok = false;
+ Variant::Type left_type = Variant::NIL;
+ String left_name;
- if (i < node->get_input_value_port_count()) {
- PropertyInfo pi = node->get_input_value_port_info(i);
- left_ok = true;
- left_type = pi.type;
- left_name = pi.name;
- }
+ if (i < node->get_input_value_port_count()) {
+ PropertyInfo pi = node->get_input_value_port_info(i);
+ left_ok = true;
+ left_type = pi.type;
+ left_name = pi.name;
+ }
- bool right_ok = false;
- Variant::Type right_type = Variant::NIL;
- String right_name;
+ bool right_ok = false;
+ Variant::Type right_type = Variant::NIL;
+ String right_name;
- if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) {
- PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports);
- right_ok = true;
- right_type = pi.type;
- right_name = pi.name;
+ if (i >= mixed_seq_ports && i < node->get_output_value_port_count() + mixed_seq_ports) {
+ PropertyInfo pi = node->get_output_value_port_info(i - mixed_seq_ports);
+ right_ok = true;
+ right_type = pi.type;
+ right_name = pi.name;
+ }
+ VBoxContainer *vbc = memnew(VBoxContainer);
+ HBoxContainer *hbc = memnew(HBoxContainer);
+ HBoxContainer *hbc2 = memnew(HBoxContainer);
+ vbc->add_child(hbc);
+ vbc->add_child(hbc2);
+ if (left_ok) {
+ Ref<Texture2D> t;
+ if (left_type >= 0 && left_type < Variant::VARIANT_MAX) {
+ t = type_icons[left_type];
+ }
+ if (t.is_valid()) {
+ TextureRect *tf = memnew(TextureRect);
+ tf->set_texture(t);
+ tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
+ hbc->add_child(tf);
}
- VBoxContainer *vbc = memnew(VBoxContainer);
- HBoxContainer *hbc = memnew(HBoxContainer);
- HBoxContainer *hbc2 = memnew(HBoxContainer);
- vbc->add_child(hbc);
- vbc->add_child(hbc2);
- if (left_ok) {
-
- Ref<Texture2D> t;
- if (left_type >= 0 && left_type < Variant::VARIANT_MAX) {
- t = type_icons[left_type];
- }
- if (t.is_valid()) {
- TextureRect *tf = memnew(TextureRect);
- tf->set_texture(t);
- tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
- hbc->add_child(tf);
- }
-
- if (is_vslist) {
- if (nd_list->is_input_port_name_editable()) {
- LineEdit *name_box = memnew(LineEdit);
- hbc->add_child(name_box);
- name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
- name_box->set_text(left_name);
- name_box->set_expand_to_text_length(true);
- name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get()));
- name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, true));
- } else {
- hbc->add_child(memnew(Label(left_name)));
- }
-
- if (nd_list->is_input_port_type_editable()) {
- OptionButton *opbtn = memnew(OptionButton);
- for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
- opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
- }
- opbtn->select(left_type);
- opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
- hbc->add_child(opbtn);
- opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, true), CONNECT_DEFERRED);
- }
- Button *rmbtn = memnew(Button);
- rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons"));
- hbc->add_child(rmbtn);
- rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E->get(), i), CONNECT_DEFERRED);
+ if (is_vslist) {
+ if (nd_list->is_input_port_name_editable()) {
+ LineEdit *name_box = memnew(LineEdit);
+ hbc->add_child(name_box);
+ name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
+ name_box->set_text(left_name);
+ name_box->set_expand_to_text_length(true);
+ name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get()));
+ name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, true));
} else {
hbc->add_child(memnew(Label(left_name)));
}
- if (left_type != Variant::NIL && !script->is_input_value_port_connected(F->get(), E->get(), i)) {
-
- PropertyInfo pi = node->get_input_value_port_info(i);
- Button *button = memnew(Button);
- Variant value = node->get_default_input_value(i);
- if (value.get_type() != left_type) {
- //different type? for now convert
- //not the same, reconvert
- Callable::CallError ce;
- const Variant *existingp = &value;
- value = Variant::construct(left_type, &existingp, 1, ce, false);
- }
-
- if (left_type == Variant::COLOR) {
- button->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
- button->connect("draw", callable_mp(this, &VisualScriptEditor::_draw_color_over_button), varray(button, value));
- } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) {
-
- Ref<Resource> res = value;
- Array arr;
- arr.push_back(button->get_instance_id());
- arr.push_back(String(value));
- EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr);
-
- } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) {
-
- button->set_text(pi.hint_string.get_slice(",", value));
- } else {
-
- button->set_text(value);
+ if (nd_list->is_input_port_type_editable()) {
+ OptionButton *opbtn = memnew(OptionButton);
+ for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
+ opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
}
- button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E->get(), i));
- hbc2->add_child(button);
+ opbtn->select(left_type);
+ opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
+ hbc->add_child(opbtn);
+ opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, true), CONNECT_DEFERRED);
}
+
+ Button *rmbtn = memnew(Button);
+ rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons"));
+ hbc->add_child(rmbtn);
+ rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E->get(), i), CONNECT_DEFERRED);
} else {
- Control *c = memnew(Control);
- c->set_custom_minimum_size(Size2(10, 0) * EDSCALE);
- hbc->add_child(c);
+ hbc->add_child(memnew(Label(left_name)));
}
- hbc->add_spacer();
- hbc2->add_spacer();
-
- if (i < mixed_seq_ports) {
+ if (left_type != Variant::NIL && !script->is_input_value_port_connected(E->get(), i)) {
+ PropertyInfo pi = node->get_input_value_port_info(i);
+ Button *button = memnew(Button);
+ Variant value = node->get_default_input_value(i);
+ if (value.get_type() != left_type) {
+ //different type? for now convert
+ //not the same, reconvert
+ Callable::CallError ce;
+ const Variant *existingp = &value;
+ Variant::construct(left_type, value, &existingp, 1, ce);
+ }
- Label *text2 = memnew(Label);
- text2->set_text(node->get_output_sequence_port_text(i));
- text2->set_align(Label::ALIGN_RIGHT);
- hbc->add_child(text2);
+ if (left_type == Variant::COLOR) {
+ button->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
+ button->connect("draw", callable_mp(this, &VisualScriptEditor::_draw_color_over_button), varray(button, value));
+ } else if (left_type == Variant::OBJECT && Ref<Resource>(value).is_valid()) {
+ Ref<Resource> res = value;
+ Array arr;
+ arr.push_back(button->get_instance_id());
+ arr.push_back(String(value));
+ EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr);
+
+ } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) {
+ button->set_text(pi.hint_string.get_slice(",", value));
+ } else {
+ button->set_text(value);
+ }
+ button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E->get(), i));
+ hbc2->add_child(button);
}
+ } else {
+ Control *c = memnew(Control);
+ c->set_custom_minimum_size(Size2(10, 0) * EDSCALE);
+ hbc->add_child(c);
+ }
- if (right_ok) {
+ hbc->add_spacer();
+ hbc2->add_spacer();
- if (is_vslist) {
- Button *rmbtn = memnew(Button);
- rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons"));
- hbc->add_child(rmbtn);
- rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E->get(), i), CONNECT_DEFERRED);
+ if (i < mixed_seq_ports) {
+ Label *text2 = memnew(Label);
+ text2->set_text(node->get_output_sequence_port_text(i));
+ text2->set_align(Label::ALIGN_RIGHT);
+ hbc->add_child(text2);
+ }
- if (nd_list->is_output_port_type_editable()) {
- OptionButton *opbtn = memnew(OptionButton);
- for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
- opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
- }
- opbtn->select(right_type);
- opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
- hbc->add_child(opbtn);
- opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, false), CONNECT_DEFERRED);
+ if (right_ok) {
+ if (is_vslist) {
+ Button *rmbtn = memnew(Button);
+ rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons"));
+ hbc->add_child(rmbtn);
+ rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E->get(), i), CONNECT_DEFERRED);
+
+ if (nd_list->is_output_port_type_editable()) {
+ OptionButton *opbtn = memnew(OptionButton);
+ for (int j = Variant::NIL; j < Variant::VARIANT_MAX; j++) {
+ opbtn->add_item(Variant::get_type_name(Variant::Type(j)));
}
+ opbtn->select(right_type);
+ opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
+ hbc->add_child(opbtn);
+ opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, false), CONNECT_DEFERRED);
+ }
- if (nd_list->is_output_port_name_editable()) {
- LineEdit *name_box = memnew(LineEdit);
- hbc->add_child(name_box);
- name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
- name_box->set_text(right_name);
- name_box->set_expand_to_text_length(true);
- name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get()));
- name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, false));
- } else {
- hbc->add_child(memnew(Label(right_name)));
- }
+ if (nd_list->is_output_port_name_editable()) {
+ LineEdit *name_box = memnew(LineEdit);
+ hbc->add_child(name_box);
+ name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0));
+ name_box->set_text(right_name);
+ name_box->set_expand_to_text_length(true);
+ name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get()));
+ name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, false));
} else {
hbc->add_child(memnew(Label(right_name)));
}
-
- Ref<Texture2D> t;
- if (right_type >= 0 && right_type < Variant::VARIANT_MAX) {
- t = type_icons[right_type];
- }
- if (t.is_valid()) {
- TextureRect *tf = memnew(TextureRect);
- tf->set_texture(t);
- tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
- hbc->add_child(tf);
- }
- }
-
- gnode->add_child(vbc);
-
- bool dark_theme = get_theme_constant("dark_theme", "Editor");
- if (i < mixed_seq_ports) {
- gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port);
} else {
- gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme));
+ hbc->add_child(memnew(Label(right_name)));
}
- slot_idx++;
+ Ref<Texture2D> t;
+ if (right_type >= 0 && right_type < Variant::VARIANT_MAX) {
+ t = type_icons[right_type];
+ }
+ if (t.is_valid()) {
+ TextureRect *tf = memnew(TextureRect);
+ tf->set_texture(t);
+ tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
+ hbc->add_child(tf);
+ }
}
- graph->add_child(gnode);
+ gnode->add_child(vbc);
- if (gnode->is_comment()) {
- graph->move_child(gnode, 0);
+ bool dark_theme = get_theme_constant("dark_theme", "Editor");
+ if (i < mixed_seq_ports) {
+ gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port);
+ } else {
+ gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), right_ok, right_type, _color_from_type(right_type, dark_theme));
}
+
+ slot_idx++;
+ }
+
+ graph->add_child(gnode);
+
+ if (gnode->is_comment()) {
+ graph->move_child(gnode, 0);
}
}
+
_update_graph_connections();
- // use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything
- graph->call_deferred("set_scroll_ofs", script->get_function_scroll(default_func) * EDSCALE);
+ // Use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything.
+ graph->call_deferred("set_scroll_ofs", script->get_scroll() * EDSCALE);
updating_graph = false;
}
void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, bool is_input) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
undo_redo->create_action("Change Port Type");
if (is_input) {
@@ -910,24 +1004,25 @@ void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, b
}
void VisualScriptEditor::_update_node_size(int p_id) {
-
Node *node = graph->get_node(itos(p_id));
- if (Object::cast_to<Control>(node))
- Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller
+ if (Object::cast_to<Control>(node)) {
+ Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); // Shrink if text is smaller.
+ }
}
-void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input) {
- StringName func = _get_function_of_node(p_id);
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input) {
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
String text;
- if (Object::cast_to<LineEdit>(p_name_box))
+ if (Object::cast_to<LineEdit>(p_name_box)) {
text = Object::cast_to<LineEdit>(p_name_box)->get_text();
- else
+ } else {
return;
+ }
undo_redo->create_action("Change Port Name");
if (is_input) {
@@ -957,19 +1052,16 @@ void VisualScriptEditor::_update_members() {
List<StringName> func_names;
script->get_function_list(&func_names);
+ func_names.sort_custom<StringName::AlphCompare>();
for (List<StringName>::Element *E = func_names.front(); E; E = E->next()) {
-
- if (E->get() == default_func) {
- continue;
- }
-
TreeItem *ti = members->create_item(functions);
ti->set_text(0, E->get());
ti->set_selectable(0, true);
ti->set_metadata(0, E->get());
ti->add_button(0, Control::get_theme_icon("Edit", "EditorIcons"), 0);
- if (selected == E->get())
+ if (selected == E->get()) {
ti->select(0);
+ }
}
TreeItem *variables = members->create_item(root);
@@ -1019,15 +1111,16 @@ void VisualScriptEditor::_update_members() {
TreeItem *ti = members->create_item(variables);
ti->set_text(0, E->get());
- Variant var = script->get_variable_default_value(E->get());
- ti->set_suffix(0, "= " + String(var));
+
+ ti->set_suffix(0, "= " + _sanitized_variant_text(E->get()));
ti->set_icon(0, type_icons[script->get_variable_info(E->get()).type]);
ti->set_selectable(0, true);
ti->set_editable(0, true);
ti->set_metadata(0, E->get());
- if (selected == E->get())
+ if (selected == E->get()) {
ti->select(0);
+ }
}
TreeItem *_signals = members->create_item(root);
@@ -1044,8 +1137,9 @@ void VisualScriptEditor::_update_members() {
ti->set_selectable(0, true);
ti->set_editable(0, true);
ti->set_metadata(0, E->get());
- if (selected == E->get())
+ if (selected == E->get()) {
ti->select(0);
+ }
}
String base_type = script->get_instance_base_type();
@@ -1060,10 +1154,24 @@ void VisualScriptEditor::_update_members() {
updating_members = false;
}
-void VisualScriptEditor::_member_selected() {
+String VisualScriptEditor::_sanitized_variant_text(const StringName &property_name) {
+ Variant var = script->get_variable_default_value(property_name);
+
+ if (script->get_variable_info(property_name).type != Variant::NIL) {
+ Callable::CallError ce;
+ const Variant *converted = &var;
+ Variant n;
+ Variant::construct(script->get_variable_info(property_name).type, n, &converted, 1, ce);
+ var = n;
+ }
+
+ return String(var);
+}
- if (updating_members)
+void VisualScriptEditor::_member_selected() {
+ if (updating_members) {
return;
+ }
TreeItem *ti = members->get_selected();
ERR_FAIL_COND(!ti);
@@ -1071,7 +1179,6 @@ void VisualScriptEditor::_member_selected() {
selected = ti->get_metadata(0);
if (ti->get_parent() == members->get_root()->get_children()) {
-
#ifdef OSX_ENABLED
bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_META);
#else
@@ -1079,15 +1186,15 @@ void VisualScriptEditor::_member_selected() {
#endif
if (held_ctrl) {
ERR_FAIL_COND(!script->has_function(selected));
- _center_on_node(selected, script->get_function_node_id(selected));
+ _center_on_node(script->get_function_node_id(selected));
}
}
}
void VisualScriptEditor::_member_edited() {
-
- if (updating_members)
+ if (updating_members) {
return;
+ }
TreeItem *ti = members->get_edited();
ERR_FAIL_COND(!ti);
@@ -1095,11 +1202,11 @@ void VisualScriptEditor::_member_edited() {
String name = ti->get_metadata(0);
String new_name = ti->get_text(0);
- if (name == new_name)
+ if (name == new_name) {
return;
+ }
if (!new_name.is_valid_identifier()) {
-
EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name);
updating_members = true;
ti->set_text(0, name);
@@ -1108,7 +1215,6 @@ void VisualScriptEditor::_member_edited() {
}
if (script->has_function(new_name) || script->has_variable(new_name) || script->has_custom_signal(new_name)) {
-
EditorNode::get_singleton()->show_warning(TTR("Name already in use by another func/var/signal:") + " " + new_name);
updating_members = true;
ti->set_text(0, name);
@@ -1119,13 +1225,12 @@ void VisualScriptEditor::_member_edited() {
TreeItem *root = members->get_root();
if (ti->get_parent() == root->get_children()) {
-
selected = new_name;
int node_id = script->get_function_node_id(name);
Ref<VisualScriptFunction> func;
- if (script->has_node(name, node_id)) {
- func = script->get_node(name, node_id);
+ if (script->has_node(node_id)) {
+ func = script->get_node(node_id);
}
undo_redo->create_action(TTR("Rename Function"));
undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name);
@@ -1135,20 +1240,17 @@ void VisualScriptEditor::_member_edited() {
undo_redo->add_undo_method(func.ptr(), "set_name", name);
}
- // also fix all function calls
- List<StringName> flst;
- script->get_function_list(&flst);
- for (List<StringName>::Element *E = flst.front(); E; E = E->next()) {
- List<int> lst;
- script->get_node_list(E->get(), &lst);
- for (List<int>::Element *F = lst.front(); F; F = F->next()) {
- Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get());
- if (!fncall.is_valid())
- continue;
- if (fncall->get_function() == name) {
- undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
- undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
- }
+ // Also fix all function calls.
+ List<int> lst;
+ script->get_node_list(&lst);
+ for (List<int>::Element *F = lst.front(); F; F = F->next()) {
+ Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get());
+ if (!fncall.is_valid()) {
+ continue;
+ }
+ if (fncall->get_function() == name) {
+ undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
+ undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
}
}
@@ -1160,11 +1262,10 @@ void VisualScriptEditor::_member_edited() {
undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
undo_redo->commit_action();
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
if (ti->get_parent() == root->get_children()->get_next()) {
-
selected = new_name;
undo_redo->create_action(TTR("Rename Variable"));
undo_redo->add_do_method(script.ptr(), "rename_variable", name, new_name);
@@ -1177,11 +1278,10 @@ void VisualScriptEditor::_member_edited() {
undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
undo_redo->commit_action();
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
if (ti->get_parent() == root->get_children()->get_next()->get_next()) {
-
selected = new_name;
undo_redo->create_action(TTR("Rename Signal"));
undo_redo->add_do_method(script.ptr(), "rename_custom_signal", name, new_name);
@@ -1192,7 +1292,7 @@ void VisualScriptEditor::_member_edited() {
undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
undo_redo->commit_action();
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
}
@@ -1218,17 +1318,21 @@ void VisualScriptEditor::_create_function() {
for (int i = 0; i < func_input_vbox->get_child_count(); i++) {
OptionButton *opbtn = Object::cast_to<OptionButton>(func_input_vbox->get_child(i)->get_child(3));
LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1));
- if (!opbtn || !lne)
+ if (!opbtn || !lne) {
continue;
+ }
Variant::Type arg_type = Variant::Type(opbtn->get_selected());
String arg_name = lne->get_text();
func_node->add_argument(arg_type, arg_name);
}
+ int func_node_id = script->get_available_id();
+
undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name);
- undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_function", name, func_node_id);
undo_redo->add_undo_method(script.ptr(), "remove_function", name);
+ undo_redo->add_do_method(script.ptr(), "add_node", func_node_id, func_node, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", func_node_id);
undo_redo->add_do_method(this, "_update_members");
undo_redo->add_undo_method(this, "_update_members");
undo_redo->add_do_method(this, "_update_graph");
@@ -1264,8 +1368,9 @@ void VisualScriptEditor::_add_func_input() {
OptionButton *type_box = memnew(OptionButton);
type_box->set_custom_minimum_size(Size2(120 * EDSCALE, 0));
- for (int i = Variant::NIL; i < Variant::VARIANT_MAX; i++)
+ for (int i = Variant::NIL; i < Variant::VARIANT_MAX; i++) {
type_box->add_item(Variant::get_type_name(Variant::Type(i)));
+ }
type_box->select(1);
hbox->add_child(type_box);
@@ -1297,13 +1402,13 @@ void VisualScriptEditor::_deselect_input_names() {
int cn = func_input_vbox->get_child_count();
for (int i = 0; i < cn; i++) {
LineEdit *lne = Object::cast_to<LineEdit>(func_input_vbox->get_child(i)->get_child(1));
- if (lne)
+ if (lne) {
lne->deselect();
+ }
}
}
void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_button) {
-
TreeItem *ti = Object::cast_to<TreeItem>(p_item);
TreeItem *root = members->get_root();
@@ -1311,14 +1416,14 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
if (ti->get_parent() == root) {
//main buttons
if (ti == root->get_children()) {
- //add function, this one uses menu
+ // Add function, this one uses menu.
if (p_button == 1) {
+ // Ensure script base exists otherwise use custom base type.
+ ERR_FAIL_COND(script.is_null());
new_virtual_method_select->select_method_from_base_type(script->get_instance_base_type(), String(), true);
-
return;
} else if (p_button == 0) {
-
String name = _validate_name("new_function");
selected = name;
Vector2 ofs = _get_available_pos();
@@ -1326,11 +1431,13 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
Ref<VisualScriptFunction> func_node;
func_node.instance();
func_node->set_name(name);
+ int fn_id = script->get_available_id();
undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name);
- undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs);
undo_redo->add_undo_method(script.ptr(), "remove_function", name);
+ undo_redo->add_do_method(script.ptr(), "remove_node", fn_id);
undo_redo->add_do_method(this, "_update_members");
undo_redo->add_undo_method(this, "_update_members");
undo_redo->add_do_method(this, "_update_graph");
@@ -1342,11 +1449,11 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
_update_graph();
}
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
if (ti == root->get_children()->get_next()) {
- //add variable
+ // Add variable.
String name = _validate_name("new_variable");
selected = name;
@@ -1358,11 +1465,11 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
undo_redo->commit_action();
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
if (ti == root->get_children()->get_next()->get_next()) {
- //add variable
+ // Add variable.
String name = _validate_name("new_signal");
selected = name;
@@ -1374,7 +1481,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
undo_redo->commit_action();
- return; //or crash because it will become invalid
+ return; // Or crash because it will become invalid.
}
} else if (ti->get_parent() == root->get_children()) {
selected = ti->get_text(0);
@@ -1386,12 +1493,10 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
}
void VisualScriptEditor::_add_input_port(int p_id) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
updating_graph = true;
@@ -1408,12 +1513,10 @@ void VisualScriptEditor::_add_input_port(int p_id) {
}
void VisualScriptEditor::_add_output_port(int p_id) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
updating_graph = true;
@@ -1430,28 +1533,28 @@ void VisualScriptEditor::_add_output_port(int p_id) {
}
void VisualScriptEditor::_remove_input_port(int p_id, int p_port) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
updating_graph = true;
undo_redo->create_action(TTR("Remove Input Port"), UndoRedo::MERGE_ENDS);
int conn_from = -1, conn_port = -1;
- script->get_input_value_port_connection_source(func, p_id, p_port, &conn_from, &conn_port);
+ script->get_input_value_port_connection_source(p_id, p_port, &conn_from, &conn_port);
- if (conn_from != -1)
- undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_id, p_port);
+ if (conn_from != -1) {
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_id, p_port);
+ }
undo_redo->add_do_method(vsn.ptr(), "remove_input_data_port", p_port);
undo_redo->add_do_method(this, "_update_graph", p_id);
- if (conn_from != -1)
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_id, p_port);
+ if (conn_from != -1) {
+ undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_id, p_port);
+ }
undo_redo->add_undo_method(vsn.ptr(), "add_input_data_port", vsn->get_input_value_port_info(p_port).type, vsn->get_input_value_port_info(p_port).name, p_port);
undo_redo->add_undo_method(this, "_update_graph", p_id);
@@ -1462,26 +1565,25 @@ void VisualScriptEditor::_remove_input_port(int p_id, int p_port) {
}
void VisualScriptEditor::_remove_output_port(int p_id, int p_port) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptLists> vsn = script->get_node(func, p_id);
- if (!vsn.is_valid())
+ Ref<VisualScriptLists> vsn = script->get_node(p_id);
+ if (!vsn.is_valid()) {
return;
+ }
updating_graph = true;
undo_redo->create_action(TTR("Remove Output Port"), UndoRedo::MERGE_ENDS);
List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(func, &data_connections);
+ script->get_data_connection_list(&data_connections);
HashMap<int, Set<int>> conn_map;
for (const List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
if (E->get().from_node == p_id && E->get().from_port == p_port) {
- // push into the connections map
- if (!conn_map.has(E->get().to_node))
+ // Push into the connections map.
+ if (!conn_map.has(E->get().to_node)) {
conn_map.set(E->get().to_node, Set<int>());
+ }
conn_map[E->get().to_node].insert(E->get().to_port);
}
}
@@ -1493,7 +1595,7 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) {
conn_map.get_key_list(&keys);
for (const List<int>::Element *E = keys.front(); E; E = E->next()) {
for (const Set<int>::Element *F = conn_map[E->get()].front(); F; F = F->next()) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_id, p_port, E->get(), F->get());
+ undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E->get(), F->get());
}
}
@@ -1506,12 +1608,10 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) {
}
void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) {
-
- StringName func = _get_function_of_node(p_id);
-
- Ref<VisualScriptExpression> vse = script->get_node(func, p_id);
- if (!vse.is_valid())
+ Ref<VisualScriptExpression> vse = script->get_node(p_id);
+ if (!vse.is_valid()) {
return;
+ }
updating_graph = true;
@@ -1523,15 +1623,17 @@ void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id
undo_redo->commit_action();
Node *node = graph->get_node(itos(p_id));
- if (Object::cast_to<Control>(node))
- Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); //shrink if text is smaller
+ if (Object::cast_to<Control>(node)) {
+ Object::cast_to<Control>(node)->set_size(Vector2(1, 1)); // Shrink if text is smaller.
+ }
updating_graph = false;
}
Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const {
- if (centered)
+ if (centered) {
ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5;
+ }
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -1542,23 +1644,19 @@ Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const
while (true) {
bool exists = false;
- List<StringName> all_fn;
- script->get_function_list(&all_fn);
- for (List<StringName>::Element *F = all_fn.front(); F; F = F->next()) {
- StringName curr_fn = F->get();
- List<int> existing;
- script->get_node_list(curr_fn, &existing);
- for (List<int>::Element *E = existing.front(); E; E = E->next()) {
- Point2 pos = script->get_node_position(curr_fn, E->get());
- if (pos.distance_to(ofs) < 50) {
- ofs += Vector2(graph->get_snap(), graph->get_snap());
- exists = true;
- break;
- }
+ List<int> existing;
+ script->get_node_list(&existing);
+ for (List<int>::Element *E = existing.front(); E; E = E->next()) {
+ Point2 pos = script->get_node_position(E->get());
+ if (pos.distance_to(ofs) < 50) {
+ ofs += Vector2(graph->get_snap(), graph->get_snap());
+ exists = true;
+ break;
}
}
- if (exists)
+ if (exists) {
continue;
+ }
break;
}
@@ -1566,12 +1664,10 @@ Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const
}
String VisualScriptEditor::_validate_name(const String &p_name) const {
-
String valid = p_name;
int counter = 1;
while (true) {
-
bool exists = script->has_function(valid) || script->has_variable(valid) || script->has_custom_signal(valid);
if (exists) {
@@ -1587,8 +1683,7 @@ String VisualScriptEditor::_validate_name(const String &p_name) const {
}
void VisualScriptEditor::_on_nodes_delete() {
-
- // delete all the selected nodes
+ // Delete all the selected nodes.
List<int> to_erase;
@@ -1601,37 +1696,33 @@ void VisualScriptEditor::_on_nodes_delete() {
}
}
- if (to_erase.empty())
+ if (to_erase.is_empty()) {
return;
+ }
undo_redo->create_action(TTR("Remove VisualScript Nodes"));
for (List<int>::Element *F = to_erase.front(); F; F = F->next()) {
-
int cr_node = F->get();
- StringName func = _get_function_of_node(cr_node);
-
- undo_redo->add_do_method(script.ptr(), "remove_node", func, cr_node);
- undo_redo->add_undo_method(script.ptr(), "add_node", func, cr_node, script->get_node(func, cr_node), script->get_node_position(func, cr_node));
+ undo_redo->add_do_method(script.ptr(), "remove_node", cr_node);
+ undo_redo->add_undo_method(script.ptr(), "add_node", cr_node, script->get_node(cr_node), script->get_node_position(cr_node));
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(func, &sequence_conns);
+ script->get_sequence_connection_list(&sequence_conns);
for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
-
if (E->get().from_node == cr_node || E->get().to_node == cr_node) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node);
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node);
}
}
List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(func, &data_conns);
+ script->get_data_connection_list(&data_conns);
for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) {
-
if (E->get().from_node == F->get() || E->get().to_node == F->get()) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
}
}
}
@@ -1642,9 +1733,7 @@ void VisualScriptEditor::_on_nodes_delete() {
}
void VisualScriptEditor::_on_nodes_duplicate() {
-
Set<int> to_duplicate;
- List<StringName> funcs;
for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
@@ -1652,13 +1741,13 @@ void VisualScriptEditor::_on_nodes_duplicate() {
if (gn->is_selected() && gn->is_close_button_visible()) {
int id = gn->get_name().operator String().to_int();
to_duplicate.insert(id);
- funcs.push_back(_get_function_of_node(id));
}
}
}
- if (to_duplicate.empty())
+ if (to_duplicate.is_empty()) {
return;
+ }
undo_redo->create_action(TTR("Duplicate VisualScript Nodes"));
int idc = script->get_available_id() + 1;
@@ -1667,10 +1756,8 @@ void VisualScriptEditor::_on_nodes_duplicate() {
HashMap<int, int> remap;
for (Set<int>::Element *F = to_duplicate.front(); F; F = F->next()) {
-
- // duplicate from the specific function but place it into the default func as it would lack the connections
- StringName func = _get_function_of_node(F->get());
- Ref<VisualScriptNode> node = script->get_node(func, F->get());
+ // Duplicate from the specific function but place it into the default func as it would lack the connections.
+ Ref<VisualScriptNode> node = script->get_node(F->get());
Ref<VisualScriptNode> dupe = node->duplicate(true);
@@ -1678,25 +1765,23 @@ void VisualScriptEditor::_on_nodes_duplicate() {
remap.set(F->get(), new_id);
to_select.insert(new_id);
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, dupe, script->get_node_position(func, F->get()) + Vector2(20, 20));
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, dupe, script->get_node_position(F->get()) + Vector2(20, 20));
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
}
- for (List<StringName>::Element *F = funcs.front(); F; F = F->next()) {
- List<VisualScript::SequenceConnection> seqs;
- script->get_sequence_connection_list(F->get(), &seqs);
- for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) {
- if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
- }
+ List<VisualScript::SequenceConnection> seqs;
+ script->get_sequence_connection_list(&seqs);
+ for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) {
+ if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
}
+ }
- List<VisualScript::DataConnection> data;
- script->get_data_connection_list(F->get(), &data);
- for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) {
- if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) {
- undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
- }
+ List<VisualScript::DataConnection> data;
+ script->get_data_connection_list(&data);
+ for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) {
+ if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) {
+ undo_redo->add_do_method(script.ptr(), "data_connect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
}
}
@@ -1714,25 +1799,27 @@ void VisualScriptEditor::_on_nodes_duplicate() {
}
if (to_select.size()) {
- EditorNode::get_singleton()->push_item(script->get_node(default_func, to_select.front()->get()).ptr());
+ EditorNode::get_singleton()->push_item(script->get_node(to_select.front()->get()).ptr());
}
}
void VisualScriptEditor::_generic_search(String p_base_type, Vector2 pos, bool node_centered) {
- if (node_centered)
+ if (node_centered) {
port_action_pos = graph->get_size() / 2.0f;
- else
+ } else {
port_action_pos = graph->get_viewport()->get_mouse_position() - graph->get_global_position();
+ }
new_connect_node_select->select_from_visual_script(p_base_type, false, false); // neither connecting nor reset text
- // ensure that the dialog fits inside the graph
+ // Ensure that the dialog fits inside the graph.
Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size();
pos.x = pos.x > bounds.x ? bounds.x : pos.x;
pos.y = pos.y > bounds.y ? bounds.y : pos.y;
- if (pos != Vector2())
+ if (pos != Vector2()) {
new_connect_node_select->set_position(pos);
+ }
}
void VisualScriptEditor::_input(const Ref<InputEvent> &p_event) {
@@ -1756,7 +1843,6 @@ void VisualScriptEditor::_graph_gui_input(const Ref<InputEvent> &p_event) {
}
void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) {
-
Ref<InputEventKey> key = p_event;
if (key.is_valid() && key->is_pressed() && !key->is_echo()) {
if (members->has_focus()) {
@@ -1786,29 +1872,27 @@ void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> btn = p_event;
if (btn.is_valid() && btn->is_doubleclick()) {
TreeItem *ti = members->get_selected();
- if (ti && ti->get_parent() == members->get_root()->get_children()) // to check if it's a function
- _center_on_node(ti->get_metadata(0), script->get_function_node_id(ti->get_metadata(0)));
+ if (ti && ti->get_parent() == members->get_root()->get_children()) { // to check if it's a function
+ _center_on_node(script->get_function_node_id(ti->get_metadata(0)));
+ }
}
}
void VisualScriptEditor::_rename_function(const String &name, const String &new_name) {
-
if (!new_name.is_valid_identifier()) {
-
EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name);
return;
}
if (script->has_function(new_name) || script->has_variable(new_name) || script->has_custom_signal(new_name)) {
-
EditorNode::get_singleton()->show_warning(TTR("Name already in use by another func/var/signal:") + " " + new_name);
return;
}
int node_id = script->get_function_node_id(name);
Ref<VisualScriptFunction> func;
- if (script->has_node(name, node_id)) {
- func = script->get_node(name, node_id);
+ if (script->has_node(node_id)) {
+ func = script->get_node(node_id);
}
undo_redo->create_action(TTR("Rename Function"));
undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name);
@@ -1818,20 +1902,17 @@ void VisualScriptEditor::_rename_function(const String &name, const String &new_
undo_redo->add_undo_method(func.ptr(), "set_name", name);
}
- // also fix all function calls
- List<StringName> flst;
- script->get_function_list(&flst);
- for (List<StringName>::Element *E = flst.front(); E; E = E->next()) {
- List<int> lst;
- script->get_node_list(E->get(), &lst);
- for (List<int>::Element *F = lst.front(); F; F = F->next()) {
- Ref<VisualScriptFunctionCall> fncall = script->get_node(E->get(), F->get());
- if (!fncall.is_valid())
- continue;
- if (fncall->get_function() == name) {
- undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
- undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
- }
+ // Also fix all function calls.
+ List<int> lst;
+ script->get_node_list(&lst);
+ for (List<int>::Element *F = lst.front(); F; F = F->next()) {
+ Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get());
+ if (!fncall.is_valid()) {
+ continue;
+ }
+ if (fncall->get_function() == name) {
+ undo_redo->add_do_method(fncall.ptr(), "set_function", new_name);
+ undo_redo->add_undo_method(fncall.ptr(), "set_function", name);
}
}
@@ -1845,9 +1926,9 @@ void VisualScriptEditor::_rename_function(const String &name, const String &new_
}
void VisualScriptEditor::_fn_name_box_input(const Ref<InputEvent> &p_event) {
-
- if (!function_name_edit->is_visible())
+ if (!function_name_edit->is_visible()) {
return;
+ }
Ref<InputEventKey> key = p_event;
if (key.is_valid() && key->is_pressed() && key->get_keycode() == KEY_ENTER) {
@@ -1858,31 +1939,28 @@ void VisualScriptEditor::_fn_name_box_input(const Ref<InputEvent> &p_event) {
}
Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
-
if (p_from == members) {
-
TreeItem *it = members->get_item_at_position(p_point);
- if (!it)
+ if (!it) {
return Variant();
+ }
String type = it->get_metadata(0);
- if (type == String())
+ if (type == String()) {
return Variant();
+ }
Dictionary dd;
TreeItem *root = members->get_root();
if (it->get_parent() == root->get_children()) {
-
dd["type"] = "visual_script_function_drag";
dd["function"] = type;
} else if (it->get_parent() == root->get_children()->get_next()) {
-
dd["type"] = "visual_script_variable_drag";
dd["variable"] = type;
} else if (it->get_parent() == root->get_children()->get_next()->get_next()) {
-
dd["type"] = "visual_script_signal_drag";
dd["signal"] = type;
@@ -1899,9 +1977,7 @@ Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_f
}
bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
-
if (p_from == graph) {
-
Dictionary d = p_data;
if (d.has("type") &&
(String(d["type"]) == "visual_script_node_drag" ||
@@ -1912,9 +1988,7 @@ bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &
String(d["type"]) == "resource" ||
String(d["type"]) == "files" ||
String(d["type"]) == "nodes")) {
-
if (String(d["type"]) == "obj_property") {
-
#ifdef OSX_ENABLED
const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a Getter. Hold Shift to drop a generic signature."), find_keycode_name(KEY_META)));
#else
@@ -1923,7 +1997,6 @@ bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &
}
if (String(d["type"]) == "nodes") {
-
#ifdef OSX_ENABLED
const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a simple reference to the node."), find_keycode_name(KEY_META)));
#else
@@ -1932,7 +2005,6 @@ bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &
}
if (String(d["type"]) == "visual_script_variable_drag") {
-
#ifdef OSX_ENABLED
const_cast<VisualScriptEditor *>(this)->_show_hint(vformat(TTR("Hold %s to drop a Variable Setter."), find_keycode_name(KEY_META)));
#else
@@ -1948,26 +2020,27 @@ bool VisualScriptEditor::can_drop_data_fw(const Point2 &p_point, const Variant &
}
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
-
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene)
+ if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
return nullptr;
+ }
Ref<Script> scr = p_current_node->get_script();
- if (scr.is_valid() && scr == script)
+ if (scr.is_valid() && scr == script) {
return p_current_node;
+ }
for (int i = 0; i < p_current_node->get_child_count(); i++) {
Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n)
+ if (n) {
return n;
+ }
}
return nullptr;
}
void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
-
if (p_from != graph) {
return;
}
@@ -1992,7 +2065,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
ofs /= EDSCALE;
- int new_id = _create_new_node_from_name(d["node_type"], ofs, default_func);
+ int new_id = _create_new_node_from_name(d["node_type"], ofs);
Node *node = graph->get_node(itos(new_id));
if (node) {
@@ -2002,7 +2075,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "visual_script_variable_drag") {
-
#ifdef OSX_ENABLED
bool use_set = Input::get_singleton()->is_key_pressed(KEY_META);
#else
@@ -2023,7 +2095,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
vnodes->set_variable(d["variable"]);
vnode = vnodes;
} else {
-
Ref<VisualScriptVariableGet> vnodeg;
vnodeg.instance();
vnodeg->set_variable(d["variable"]);
@@ -2033,8 +2104,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -2047,7 +2118,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "visual_script_function_drag") {
-
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -2063,11 +2133,11 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs);
undo_redo->add_do_method(vnode.ptr(), "set_base_type", script->get_instance_base_type());
undo_redo->add_do_method(vnode.ptr(), "set_function", d["function"]);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -2080,7 +2150,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "visual_script_signal_drag") {
-
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -2096,8 +2165,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, vnode, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -2110,7 +2179,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "resource") {
-
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -2126,8 +2194,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Preload Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -2140,7 +2208,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "files") {
-
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -2158,17 +2225,17 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
undo_redo->create_action(TTR("Add Preload Node"));
for (int i = 0; i < files.size(); i++) {
-
Ref<Resource> res = ResourceLoader::load(files[i]);
- if (!res.is_valid())
+ if (!res.is_valid()) {
continue;
+ }
Ref<VisualScriptPreload> prnode;
prnode.instance();
prnode->set_preload(res);
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, prnode, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
new_ids.push_back(new_id);
new_id++;
ofs += Vector2(20, 20) * EDSCALE;
@@ -2180,7 +2247,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
for (List<int>::Element *E = new_ids.front(); E; E = E->next()) {
-
Node *node = graph->get_node(itos(E->get()));
if (node) {
graph->set_selected(node);
@@ -2190,7 +2256,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "nodes") {
-
Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
if (!sn) {
@@ -2222,7 +2287,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
for (int i = 0; i < nodes.size(); i++) {
-
NodePath np = nodes[i];
Node *node = get_node(np);
if (!node) {
@@ -2237,7 +2301,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
scene_node->set_node_path(sn->get_path_to(node));
n = scene_node;
} else {
- // ! Doesn't work properly
+ // ! Doesn't work properly.
Ref<VisualScriptFunctionCall> call;
call.instance();
call->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH);
@@ -2248,8 +2312,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
selecting_method_id = base_id;
}
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, n, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", base_id, n, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
base_id++;
ofs += Vector2(25, 25);
@@ -2260,7 +2324,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
if (String(d["type"]) == "obj_property") {
-
Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
if (!sn && !Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
@@ -2270,8 +2333,9 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
Object *obj = d["object"];
- if (!obj)
+ if (!obj) {
return;
+ }
Node *node = Object::cast_to<Node>(obj);
Vector2 ofs = graph->get_scroll_ofs() + p_point;
@@ -2289,18 +2353,17 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
#endif
if (!node || Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
-
- if (use_get)
+ if (use_get) {
undo_redo->create_action(TTR("Add Getter Property"));
- else
+ } else {
undo_redo->create_action(TTR("Add Setter Property"));
+ }
int base_id = script->get_available_id();
Ref<VisualScriptNode> vnode;
if (!use_get) {
-
Ref<VisualScriptPropertySet> pset;
pset.instance();
pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE);
@@ -2311,7 +2374,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}*/
vnode = pset;
} else {
-
Ref<VisualScriptPropertyGet> pget;
pget.instance();
pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
@@ -2320,31 +2382,30 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
vnode = pget;
}
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs);
undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]);
if (!use_get) {
undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
}
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
} else {
-
- if (use_get)
+ if (use_get) {
undo_redo->create_action(TTR("Add Getter Property"));
- else
+ } else {
undo_redo->create_action(TTR("Add Setter Property"));
+ }
int base_id = script->get_available_id();
Ref<VisualScriptNode> vnode;
if (!use_get) {
-
Ref<VisualScriptPropertySet> pset;
pset.instance();
if (sn == node) {
@@ -2356,7 +2417,6 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
vnode = pset;
} else {
-
Ref<VisualScriptPropertyGet> pget;
pget.instance();
if (sn == node) {
@@ -2367,12 +2427,12 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
vnode = pget;
}
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, base_id, vnode, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs);
undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]);
if (!use_get) {
undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
}
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, base_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", base_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
@@ -2382,33 +2442,33 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da
}
void VisualScriptEditor::_selected_method(const String &p_method, const String &p_type, const bool p_connecting) {
-
- Ref<VisualScriptFunctionCall> vsfc = script->get_node(default_func, selecting_method_id);
- if (!vsfc.is_valid())
+ Ref<VisualScriptFunctionCall> vsfc = script->get_node(selecting_method_id);
+ if (!vsfc.is_valid()) {
return;
+ }
vsfc->set_function(p_method);
}
void VisualScriptEditor::_draw_color_over_button(Object *obj, Color p_color) {
-
Button *button = Object::cast_to<Button>(obj);
- if (!button)
+ if (!button) {
return;
+ }
Ref<StyleBox> normal = get_theme_stylebox("normal", "Button");
button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color);
}
void VisualScriptEditor::_button_resource_previewed(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Variant p_ud) {
-
Array ud = p_ud;
ERR_FAIL_COND(ud.size() != 2);
ObjectID id = ud[0];
Object *obj = ObjectDB::get_instance(id);
- if (!obj)
+ if (!obj) {
return;
+ }
Button *b = Object::cast_to<Button>(obj);
ERR_FAIL_COND(!b);
@@ -2416,7 +2476,6 @@ void VisualScriptEditor::_button_resource_previewed(const String &p_path, const
if (p_preview.is_null()) {
b->set_text(ud[1]);
} else {
-
b->set_icon(p_preview);
}
}
@@ -2431,7 +2490,8 @@ RES VisualScriptEditor::get_edited_resource() const {
}
void VisualScriptEditor::set_edited_resource(const RES &p_res) {
-
+ ERR_FAIL_COND(script.is_valid());
+ ERR_FAIL_COND(p_res.is_null());
script = p_res;
signal_editor->script = script;
signal_editor->undo_redo = undo_redo;
@@ -2440,20 +2500,14 @@ void VisualScriptEditor::set_edited_resource(const RES &p_res) {
script->connect("node_ports_changed", callable_mp(this, &VisualScriptEditor::_node_ports_changed));
- default_func = script->get_default_func();
-
- if (!script->has_function(default_func)) // this is the supposed default function
- {
- script->add_function(default_func);
- script->set_edited(true); //so that if a function was added it's saved
- }
-
_update_graph();
- _update_members();
+ call_deferred("_update_members");
}
-Vector<String> VisualScriptEditor::get_functions() {
+void VisualScriptEditor::enable_editor() {
+}
+Vector<String> VisualScriptEditor::get_functions() {
return Vector<String>();
}
@@ -2461,36 +2515,39 @@ void VisualScriptEditor::reload_text() {
}
String VisualScriptEditor::get_name() {
-
String name;
if (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) {
name = script->get_path().get_file();
if (is_unsaved()) {
+ if (script->get_path().is_empty()) {
+ name = TTR("[unsaved]");
+ }
name += "(*)";
}
- } else if (script->get_name() != "")
+ } else if (script->get_name() != "") {
name = script->get_name();
- else
+ } else {
name = script->get_class() + "(" + itos(script->get_instance_id()) + ")";
+ }
return name;
}
Ref<Texture2D> VisualScriptEditor::get_theme_icon() {
-
return Control::get_theme_icon("VisualScript", "EditorIcons");
}
bool VisualScriptEditor::is_unsaved() {
-
- return script->is_edited() || script->are_subnodes_edited();
+ bool unsaved =
+ script->is_edited() ||
+ script->are_subnodes_edited() ||
+ script->get_path().is_empty(); // In memory.
+ return unsaved;
}
Variant VisualScriptEditor::get_edit_state() {
-
Dictionary d;
- d["function"] = default_func;
d["scroll"] = graph->get_scroll_ofs();
d["zoom"] = graph->get_zoom();
d["using_snap"] = graph->is_using_snap();
@@ -2499,11 +2556,7 @@ Variant VisualScriptEditor::get_edit_state() {
}
void VisualScriptEditor::set_edit_state(const Variant &p_state) {
-
Dictionary d = p_state;
- if (d.has("function")) {
- selected = default_func;
- }
_update_graph();
_update_members();
@@ -2522,40 +2575,38 @@ void VisualScriptEditor::set_edit_state(const Variant &p_state) {
}
}
-void VisualScriptEditor::_center_on_node(const StringName &p_func, int p_id) {
-
+void VisualScriptEditor::_center_on_node(int p_id) {
Node *n = graph->get_node(itos(p_id));
GraphNode *gn = Object::cast_to<GraphNode>(n);
- // clear selection
+ // Clear selection.
for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gnd = Object::cast_to<GraphNode>(graph->get_child(i));
- if (gnd)
+ if (gnd) {
gnd->set_selected(false);
+ }
}
if (gn) {
gn->set_selected(true);
- Vector2 new_scroll = gn->get_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5;
+ Vector2 new_scroll = gn->get_position_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5;
graph->set_scroll_ofs(new_scroll);
- script->set_function_scroll(p_func, new_scroll / EDSCALE);
+ script->set_scroll(new_scroll / EDSCALE);
script->set_edited(true);
}
}
void VisualScriptEditor::goto_line(int p_line, bool p_with_error) {
+ p_line += 1; // Add one because script lines begin from 0.
- p_line += 1; //add one because script lines begin from 0.
-
- if (p_with_error)
+ if (p_with_error) {
error_line = p_line;
+ }
List<StringName> functions;
script->get_function_list(&functions);
for (List<StringName>::Element *E = functions.front(); E; E = E->next()) {
-
- if (script->has_node(E->get(), p_line)) {
-
+ if (script->has_node(p_line)) {
_update_graph();
_update_members();
@@ -2586,7 +2637,6 @@ void VisualScriptEditor::convert_indent_to_tabs() {
}
void VisualScriptEditor::ensure_focus() {
-
graph->grab_focus();
}
@@ -2597,37 +2647,34 @@ void VisualScriptEditor::reload(bool p_soft) {
_update_graph();
}
-void VisualScriptEditor::get_breakpoints(List<int> *p_breakpoints) {
-
+Array VisualScriptEditor::get_breakpoints() {
+ Array breakpoints;
List<StringName> functions;
script->get_function_list(&functions);
for (List<StringName>::Element *E = functions.front(); E; E = E->next()) {
-
List<int> nodes;
- script->get_node_list(E->get(), &nodes);
+ script->get_node_list(&nodes);
for (List<int>::Element *F = nodes.front(); F; F = F->next()) {
-
- Ref<VisualScriptNode> vsn = script->get_node(E->get(), F->get());
+ Ref<VisualScriptNode> vsn = script->get_node(F->get());
if (vsn->is_breakpoint()) {
- p_breakpoints->push_back(F->get() - 1); //subtract 1 because breakpoints in text start from zero
+ breakpoints.push_back(F->get() - 1); // Subtract 1 because breakpoints in text start from zero.
}
}
}
+ return breakpoints;
}
void VisualScriptEditor::add_callback(const String &p_function, PackedStringArray p_args) {
-
if (script->has_function(p_function)) {
_update_members();
_update_graph();
- _center_on_node(p_function, script->get_function_node_id(p_function));
+ _center_on_node(script->get_function_node_id(p_function));
return;
}
Ref<VisualScriptFunction> func;
func.instance();
for (int i = 0; i < p_args.size(); i++) {
-
String name = p_args[i];
Variant::Type type = Variant::NIL;
@@ -2635,7 +2682,6 @@ void VisualScriptEditor::add_callback(const String &p_function, PackedStringArra
String tt = name.get_slice(":", 1);
name = name.get_slice(":", 0);
for (int j = 0; j < Variant::VARIANT_MAX; j++) {
-
String tname = Variant::get_type_name(Variant::Type(j));
if (tname == tt) {
type = Variant::Type(j);
@@ -2646,15 +2692,15 @@ void VisualScriptEditor::add_callback(const String &p_function, PackedStringArra
func->add_argument(type, name);
}
-
+ int fn_id = script->get_available_id();
func->set_name(p_function);
- script->add_function(p_function);
- script->add_node(p_function, script->get_available_id(), func);
+ script->add_function(p_function, fn_id);
+ script->add_node(fn_id, func);
_update_members();
_update_graph();
- _center_on_node(p_function, script->get_function_node_id(p_function));
+ _center_on_node(script->get_function_node_id(p_function));
}
bool VisualScriptEditor::show_members_overview() {
@@ -2662,7 +2708,6 @@ bool VisualScriptEditor::show_members_overview() {
}
void VisualScriptEditor::update_settings() {
-
_update_graph();
}
@@ -2677,12 +2722,10 @@ void VisualScriptEditor::set_tooltip_request_func(String p_method, Object *p_obj
}
Control *VisualScriptEditor::get_edit_menu() {
-
return edit_menu;
}
void VisualScriptEditor::_change_base_type() {
-
select_base_type->popup_create(true, true);
}
@@ -2696,7 +2739,6 @@ void VisualScriptEditor::clear_edit_menu() {
}
void VisualScriptEditor::_change_base_type_callback() {
-
String bt = select_base_type->get_selected_type();
ERR_FAIL_COND(bt == String());
@@ -2709,16 +2751,15 @@ void VisualScriptEditor::_change_base_type_callback() {
}
void VisualScriptEditor::_node_selected(Node *p_node) {
-
Ref<VisualScriptNode> vnode = p_node->get_meta("__vnode");
- if (vnode.is_null())
+ if (vnode.is_null()) {
return;
+ }
EditorNode::get_singleton()->push_item(vnode.ptr()); //edit node in inspector
}
static bool _get_out_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &r_real_slot, bool &r_sequence) {
-
if (p_slot < p_node->get_output_sequence_port_count()) {
r_sequence = true;
r_real_slot = p_slot;
@@ -2733,7 +2774,6 @@ static bool _get_out_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &
}
static bool _get_in_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &r_real_slot, bool &r_sequence) {
-
if (p_slot == 0 && p_node->has_input_sequence_port()) {
r_sequence = true;
r_real_slot = 0;
@@ -2747,75 +2787,53 @@ static bool _get_in_slot(const Ref<VisualScriptNode> &p_node, int p_slot, int &r
}
void VisualScriptEditor::_begin_node_move() {
-
undo_redo->create_action(TTR("Move Node(s)"));
}
void VisualScriptEditor::_end_node_move() {
-
undo_redo->commit_action();
}
-void VisualScriptEditor::_move_node(const StringName &p_func, int p_id, const Vector2 &p_to) {
-
- if (!script->has_function(p_func))
+void VisualScriptEditor::_move_node(int p_id, const Vector2 &p_to) {
+ if (!script->has_node(p_id)) {
return;
+ }
Node *node = graph->get_node(itos(p_id));
- if (Object::cast_to<GraphNode>(node))
- Object::cast_to<GraphNode>(node)->set_offset(p_to);
-
- script->set_node_position(p_func, p_id, p_to / EDSCALE);
-}
-
-StringName VisualScriptEditor::_get_function_of_node(int p_id) const {
-
- List<StringName> funcs;
- script->get_function_list(&funcs);
- for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) {
- if (script->has_node(E->get(), p_id)) {
- return E->get();
- }
+ if (Object::cast_to<GraphNode>(node)) {
+ Object::cast_to<GraphNode>(node)->set_position_offset(p_to);
}
- return ""; // this is passed to avoid crash and is tested against later
+ script->set_node_position(p_id, p_to / EDSCALE);
}
void VisualScriptEditor::_node_moved(Vector2 p_from, Vector2 p_to, int p_id) {
-
- StringName func = _get_function_of_node(p_id);
-
- undo_redo->add_do_method(this, "_move_node", func, p_id, p_to);
- undo_redo->add_undo_method(this, "_move_node", func, p_id, p_from);
+ undo_redo->add_do_method(this, "_move_node", p_id, p_to);
+ undo_redo->add_undo_method(this, "_move_node", p_id, p_from);
}
void VisualScriptEditor::_remove_node(int p_id) {
-
undo_redo->create_action(TTR("Remove VisualScript Node"));
- StringName func = _get_function_of_node(p_id);
-
- undo_redo->add_do_method(script.ptr(), "remove_node", func, p_id);
- undo_redo->add_undo_method(script.ptr(), "add_node", func, p_id, script->get_node(func, p_id), script->get_node_position(func, p_id));
+ undo_redo->add_do_method(script.ptr(), "remove_node", p_id);
+ undo_redo->add_undo_method(script.ptr(), "add_node", p_id, script->get_node(p_id), script->get_node_position(p_id));
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(func, &sequence_conns);
+ script->get_sequence_connection_list(&sequence_conns);
for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
-
if (E->get().from_node == p_id || E->get().to_node == p_id) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, E->get().from_node, E->get().from_output, E->get().to_node);
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node);
}
}
List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(func, &data_conns);
+ script->get_data_connection_list(&data_conns);
for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) {
-
if (E->get().from_node == p_id || E->get().to_node == p_id) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
}
}
@@ -2825,102 +2843,66 @@ void VisualScriptEditor::_remove_node(int p_id) {
undo_redo->commit_action();
}
-void VisualScriptEditor::_node_ports_changed(const String &p_func, int p_id) {
-
+void VisualScriptEditor::_node_ports_changed(int p_id) {
_update_graph(p_id);
}
-bool VisualScriptEditor::node_has_sequence_connections(const StringName &p_func, int p_id) {
+bool VisualScriptEditor::node_has_sequence_connections(int p_id) {
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(p_func, &sequence_conns);
+ script->get_sequence_connection_list(&sequence_conns);
for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
int from = E->get().from_node;
int to = E->get().to_node;
- if (to == p_id || from == p_id)
+ if (to == p_id || from == p_id) {
return true;
+ }
}
return false;
}
void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
-
- StringName from_func = _get_function_of_node(p_from.to_int());
-
- Ref<VisualScriptNode> from_node = script->get_node(from_func, p_from.to_int());
+ Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int());
ERR_FAIL_COND(!from_node.is_valid());
bool from_seq;
int from_port;
- if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq))
+ if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) {
return; //can't connect this, it's invalid
+ }
- StringName to_func = _get_function_of_node(p_to.to_int());
-
- Ref<VisualScriptNode> to_node = script->get_node(to_func, p_to.to_int());
+ Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int());
ERR_FAIL_COND(!to_node.is_valid());
bool to_seq;
int to_port;
- if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq))
+ if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq)) {
return; //can't connect this, it's invalid
+ }
ERR_FAIL_COND(from_seq != to_seq);
- // Do all the checks here
- StringName func; // this the func where we store the one the nodes at the end of the resolution on having multiple nodes
+ // Do all the checks here.
+ StringName func; // This the func where we store the one the nodes at the end of the resolution on having multiple nodes.
undo_redo->create_action(TTR("Connect Nodes"));
- if (from_func == to_func) {
- func = to_func;
- } else if (from_seq) {
- // this is a sequence connection
- _move_nodes_with_rescan(to_func, from_func, p_to.to_int()); // this function moves the nodes from func1 to func2
- func = from_func;
- } else {
- if (node_has_sequence_connections(to_func, p_to.to_int())) {
- if (node_has_sequence_connections(from_func, p_from.to_int())) {
- ERR_PRINT("Trying to connect between different sequence node trees");
- return;
- } else {
- _move_nodes_with_rescan(from_func, to_func, p_from.to_int());
- func = to_func;
- }
- } else if (node_has_sequence_connections(from_func, p_from.to_int())) {
- if (from_func == default_func) {
- _move_nodes_with_rescan(from_func, to_func, p_from.to_int());
- func = to_func;
- } else {
- _move_nodes_with_rescan(to_func, from_func, p_to.to_int());
- func = from_func;
- }
- } else {
- if (to_func == default_func) {
- _move_nodes_with_rescan(to_func, from_func, p_to.to_int());
- func = from_func;
- } else {
- _move_nodes_with_rescan(from_func, to_func, p_from.to_int());
- func = to_func;
- }
- }
- }
-
if (from_seq) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int());
- // this undo error on undo after move can't be removed without painful gymnastics
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int());
+ // This undo error on undo after move can't be removed without painful gymnastics
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
} else {
bool converted = false;
- int conv_node = -1;
Ref<VisualScriptOperator> oper = to_node;
if (oper.is_valid() && oper->get_typed() == Variant::NIL) {
- // it's an operator Node and if the type is already nil
+ // It's an operator Node and if the type is already nil
if (from_node->get_output_value_port_info(from_port).type != Variant::NIL) {
oper->set_typed(from_node->get_output_value_port_info(from_port).type);
}
@@ -2928,104 +2910,36 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot,
Ref<VisualScriptOperator> operf = from_node;
if (operf.is_valid() && operf->get_typed() == Variant::NIL) {
- // it's an operator Node and if the type is already nil
+ // It's an operator Node and if the type is already nil
if (to_node->get_input_value_port_info(to_port).type != Variant::NIL) {
operf->set_typed(to_node->get_input_value_port_info(to_port).type);
}
}
- Variant::Type to_type = to_node->get_input_value_port_info(to_port).type;
- Variant::Type from_type = from_node->get_output_value_port_info(from_port).type;
-
- if (to_type != Variant::NIL && from_type != Variant::NIL && to_type != from_type) {
- // add a constructor node between the ports
- bool exceptions = false; // true if there are any exceptions
- exceptions = exceptions || (to_type == Variant::INT && from_type == Variant::FLOAT);
- exceptions = exceptions || (to_type == Variant::FLOAT && from_type == Variant::INT);
- if (Variant::can_convert(from_type, to_type) && !exceptions) {
- MethodInfo mi;
- mi.name = Variant::get_type_name(to_type);
- PropertyInfo pi;
- pi.name = "from";
- pi.type = from_type;
- mi.arguments.push_back(pi);
- mi.return_val.type = to_type;
- // we know that this is allowed so create a new constructor node
- Ref<VisualScriptConstructor> constructor;
- constructor.instance();
- constructor->set_constructor_type(to_type);
- constructor->set_constructor(mi);
- // add the new constructor node
-
- GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(p_from));
- GraphNode *gn2 = Object::cast_to<GraphNode>(graph->get_node(p_to));
- if (gn && gn2) {
- Vector2 from_node_size = gn->get_rect().get_size();
- Vector2 to_node_size = gn2->get_rect().get_size();
- Vector2 to_node_pos = script->get_node_position(func, p_to.to_int());
- Vector2 from_node_pos = script->get_node_position(func, p_from.to_int());
- Vector2 new_to_node_pos = from_node_pos;
- Vector2 constructor_pos;
- if ((to_node_pos.x - from_node_pos.x) < 0) {
- // to is behind from node
- if (to_node_pos.x > (from_node_pos.x - to_node_size.x - 240))
- new_to_node_pos.x = from_node_pos.x - to_node_size.x - 240; // approx size of constructor node + padding
- else
- new_to_node_pos.x = to_node_pos.x;
- new_to_node_pos.y = to_node_pos.y;
- constructor_pos.x = from_node_pos.x - 210;
- constructor_pos.y = to_node_pos.y;
- } else {
- // to is ahead of from node
- if (to_node_pos.x < (from_node_size.x + from_node_pos.x + 240))
- new_to_node_pos.x = from_node_size.x + from_node_pos.x + 240; // approx size of constructor node + padding
- else
- new_to_node_pos.x = to_node_pos.x;
- new_to_node_pos.y = to_node_pos.y;
- constructor_pos.x = from_node_size.x + from_node_pos.x + 10;
- constructor_pos.y = to_node_pos.y;
- }
- undo_redo->add_do_method(this, "_move_node", func, p_to.to_int(), new_to_node_pos);
- undo_redo->add_undo_method(this, "_move_node", func, p_to.to_int(), to_node_pos);
- conv_node = script->get_available_id();
- undo_redo->add_do_method(script.ptr(), "add_node", func, conv_node, constructor, _get_available_pos(false, constructor_pos));
- undo_redo->add_undo_method(script.ptr(), "remove_node", func, conv_node);
- converted = true;
- }
- }
- }
-
- // disconnect current, and connect the new one
- if (script->is_input_value_port_connected(func, p_to.to_int(), to_port)) {
+ // Disconnect current, and connect the new one
+ if (script->is_input_value_port_connected(p_to.to_int(), to_port)) {
if (can_swap && data_disconnect_node == p_to.to_int()) {
int conn_from;
int conn_port;
- script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port);
- undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port);
- undo_redo->add_do_method(script.ptr(), "data_connect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, data_disconnect_node, data_disconnect_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port);
+ script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port);
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port);
+ undo_redo->add_do_method(script.ptr(), "data_connect", conn_from, conn_port, data_disconnect_node, data_disconnect_port);
+ undo_redo->add_undo_method(script.ptr(), "data_disconnect", conn_from, conn_port, data_disconnect_node, data_disconnect_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port);
can_swap = false; // swapped
} else {
int conn_from;
int conn_port;
- script->get_input_value_port_connection_source(func, p_to.to_int(), to_port, &conn_from, &conn_port);
- undo_redo->add_do_method(script.ptr(), "data_disconnect", func, conn_from, conn_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, conn_from, conn_port, p_to.to_int(), to_port);
+ script->get_input_value_port_connection_source(p_to.to_int(), to_port, &conn_from, &conn_port);
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", conn_from, conn_port, p_to.to_int(), to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", conn_from, conn_port, p_to.to_int(), to_port);
}
}
if (!converted) {
- undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port);
- } else {
- // this is noice
- undo_redo->add_do_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, conv_node, 0);
- undo_redo->add_do_method(script.ptr(), "data_connect", func, conv_node, 0, p_to.to_int(), to_port);
- // I don't think this is needed but gonna leave it here for now... until I need to finalise it all
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, conv_node, 0);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, conv_node, 0, p_to.to_int(), to_port);
+ undo_redo->add_do_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port);
}
- //update nodes in graph
+ // Update nodes in graph
if (!converted) {
undo_redo->add_do_method(this, "_update_graph", p_from.to_int());
undo_redo->add_do_method(this, "_update_graph", p_to.to_int());
@@ -3037,315 +2951,95 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot,
}
}
- undo_redo->add_do_method(this, "_update_graph_connections");
- undo_redo->add_undo_method(this, "_update_graph_connections");
-
undo_redo->commit_action();
}
void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
-
- StringName func = _get_function_of_node(p_from.to_int());
- ERR_FAIL_COND(func != _get_function_of_node(p_to.to_int()));
-
- Ref<VisualScriptNode> from_node = script->get_node(func, p_from.to_int());
+ Ref<VisualScriptNode> from_node = script->get_node(p_from.to_int());
ERR_FAIL_COND(!from_node.is_valid());
bool from_seq;
int from_port;
- if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq))
- return; //can't connect this, it's invalid
+ if (!_get_out_slot(from_node, p_from_slot, from_port, from_seq)) {
+ return; // Can't connect this, it's invalid.
+ }
- Ref<VisualScriptNode> to_node = script->get_node(func, p_to.to_int());
+ Ref<VisualScriptNode> to_node = script->get_node(p_to.to_int());
ERR_FAIL_COND(!to_node.is_valid());
bool to_seq;
int to_port;
- if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq))
- return; //can't connect this, it's invalid
+ if (!_get_in_slot(to_node, p_to_slot, to_port, to_seq)) {
+ return; // Can't connect this, it's invalid.
+ }
ERR_FAIL_COND(from_seq != to_seq);
undo_redo->create_action(TTR("Disconnect Nodes"));
if (from_seq) {
- undo_redo->add_do_method(script.ptr(), "sequence_disconnect", func, p_from.to_int(), from_port, p_to.to_int());
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", func, p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_do_method(script.ptr(), "sequence_disconnect", p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
} else {
-
can_swap = true;
data_disconnect_node = p_to.to_int();
data_disconnect_port = to_port;
- undo_redo->add_do_method(script.ptr(), "data_disconnect", func, p_from.to_int(), from_port, p_to.to_int(), to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", func, p_from.to_int(), from_port, p_to.to_int(), to_port);
- //update relevant nodes in the graph
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", p_from.to_int(), from_port, p_to.to_int(), to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", p_from.to_int(), from_port, p_to.to_int(), to_port);
+ // Update relevant nodes in the graph.
undo_redo->add_do_method(this, "_update_graph", p_from.to_int());
undo_redo->add_do_method(this, "_update_graph", p_to.to_int());
undo_redo->add_undo_method(this, "_update_graph", p_from.to_int());
undo_redo->add_undo_method(this, "_update_graph", p_to.to_int());
}
- undo_redo->add_do_method(this, "_update_graph_connections");
- undo_redo->add_undo_method(this, "_update_graph_connections");
undo_redo->commit_action();
}
-void VisualScriptEditor::_move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id) {
-
- Set<int> nodes_to_move;
- HashMap<int, Map<int, int>> seqconns_to_move; // from => List(outp, to)
- HashMap<int, Map<int, Pair<int, int>>> dataconns_to_move; // to => List(inp_p => from, outp)
-
- nodes_to_move.insert(p_id);
- Set<int> sequence_connections;
- {
- List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(p_func_from, &sequence_conns);
-
- HashMap<int, Map<int, int>> seqcons; // from => List(out_p => to)
-
- for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
- int from = E->get().from_node;
- int to = E->get().to_node;
- int out_p = E->get().from_output;
- if (!seqcons.has(from))
- seqcons.set(from, Map<int, int>());
- seqcons[from].insert(out_p, to);
- sequence_connections.insert(to);
- sequence_connections.insert(from);
- }
-
- int conn = p_id;
- List<int> stack;
- HashMap<int, Set<int>> seen; // from, outp
- while (seqcons.has(conn)) {
- for (auto E = seqcons[conn].front(); E; E = E->next()) {
- if (seen.has(conn) && seen[conn].has(E->key())) {
- if (!E->next()) {
- if (stack.size() > 0) {
- conn = stack.back()->get();
- stack.pop_back();
- break;
- }
- conn = -101;
- break;
- }
- continue;
- }
- if (!seen.has(conn))
- seen.set(conn, Set<int>());
- seen[conn].insert(E->key());
- stack.push_back(conn);
- if (!seqconns_to_move.has(conn))
- seqconns_to_move.set(conn, Map<int, int>());
- seqconns_to_move[conn].insert(E->key(), E->get());
- conn = E->get();
- nodes_to_move.insert(conn);
- break;
- }
- if (!seqcons.has(conn) && stack.size() > 0) {
- conn = stack.back()->get();
- stack.pop_back();
- }
- }
- }
-
- {
- List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(p_func_from, &data_connections);
-
- HashMap<int, Map<int, Pair<int, int>>> connections;
-
- for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
- int from = E->get().from_node;
- int to = E->get().to_node;
- int out_p = E->get().from_port;
- int in_p = E->get().to_port;
-
- if (!connections.has(to))
- connections.set(to, Map<int, Pair<int, int>>());
- connections[to].insert(in_p, Pair<int, int>(from, out_p));
- }
-
- // go through the HashMap and do all sorts of crazy ass stuff now...
- Set<int> nodes_to_be_added;
- for (Set<int>::Element *F = nodes_to_move.front(); F; F = F->next()) {
- HashMap<int, Set<int>> seen;
- List<int> stack;
- int id = F->get();
- while (connections.has(id)) {
- for (auto E = connections[id].front(); E; E = E->next()) {
- if (seen.has(id) && seen[id].has(E->key())) {
- if (!E->next()) {
- if (stack.size() > 0) {
- id = stack.back()->get();
- stack.pop_back();
- break;
- }
- id = -11; // I assume ids can't be negative should confirm it...
- break;
- }
- continue;
- }
-
- if (sequence_connections.has(E->get().first)) {
- if (!nodes_to_move.has(E->get().first)) {
- if (stack.size() > 0) {
- id = stack.back()->get();
- stack.pop_back();
- break;
- }
- id = -11; // I assume ids can't be negative should confirm it...
- break;
- }
- }
-
- if (!seen.has(id))
- seen.set(id, Set<int>());
- seen[id].insert(E->key());
- stack.push_back(id);
- if (!dataconns_to_move.has(id))
- dataconns_to_move.set(id, Map<int, Pair<int, int>>());
- dataconns_to_move[id].insert(E->key(), Pair<int, int>(E->get().first, E->get().second));
- id = E->get().first;
- nodes_to_be_added.insert(id);
- break;
- }
- if (!connections.has(id) && stack.size() > 0) {
- id = stack.back()->get();
- stack.pop_back();
- }
- }
- }
- for (Set<int>::Element *E = nodes_to_be_added.front(); E; E = E->next()) {
- nodes_to_move.insert(E->get());
- }
- }
-
- // * this is primarily for the sake of the having proper undo
- List<VisualScript::SequenceConnection> seqext;
- List<VisualScript::DataConnection> dataext;
-
- List<VisualScript::SequenceConnection> seq_connections;
- script->get_sequence_connection_list(p_func_from, &seq_connections);
-
- for (List<VisualScript::SequenceConnection>::Element *E = seq_connections.front(); E; E = E->next()) {
- if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) {
- seqext.push_back(E->get());
- } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) {
- seqext.push_back(E->get());
- }
- }
-
- List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(p_func_from, &data_connections);
-
- for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
- if (!nodes_to_move.has(E->get().from_node) && nodes_to_move.has(E->get().to_node)) {
- dataext.push_back(E->get());
- } else if (nodes_to_move.has(E->get().from_node) && !nodes_to_move.has(E->get().to_node)) {
- dataext.push_back(E->get());
- }
- }
-
- // undo_redo->create_action("Rescan Functions");
-
- for (Set<int>::Element *E = nodes_to_move.front(); E; E = E->next()) {
- int id = E->get();
-
- undo_redo->add_do_method(script.ptr(), "remove_node", p_func_from, id);
- undo_redo->add_do_method(script.ptr(), "add_node", p_func_to, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id));
-
- undo_redo->add_undo_method(script.ptr(), "remove_node", p_func_to, id);
- undo_redo->add_undo_method(script.ptr(), "add_node", p_func_from, id, script->get_node(p_func_from, id), script->get_node_position(p_func_from, id));
- }
-
- List<int> skeys;
- seqconns_to_move.get_key_list(&skeys);
- for (List<int>::Element *E = skeys.front(); E; E = E->next()) {
- int from_node = E->get();
- for (Map<int, int>::Element *F = seqconns_to_move[from_node].front(); F; F = F->next()) {
- int from_port = F->key();
- int to_node = F->get();
- undo_redo->add_do_method(script.ptr(), "sequence_connect", p_func_to, from_node, from_port, to_node);
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, from_node, from_port, to_node);
- }
- }
-
- List<int> keys;
- dataconns_to_move.get_key_list(&keys);
- for (List<int>::Element *E = keys.front(); E; E = E->next()) {
- int to_node = E->get(); // to_node
- for (Map<int, Pair<int, int>>::Element *F = dataconns_to_move[E->get()].front(); F; F = F->next()) {
- int inp_p = F->key();
- Pair<int, int> fro = F->get();
-
- undo_redo->add_do_method(script.ptr(), "data_connect", p_func_to, fro.first, fro.second, to_node, inp_p);
- undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, fro.first, fro.second, to_node, inp_p);
- }
- }
-
- // this to have proper undo operations
- for (List<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", p_func_from, E->get().from_node, E->get().from_output, E->get().to_node);
- }
- for (List<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", p_func_from, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
- }
- // this doesn't need do methods as they are handled by the subsequent do calls implicitly
-
- undo_redo->add_do_method(this, "_update_graph");
- undo_redo->add_undo_method(this, "_update_graph");
-
- // undo_redo->commit_action();
-}
-
void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos) {
-
Node *node = graph->get_node(p_from);
GraphNode *gn = Object::cast_to<GraphNode>(node);
- if (!gn)
+ if (!gn) {
return;
+ }
- StringName func = _get_function_of_node(p_from.to_int());
-
- Ref<VisualScriptNode> vsn = script->get_node(func, p_from.to_int());
- if (!vsn.is_valid())
+ Ref<VisualScriptNode> vsn = script->get_node(p_from.to_int());
+ if (!vsn.is_valid()) {
return;
+ }
+ if (vsn->get_output_value_port_count())
- port_action_pos = p_release_pos;
+ port_action_pos = p_release_pos;
if (p_from_slot < vsn->get_output_sequence_port_count()) {
-
port_action_node = p_from.to_int();
port_action_output = p_from_slot;
- _port_action_menu(CREATE_ACTION, func);
+ _port_action_menu(CREATE_ACTION);
} else {
port_action_output = p_from_slot - vsn->get_output_sequence_port_count();
port_action_node = p_from.to_int();
- _port_action_menu(CREATE_CALL_SET_GET, func);
+ _port_action_menu(CREATE_CALL_SET_GET);
}
}
VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_action_node, int p_port_action_output, Set<int> &visited_nodes) {
-
VisualScriptNode::TypeGuess tg;
tg.type = Variant::NIL;
- if (visited_nodes.has(p_port_action_node))
+ if (visited_nodes.has(p_port_action_node)) {
return tg; //no loop
+ }
visited_nodes.insert(p_port_action_node);
- StringName func = _get_function_of_node(p_port_action_node);
-
- Ref<VisualScriptNode> node = script->get_node(func, p_port_action_node);
+ Ref<VisualScriptNode> node = script->get_node(p_port_action_node);
if (!node.is_valid()) {
-
return tg;
}
@@ -3357,21 +3051,18 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac
g.type = pi.type;
if (g.type == Variant::NIL || g.type == Variant::OBJECT) {
- //any or object input, must further guess what this is
+ // Any or object input, must further guess what this is.
int from_node;
int from_port;
- if (script->get_input_value_port_connection_source(func, p_port_action_node, i, &from_node, &from_port)) {
-
+ if (script->get_input_value_port_connection_source(p_port_action_node, i, &from_node, &from_port)) {
g = _guess_output_type(from_node, from_port, visited_nodes);
} else {
Variant defval = node->get_default_input_value(i);
if (defval.get_type() == Variant::OBJECT) {
-
Object *obj = defval;
if (obj) {
-
g.type = Variant::OBJECT;
g.gdclass = obj->get_class();
g.script = obj->get_script();
@@ -3386,8 +3077,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac
return node->guess_output_type(in_guesses.ptrw(), p_port_action_output);
}
-void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func) {
-
+void VisualScriptEditor::_port_action_menu(int p_option) {
Vector2 ofs = graph->get_scroll_ofs() + port_action_pos;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -3398,7 +3088,6 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
Set<int> vn;
switch (p_option) {
-
case CREATE_CALL_SET_GET: {
Ref<VisualScriptFunctionCall> n;
n.instance();
@@ -3411,8 +3100,8 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
n->set_base_type("Object");
}
String type_string;
- if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) {
- type_string = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string;
+ if (script->get_node(port_action_node)->get_output_value_port_count() > 0) {
+ type_string = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
}
if (tg.type == Variant::OBJECT) {
if (tg.script.is_valid()) {
@@ -3427,7 +3116,7 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
} else {
new_connect_node_select->select_from_basic_type(tg.type);
}
- // ensure that the dialog fits inside the graph
+ // Ensure that the dialog fits inside the graph.
Vector2 pos = mouse_up_position;
Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size();
pos.x = pos.x > bounds.x ? bounds.x : pos.x;
@@ -3437,8 +3126,8 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
case CREATE_ACTION: {
VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
PropertyInfo property_info;
- if (script->get_node(func, port_action_node)->get_output_value_port_count() > 0) {
- property_info = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output);
+ if (script->get_node(port_action_node)->get_output_value_port_count() > 0) {
+ property_info = script->get_node(port_action_node)->get_output_value_port_info(port_action_output);
}
if (tg.type == Variant::OBJECT) {
if (property_info.type == Variant::OBJECT && property_info.hint_string != String()) {
@@ -3451,7 +3140,7 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
} else {
new_connect_node_select->select_from_action(Variant::get_type_name(tg.type));
}
- // ensure that the dialog fits inside the graph
+ // Ensure that the dialog fits inside the graph.
Vector2 pos = mouse_up_position;
Size2 bounds = graph->get_global_position() + graph->get_size() - new_connect_node_select->get_size();
pos.x = pos.x > bounds.x ? bounds.x : pos.x;
@@ -3462,7 +3151,6 @@ void VisualScriptEditor::_port_action_menu(int p_option, const StringName &func)
}
void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id) {
-
undo_redo->create_action(TTR("Connect Node Data"));
VisualScriptReturn *vnode_return = Object::cast_to<VisualScriptReturn>(vnode.ptr());
if (vnode_return != nullptr && vnode_old->get_output_value_port_count() > 0) {
@@ -3481,14 +3169,12 @@ void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<Visua
if (port >= value_count) {
port = 0;
}
- StringName func = _get_function_of_node(port_action_node);
- undo_redo->add_do_method(script.ptr(), "data_connect", func, port_action_node, port, new_id, 0);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", func, port_action_node, port, new_id, 0);
+ undo_redo->add_do_method(script.ptr(), "data_connect", port_action_node, port, new_id, 0);
+ undo_redo->add_undo_method(script.ptr(), "data_disconnect", port_action_node, port, new_id, 0);
undo_redo->commit_action();
}
void VisualScriptEditor::_selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting) {
-
Vector2 ofs = graph->get_scroll_ofs() + port_action_pos;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
@@ -3501,17 +3187,17 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
bool port_node_exists = true;
- StringName func = _get_function_of_node(port_action_node);
- if (func == StringName()) {
- func = default_func;
- port_node_exists = false;
- }
+ // if (func == StringName()) {
+ // func = default_func;
+ // port_node_exists = false;
+ // }
if (p_category == "visualscript") {
Ref<VisualScriptNode> vnode_new = VisualScriptLanguage::singleton->create_node_from_name(p_text);
Ref<VisualScriptNode> vnode_old;
- if (port_node_exists)
- vnode_old = script->get_node(func, port_action_node);
+ if (port_node_exists && p_connecting) {
+ vnode_old = script->get_node(port_action_node);
+ }
int new_id = script->get_available_id();
if (Object::cast_to<VisualScriptOperator>(vnode_new.ptr()) && vnode_old.is_valid()) {
@@ -3533,13 +3219,13 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
}
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode_new, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode_new, ofs);
if (vnode_old.is_valid() && p_connecting) {
connect_seq(vnode_old, vnode_new, new_id);
connect_data(vnode_old, vnode_new, new_id);
}
- undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -3550,18 +3236,15 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
Ref<VisualScriptPropertySet> script_prop_set;
if (p_category == String("method")) {
-
Ref<VisualScriptFunctionCall> n;
n.instance();
vnode = n;
} else if (p_category == String("set")) {
-
Ref<VisualScriptPropertySet> n;
n.instance();
vnode = n;
script_prop_set = n;
} else if (p_category == String("get")) {
-
Ref<VisualScriptPropertyGet> n;
n.instance();
n->set_property(p_text);
@@ -3570,33 +3253,27 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
if (p_category == String("action")) {
if (p_text == "VisualScriptCondition") {
-
Ref<VisualScriptCondition> n;
n.instance();
vnode = n;
}
if (p_text == "VisualScriptSwitch") {
-
Ref<VisualScriptSwitch> n;
n.instance();
vnode = n;
} else if (p_text == "VisualScriptSequence") {
-
Ref<VisualScriptSequence> n;
n.instance();
vnode = n;
} else if (p_text == "VisualScriptIterator") {
-
Ref<VisualScriptIterator> n;
n.instance();
vnode = n;
} else if (p_text == "VisualScriptWhile") {
-
Ref<VisualScriptWhile> n;
n.instance();
vnode = n;
} else if (p_text == "VisualScriptReturn") {
-
Ref<VisualScriptReturn> n;
n.instance();
vnode = n;
@@ -3605,21 +3282,21 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph", new_id);
undo_redo->add_undo_method(this, "_update_graph", new_id);
undo_redo->commit_action();
- if (script_prop_set.is_valid())
+ if (script_prop_set.is_valid()) {
script_prop_set->set_property(p_text);
+ }
port_action_new_node = new_id;
- Ref<VisualScriptNode> vsn = script->get_node(func, port_action_new_node);
+ Ref<VisualScriptNode> vsn = script->get_node(port_action_new_node);
if (Object::cast_to<VisualScriptFunctionCall>(vsn.ptr())) {
-
Ref<VisualScriptFunctionCall> vsfc = vsn;
vsfc->set_function(p_text);
@@ -3631,10 +3308,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
vsfc->set_base_type(String(""));
if (tg.gdclass != StringName()) {
vsfc->set_base_type(tg.gdclass);
-
- } else if (script->get_node(func, port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string;
+ } else if (script->get_node(port_action_node).is_valid()) {
+ PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
+ String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) {
vsfc->set_base_type(base_type);
@@ -3667,9 +3343,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
if (tg.gdclass != StringName()) {
vsp->set_base_type(tg.gdclass);
- } else if (script->get_node(func, port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string;
+ } else if (script->get_node(port_action_node).is_valid()) {
+ PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
+ String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) {
vsp->set_base_type(base_type);
@@ -3697,9 +3373,9 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
if (tg.gdclass != StringName()) {
vsp->set_base_type(tg.gdclass);
- } else if (script->get_node(func, port_action_node).is_valid()) {
- PropertyHint hint = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint;
- String base_type = script->get_node(func, port_action_node)->get_output_value_port_info(port_action_output).hint_string;
+ } else if (script->get_node(port_action_node).is_valid()) {
+ PropertyHint hint = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint;
+ String base_type = script->get_node(port_action_node)->get_output_value_port_info(port_action_output).hint_string;
if (base_type != String() && hint == PROPERTY_HINT_TYPE_STRING) {
vsp->set_base_type(base_type);
}
@@ -3717,19 +3393,16 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri
}
}
if (port_node_exists) {
- Ref<VisualScriptNode> vnode_old = script->get_node(func, port_action_node);
+ Ref<VisualScriptNode> vnode_old = script->get_node(port_action_node);
if (vnode_old.is_valid() && p_connecting) {
connect_seq(vnode_old, vnode, port_action_new_node);
connect_data(vnode_old, vnode, port_action_new_node);
}
}
_update_graph(port_action_new_node);
- if (port_node_exists)
- _update_graph_connections();
}
void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id) {
-
VisualScriptOperator *vnode_operator = Object::cast_to<VisualScriptOperator>(vnode_new.ptr());
if (vnode_operator != nullptr && !vnode_operator->has_input_sequence_port()) {
return;
@@ -3745,29 +3418,27 @@ void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<Visual
return;
}
- StringName func = _get_function_of_node(port_action_node);
-
undo_redo->create_action(TTR("Connect Node Sequence"));
int pass_port = -vnode_old->get_output_sequence_port_count() + 1;
int return_port = port_action_output - 1;
if (vnode_old->get_output_value_port_info(port_action_output).name == String("pass") &&
- !script->get_output_sequence_ports_connected(func, port_action_node).has(pass_port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, pass_port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, pass_port, new_id);
+ !script->get_output_sequence_ports_connected(port_action_node).has(pass_port)) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, pass_port, new_id);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, pass_port, new_id);
} else if (vnode_old->get_output_value_port_info(port_action_output).name == String("return") &&
- !script->get_output_sequence_ports_connected(func, port_action_node).has(return_port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, return_port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, return_port, new_id);
+ !script->get_output_sequence_ports_connected(port_action_node).has(return_port)) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, return_port, new_id);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, return_port, new_id);
} else {
for (int port = 0; port < vnode_old->get_output_sequence_port_count(); port++) {
int count = vnode_old->get_output_sequence_port_count();
- if (port_action_output < count && !script->get_output_sequence_ports_connected(func, port_action_node).has(port_action_output)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port_action_output, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port_action_output, new_id);
+ if (port_action_output < count && !script->get_output_sequence_ports_connected(port_action_node).has(port_action_output)) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port_action_output, new_id);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port_action_output, new_id);
break;
- } else if (!script->get_output_sequence_ports_connected(func, port_action_node).has(port)) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", func, port_action_node, port, new_id);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", func, port_action_node, port, new_id);
+ } else if (!script->get_output_sequence_ports_connected(port_action_node).has(port)) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", port_action_node, port, new_id);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", port_action_node, port, new_id);
break;
}
}
@@ -3777,7 +3448,6 @@ void VisualScriptEditor::connect_seq(Ref<VisualScriptNode> vnode_old, Ref<Visual
}
void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting) {
-
String name = p_text;
if (script->has_function(name)) {
EditorNode::get_singleton()->show_warning(vformat(TTR("Script already has function '%s'"), name));
@@ -3803,9 +3473,9 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons
Ref<VisualScriptFunction> func_node;
func_node.instance();
func_node->set_name(name);
-
+ int fn_id = script->get_available_id();
undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(), "add_function", name);
+ undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id);
for (int i = 0; i < minfo.arguments.size(); i++) {
func_node->add_argument(minfo.arguments[i].type, minfo.arguments[i].name, -1, minfo.arguments[i].hint, minfo.arguments[i].hint_string);
@@ -3813,14 +3483,17 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons
Vector2 ofs = _get_available_pos();
- undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node, ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id);
if (minfo.return_val.type != Variant::NIL || minfo.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
Ref<VisualScriptReturn> ret_node;
ret_node.instance();
ret_node->set_return_type(minfo.return_val.type);
ret_node->set_enable_return_value(true);
ret_node->set_name(name);
- undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id() + 1, ret_node, _get_available_pos(false, ofs + Vector2(500, 0)));
+ int nid = script->get_available_id() + 1;
+ undo_redo->add_do_method(script.ptr(), "add_node", nid, ret_node, _get_available_pos(false, ofs + Vector2(500, 0)));
+ undo_redo->add_undo_method(script.ptr(), "remove_node", nid);
}
undo_redo->add_undo_method(script.ptr(), "remove_function", name);
@@ -3835,21 +3508,16 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons
}
void VisualScriptEditor::_cancel_connect_node() {
- // ensure the cancel is done
+ // Ensure the cancel is done.
port_action_new_node = -1;
}
-int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func) {
-
- StringName func = default_func;
- if (p_func != StringName())
- func = p_func;
-
+int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const Vector2 &p_point) {
Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(p_text);
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(), "add_node", func, new_id, vnode, p_point);
- undo_redo->add_undo_method(script.ptr(), "remove_node", func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, p_point);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -3857,10 +3525,10 @@ int VisualScriptEditor::_create_new_node_from_name(const String &p_text, const V
}
void VisualScriptEditor::_default_value_changed() {
-
- Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(editing_id), editing_id);
- if (vsn.is_null())
+ Ref<VisualScriptNode> vsn = script->get_node(editing_id);
+ if (vsn.is_null()) {
return;
+ }
undo_redo->create_action(TTR("Change Input Value"));
undo_redo->add_do_method(vsn.ptr(), "set_default_input_value", editing_input, default_value_edit->get_variant());
@@ -3872,35 +3540,34 @@ void VisualScriptEditor::_default_value_changed() {
}
void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_input_port) {
-
- Ref<VisualScriptNode> vsn = script->get_node(_get_function_of_node(p_id), p_id);
- if (vsn.is_null())
+ Ref<VisualScriptNode> vsn = script->get_node(p_id);
+ if (vsn.is_null()) {
return;
+ }
PropertyInfo pinfo = vsn->get_input_value_port_info(p_input_port);
Variant existing = vsn->get_default_input_value(p_input_port);
if (pinfo.type != Variant::NIL && existing.get_type() != pinfo.type) {
-
Callable::CallError ce;
- const Variant *existingp = &existing;
- existing = Variant::construct(pinfo.type, &existingp, 1, ce, false);
+ Variant e = existing;
+ const Variant *existingp = &e;
+ Variant::construct(pinfo.type, existing, &existingp, 1, ce);
}
default_value_edit->set_position(Object::cast_to<Control>(p_button)->get_global_position() + Vector2(0, Object::cast_to<Control>(p_button)->get_size().y));
default_value_edit->set_size(Size2(1, 1));
if (pinfo.type == Variant::NODE_PATH) {
-
Node *edited_scene = get_tree()->get_edited_scene_root();
- if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open)
+ if (edited_scene) { // Fixing an old crash bug ( Visual Script Crashes on editing NodePath with an empty scene open).
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (script_node) {
- //pick a node relative to the script, IF the script exists
+ // Pick a node relative to the script, IF the script exists.
pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE;
pinfo.hint_string = script_node->get_path();
} else {
- //pick a path relative to edited scene
+ // Pick a path relative to edited scene.
pinfo.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE;
pinfo.hint_string = get_tree()->get_edited_scene_root()->get_path();
}
@@ -3908,10 +3575,11 @@ void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_i
}
if (default_value_edit->edit(nullptr, pinfo.name, pinfo.type, existing, pinfo.hint, pinfo.hint_string)) {
- if (pinfo.hint == PROPERTY_HINT_MULTILINE_TEXT)
+ if (pinfo.hint == PROPERTY_HINT_MULTILINE_TEXT) {
default_value_edit->popup_centered_ratio();
- else
+ } else {
default_value_edit->popup();
+ }
}
editing_id = p_id;
@@ -3919,19 +3587,16 @@ void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_i
}
void VisualScriptEditor::_show_hint(const String &p_hint) {
-
hint_text->set_text(p_hint);
hint_text->show();
hint_text_timer->start();
}
void VisualScriptEditor::_hide_timer() {
-
hint_text->hide();
}
void VisualScriptEditor::_notification(int p_what) {
-
switch (p_what) {
case NOTIFICATION_READY: {
variable_editor->connect("changed", callable_mp(this, &VisualScriptEditor::_update_members));
@@ -3994,35 +3659,31 @@ void VisualScriptEditor::_notification(int p_what) {
}
void VisualScriptEditor::_graph_ofs_changed(const Vector2 &p_ofs) {
-
- if (updating_graph || !script.is_valid())
+ if (updating_graph || !script.is_valid()) {
return;
+ }
updating_graph = true;
- // Just use the default func for all the properties that need to be handled for drawing rather than adding to the Visual Script Class
- if (script->has_function(default_func)) {
- script->set_function_scroll(default_func, graph->get_scroll_ofs() / EDSCALE);
- script->set_edited(true);
- }
+ script->set_scroll(graph->get_scroll_ofs() / EDSCALE);
+ script->set_edited(true);
updating_graph = false;
}
void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_node) {
-
- if (updating_graph)
+ if (updating_graph) {
return;
-
- StringName func = _get_function_of_node(p_node);
-
- Ref<VisualScriptComment> vsc = script->get_node(func, p_node);
- if (vsc.is_null())
+ }
+ Ref<VisualScriptComment> vsc = script->get_node(p_node);
+ if (vsc.is_null()) {
return;
+ }
Node *node = graph->get_node(itos(p_node));
GraphNode *gn = Object::cast_to<GraphNode>(node);
- if (!gn)
+ if (!gn) {
return;
+ }
updating_graph = true;
@@ -4040,21 +3701,18 @@ void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_
}
void VisualScriptEditor::_menu_option(int p_what) {
-
switch (p_what) {
case EDIT_DELETE_NODES: {
_on_nodes_delete();
} break;
case EDIT_TOGGLE_BREAKPOINT: {
-
List<String> reselect;
for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
if (gn) {
if (gn->is_selected()) {
int id = String(gn->get_name()).to_int();
- StringName func = _get_function_of_node(id);
- Ref<VisualScriptNode> vsn = script->get_node(func, id);
+ Ref<VisualScriptNode> vsn = script->get_node(id);
if (vsn.is_valid()) {
vsn->set_breakpoint(!vsn->is_breakpoint());
reselect.push_back(gn->get_name());
@@ -4076,61 +3734,47 @@ void VisualScriptEditor::_menu_option(int p_what) {
} break;
case EDIT_COPY_NODES:
case EDIT_CUT_NODES: {
- if (!script->has_function(default_func))
- break;
-
clipboard->nodes.clear();
clipboard->data_connections.clear();
clipboard->sequence_connections.clear();
- Set<String> funcs;
for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i));
if (gn) {
if (gn->is_selected()) {
-
- int id = String(gn->get_name()).to_int();
- StringName func = _get_function_of_node(id);
- Ref<VisualScriptNode> node = script->get_node(func, id);
+ int id = gn->get_name().operator String().to_int();
+ Ref<VisualScriptNode> node = script->get_node(id);
if (Object::cast_to<VisualScriptFunction>(*node)) {
EditorNode::get_singleton()->show_warning(TTR("Can't copy the function node."));
return;
}
if (node.is_valid()) {
clipboard->nodes[id] = node->duplicate(true);
- clipboard->nodes_positions[id] = script->get_node_position(func, id);
- funcs.insert(String(func));
+ clipboard->nodes_positions[id] = script->get_node_position(id);
}
}
}
}
- if (clipboard->nodes.empty())
+ if (clipboard->nodes.is_empty()) {
break;
+ }
- for (Set<String>::Element *F = funcs.front(); F; F = F->next()) {
- List<VisualScript::SequenceConnection> sequence_connections;
-
- script->get_sequence_connection_list(F->get(), &sequence_connections);
-
- for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) {
-
- if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) {
+ List<VisualScript::SequenceConnection> sequence_connections;
+ script->get_sequence_connection_list(&sequence_connections);
- clipboard->sequence_connections.insert(E->get());
- }
+ for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) {
+ if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) {
+ clipboard->sequence_connections.insert(E->get());
}
+ }
- List<VisualScript::DataConnection> data_connections;
-
- script->get_data_connection_list(F->get(), &data_connections);
-
- for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
-
- if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) {
+ List<VisualScript::DataConnection> data_connections;
+ script->get_data_connection_list(&data_connections);
- clipboard->data_connections.insert(E->get());
- }
+ for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
+ if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) {
+ clipboard->data_connections.insert(E->get());
}
}
if (p_what == EDIT_CUT_NODES) {
@@ -4139,10 +3783,7 @@ void VisualScriptEditor::_menu_option(int p_what) {
} break;
case EDIT_PASTE_NODES: {
- if (!script->has_function(default_func))
- break;
-
- if (clipboard->nodes.empty()) {
+ if (clipboard->nodes.is_empty()) {
EditorNode::get_singleton()->show_warning(TTR("Clipboard is empty!"));
break;
}
@@ -4157,20 +3798,15 @@ void VisualScriptEditor::_menu_option(int p_what) {
Set<Vector2> existing_positions;
{
- List<StringName> functions;
- script->get_function_list(&functions);
- for (List<StringName>::Element *F = functions.front(); F; F = F->next()) {
- List<int> nodes;
- script->get_node_list(F->get(), &nodes);
- for (List<int>::Element *E = nodes.front(); E; E = E->next()) {
- Vector2 pos = script->get_node_position(F->get(), E->get()).snapped(Vector2(2, 2));
- existing_positions.insert(pos);
- }
+ List<int> nodes;
+ script->get_node_list(&nodes);
+ for (List<int>::Element *E = nodes.front(); E; E = E->next()) {
+ Vector2 pos = script->get_node_position(E->get()).snapped(Vector2(2, 2));
+ existing_positions.insert(pos);
}
}
for (Map<int, Ref<VisualScriptNode>>::Element *E = clipboard->nodes.front(); E; E = E->next()) {
-
Ref<VisualScriptNode> node = E->get()->duplicate();
int new_id = idc++;
@@ -4184,20 +3820,18 @@ void VisualScriptEditor::_menu_option(int p_what) {
paste_pos += Vector2(20, 20) * EDSCALE;
}
- undo_redo->add_do_method(script.ptr(), "add_node", default_func, new_id, node, paste_pos);
- undo_redo->add_undo_method(script.ptr(), "remove_node", default_func, new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", new_id, node, paste_pos);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", new_id);
}
for (Set<VisualScript::SequenceConnection>::Element *E = clipboard->sequence_connections.front(); E; E = E->next()) {
-
- undo_redo->add_do_method(script.ptr(), "sequence_connect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
- undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", default_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
}
for (Set<VisualScript::DataConnection>::Element *E = clipboard->data_connections.front(); E; E = E->next()) {
-
- undo_redo->add_do_method(script.ptr(), "data_connect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
- undo_redo->add_undo_method(script.ptr(), "data_disconnect", default_func, remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
+ undo_redo->add_do_method(script.ptr(), "data_connect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_disconnect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port);
}
undo_redo->add_do_method(this, "_update_graph");
@@ -4214,8 +3848,7 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
} break;
case EDIT_CREATE_FUNCTION: {
-
- StringName function = "";
+ // Create Function.
Map<int, Ref<VisualScriptNode>> nodes;
Set<int> selections;
for (int i = 0; i < graph->get_child_count(); i++) {
@@ -4223,20 +3856,14 @@ void VisualScriptEditor::_menu_option(int p_what) {
if (gn) {
if (gn->is_selected()) {
int id = String(gn->get_name()).to_int();
- StringName func = _get_function_of_node(id);
- Ref<VisualScriptNode> node = script->get_node(func, id);
+ Ref<VisualScriptNode> node = script->get_node(id);
if (Object::cast_to<VisualScriptFunction>(*node)) {
EditorNode::get_singleton()->show_warning(TTR("Can't create function with a function node."));
return;
}
if (node.is_valid()) {
- if (func != function && function != StringName("")) {
- EditorNode::get_singleton()->show_warning(TTR("Can't create function of nodes from nodes of multiple functions."));
- return;
- }
nodes.insert(id, node);
selections.insert(id);
- function = func;
}
}
}
@@ -4255,46 +3882,46 @@ void VisualScriptEditor::_menu_option(int p_what) {
int start_node = -1;
Set<int> end_nodes;
if (nodes.size() == 1) {
- Ref<VisualScriptNode> nd = script->get_node(function, nodes.front()->key());
- if (nd.is_valid() && nd->has_input_sequence_port())
+ Ref<VisualScriptNode> nd = script->get_node(nodes.front()->key());
+ if (nd.is_valid() && nd->has_input_sequence_port()) {
start_node = nodes.front()->key();
- else {
+ } else {
EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port."));
return;
}
} else {
List<VisualScript::SequenceConnection> seqs;
- script->get_sequence_connection_list(function, &seqs);
+ script->get_sequence_connection_list(&seqs);
if (seqs.size() == 0) {
- // in case there are no sequence connections
- // select the top most node cause that's probably how
- // the user wants to connect the nodes
+ // In case there are no sequence connections,
+ // select the top most node cause that's probably how,
+ // the user wants to connect the nodes.
int top_nd = -1;
Vector2 top;
for (Map<int, Ref<VisualScriptNode>>::Element *E = nodes.front(); E; E = E->next()) {
- Ref<VisualScriptNode> nd = script->get_node(function, E->key());
+ Ref<VisualScriptNode> nd = script->get_node(E->key());
if (nd.is_valid() && nd->has_input_sequence_port()) {
if (top_nd < 0) {
top_nd = E->key();
- top = script->get_node_position(function, top_nd);
+ top = script->get_node_position(top_nd);
}
- Vector2 pos = script->get_node_position(function, E->key());
+ Vector2 pos = script->get_node_position(E->key());
if (top.y > pos.y) {
top_nd = E->key();
top = pos;
}
}
}
- Ref<VisualScriptNode> nd = script->get_node(function, top_nd);
- if (nd.is_valid() && nd->has_input_sequence_port())
+ Ref<VisualScriptNode> nd = script->get_node(top_nd);
+ if (nd.is_valid() && nd->has_input_sequence_port()) {
start_node = top_nd;
- else {
+ } else {
EditorNode::get_singleton()->show_warning(TTR("Select at least one node with sequence port."));
return;
}
} else {
- // pick the node with input sequence
+ // Pick the node with input sequence.
Set<int> nodes_from;
Set<int> nodes_to;
for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) {
@@ -4315,13 +3942,13 @@ void VisualScriptEditor::_menu_option(int p_what) {
nodes_to.insert(E->get().to_node);
}
- // to use to add return nodes
+ // To use to add return nodes.
_get_ends(start_node, seqs, selections, end_nodes);
if (start_node == -1) {
- // if we still don't have a start node then
- // run through the nodes and select the first tree node
- // ie node without any input sequence but output sequence
+ // If we still don't have a start node then,
+ // run through the nodes and select the first tree node,
+ // ie node without any input sequence but output sequence.
for (Set<int>::Element *E = nodes_from.front(); E; E = E->next()) {
if (!nodes_to.has(E->get())) {
start_node = E->get();
@@ -4332,20 +3959,20 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
if (start_node == -1) {
- return; // this should not happen, but just in case something goes wrong
+ return; // This should not happen, but just in case something goes wrong.
}
List<Variant::Type> inputs; // input types
List<Pair<int, int>> input_connections;
{
List<VisualScript::DataConnection> dats;
- script->get_data_connection_list(function, &dats);
+ script->get_data_connection_list(&dats);
for (List<VisualScript::DataConnection>::Element *E = dats.front(); E; E = E->next()) {
if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) {
datamove.insert(E->get());
} else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) {
- // add all these as inputs for the Function
- Ref<VisualScriptNode> node = script->get_node(function, E->get().to_node);
+ // Add all these as inputs for the Function.
+ Ref<VisualScriptNode> node = script->get_node(E->get().to_node);
if (node.is_valid()) {
dataext.insert(E->get());
PropertyInfo pi = node->get_input_value_port_info(E->get().to_port);
@@ -4357,59 +3984,55 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
}
}
-
- String new_fn = _validate_name("new_function");
-
- Vector2 ofs = _get_available_pos(false, script->get_node_position(function, start_node) - Vector2(80, 150));
-
- Ref<VisualScriptFunction> func_node;
- func_node.instance();
- func_node->set_name(new_fn);
-
- undo_redo->create_action(TTR("Create Function"));
-
- undo_redo->add_do_method(script.ptr(), "add_function", new_fn);
int fn_id = script->get_available_id();
- undo_redo->add_do_method(script.ptr(), "add_node", new_fn, fn_id, func_node, ofs);
- undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn);
- undo_redo->add_do_method(this, "_update_members");
- undo_redo->add_undo_method(this, "_update_members");
- undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
- undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
-
- // Move the nodes
+ {
+ String new_fn = _validate_name("new_function");
- for (Map<int, Ref<VisualScriptNode>>::Element *E = nodes.front(); E; E = E->next()) {
- undo_redo->add_do_method(script.ptr(), "remove_node", function, E->key());
- undo_redo->add_do_method(script.ptr(), "add_node", new_fn, E->key(), E->get(), script->get_node_position(function, E->key()));
+ Vector2 ofs = _get_available_pos(false, script->get_node_position(start_node) - Vector2(80, 150));
- // undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, E->key()); not needed cause we already remove the function :P
- undo_redo->add_undo_method(script.ptr(), "add_node", function, E->key(), E->get(), script->get_node_position(function, E->key()));
- }
+ Ref<VisualScriptFunction> func_node;
+ func_node.instance();
+ func_node->set_name(new_fn);
- for (Set<VisualScript::SequenceConnection>::Element *E = seqmove.front(); E; E = E->next()) {
- undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, E->get().from_node, E->get().from_output, E->get().to_node);
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node);
- }
+ undo_redo->create_action(TTR("Create Function"));
- for (Set<VisualScript::DataConnection>::Element *E = datamove.front(); E; E = E->next()) {
- undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
- undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ undo_redo->add_do_method(script.ptr(), "add_function", new_fn, fn_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
+ undo_redo->add_do_method(this, "emit_signal", "edited_script_changed");
+ undo_redo->add_undo_method(this, "emit_signal", "edited_script_changed");
+ // Might make the system more intelligent by checking port from info.
+ int i = 0;
+ List<Pair<int, int>>::Element *F = input_connections.front();
+ for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) {
+ func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i);
+ undo_redo->add_do_method(script.ptr(), "data_connect", fn_id, i, F->get().first, F->get().second);
+ i++; // increment i
+ }
+ // Ensure Preview Selection is of newly created function node.
+ if (selections.size()) {
+ EditorNode::get_singleton()->push_item(func_node.ptr());
+ }
}
+ // Move the nodes.
- // Add undo for external connections as well so that it's easier to revert back and forth
- // these didn't require do methods as it's already handled internally by other do calls
+ // Handles reconnection of sequence connections on undo, start here in case of issues.
for (Set<VisualScript::SequenceConnection>::Element *E = seqext.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", function, E->get().from_node, E->get().from_output, E->get().to_node);
+ undo_redo->add_do_method(script.ptr(), "sequence_disconnect", E->get().from_node, E->get().from_output, E->get().to_node);
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node);
}
for (Set<VisualScript::DataConnection>::Element *E = dataext.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", function, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
}
- // I don't really think we need support for non sequenced functions at this moment
- undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, fn_id, 0, start_node);
+ // I don't really think we need support for non sequenced functions at this moment.
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", fn_id, 0, start_node);
- // end nodes are mapped to the return nodes with data connections if possible
+ // Could fail with the new changes, start here when searching for bugs in create function shortcut.
int m = 1;
for (Set<int>::Element *G = end_nodes.front(); G; G = G->next()) {
Ref<VisualScriptReturn> ret_node;
@@ -4417,36 +4040,27 @@ void VisualScriptEditor::_menu_option(int p_what) {
int ret_id = fn_id + (m++);
selections.insert(ret_id);
- Vector2 ofsi = _get_available_pos(false, script->get_node_position(function, G->get()) + Vector2(80, -100));
- undo_redo->add_do_method(script.ptr(), "add_node", new_fn, ret_id, ret_node, ofsi);
- undo_redo->add_undo_method(script.ptr(), "remove_node", new_fn, ret_id);
+ Vector2 ofsi = _get_available_pos(false, script->get_node_position(G->get()) + Vector2(80, -100));
+ undo_redo->add_do_method(script.ptr(), "add_node", ret_id, ret_node, ofsi);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", ret_id);
- undo_redo->add_do_method(script.ptr(), "sequence_connect", new_fn, G->get(), 0, ret_id);
- // add data outputs from each of the end_nodes
- Ref<VisualScriptNode> vsn = script->get_node(function, G->get());
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", G->get(), 0, ret_id);
+ // Add data outputs from each of the end_nodes.
+ Ref<VisualScriptNode> vsn = script->get_node(G->get());
if (vsn.is_valid() && vsn->get_output_value_port_count() > 0) {
ret_node->set_enable_return_value(true);
- // use the zeroth data port cause that's the likely one that is planned to be used
+ // Use the zeroth data port cause that's the likely one that is planned to be used.
ret_node->set_return_type(vsn->get_output_value_port_info(0).type);
- undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, G->get(), 0, ret_id, 0);
+ undo_redo->add_do_method(script.ptr(), "data_connect", G->get(), 0, ret_id, 0);
}
}
- // * might make the system more intelligent by checking port from info.
- int i = 0;
- List<Pair<int, int>>::Element *F = input_connections.front();
- for (List<Variant::Type>::Element *E = inputs.front(); E && F; E = E->next(), F = F->next()) {
- func_node->add_argument(E->get(), "arg_" + String::num_int64(i), i);
- undo_redo->add_do_method(script.ptr(), "data_connect", new_fn, fn_id, i, F->get().first, F->get().second);
- i++; // increment i
- }
-
undo_redo->add_do_method(this, "_update_graph");
undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- // make sure all Nodes get marked for selection so that they can be moved together
+ // Make sure all Nodes get marked for selection so that they can be moved together.
selections.insert(fn_id);
for (int k = 0; k < graph->get_child_count(); k++) {
GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(k));
@@ -4456,11 +4070,6 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
}
- // Ensure Preview Selection is of newly created function node
- if (selections.size()) {
- EditorNode::get_singleton()->push_item(func_node.ptr());
- }
-
} break;
case REFRESH_GRAPH: {
_update_graph();
@@ -4468,16 +4077,16 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
}
-// this is likely going to be very slow and I am not sure if I should keep it
-// but I hope that it will not be a problem considering that we won't be creating functions so frequently
-// and cyclic connections would be a problem but hopefully we won't let them get to this point
+// This is likely going to be very slow and I am not sure if I should keep it,
+// but I hope that it will not be a problem considering that we won't be creating functions so frequently,
+// and cyclic connections would be a problem but hopefully we won't let them get to this point.
void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes) {
for (const List<VisualScript::SequenceConnection>::Element *E = p_seqs.front(); E; E = E->next()) {
int from = E->get().from_node;
int to = E->get().to_node;
if (from == p_node && p_selected.has(to)) {
- // this is an interior connection move forward to the to node
+ // This is an interior connection move forward to the to node.
_get_ends(to, p_seqs, p_selected, r_end_nodes);
} else if (from == p_node && !p_selected.has(to)) {
r_end_nodes.insert(from);
@@ -4486,7 +4095,6 @@ void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::Sequence
}
void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) {
-
TreeItem *ti = members->get_selected();
ERR_FAIL_COND(!ti);
@@ -4504,7 +4112,6 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) {
Ref<Texture2D> edit_icon = Control::get_theme_icon("Edit", "EditorIcons");
if (ti->get_parent() == root->get_children()) {
-
member_type = MEMBER_FUNCTION;
member_name = ti->get_text(0);
member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
@@ -4515,7 +4122,6 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) {
}
if (ti->get_parent() == root->get_children()->get_next()) {
-
member_type = MEMBER_VARIABLE;
member_name = ti->get_text(0);
member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
@@ -4526,7 +4132,6 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) {
}
if (ti->get_parent() == root->get_children()->get_next()->get_next()) {
-
member_type = MEMBER_SIGNAL;
member_name = ti->get_text(0);
member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT);
@@ -4538,39 +4143,32 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) {
}
void VisualScriptEditor::_member_option(int p_option) {
-
switch (member_type) {
case MEMBER_FUNCTION: {
-
if (p_option == MEMBER_REMOVE) {
- //delete the function
+ // Delete the function.
String name = member_name;
-
+ List<String> lst;
+ int fn_node = script->get_function_node_id(name);
undo_redo->create_action(TTR("Remove Function"));
undo_redo->add_do_method(script.ptr(), "remove_function", name);
- undo_redo->add_undo_method(script.ptr(), "add_function", name);
- List<int> nodes;
- script->get_node_list(name, &nodes);
- for (List<int>::Element *E = nodes.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "add_node", name, E->get(), script->get_node(name, E->get()), script->get_node_position(name, E->get()));
- }
-
- List<VisualScript::SequenceConnection> seq_connections;
-
- script->get_sequence_connection_list(name, &seq_connections);
-
- for (List<VisualScript::SequenceConnection>::Element *E = seq_connections.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "sequence_connect", name, E->get().from_node, E->get().from_output, E->get().to_node);
+ undo_redo->add_do_method(script.ptr(), "remove_node", fn_node);
+ undo_redo->add_undo_method(script.ptr(), "add_function", name, fn_node);
+ undo_redo->add_undo_method(script.ptr(), "add_node", fn_node, script->get_node(fn_node), script->get_node_position(fn_node));
+ List<VisualScript::SequenceConnection> seqcons;
+ script->get_sequence_connection_list(&seqcons);
+ for (const List<VisualScript::SequenceConnection>::Element *E = seqcons.front(); E; E = E->next()) {
+ if (E->get().from_node == fn_node) {
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", fn_node, E->get().from_output, E->get().to_node);
+ }
}
-
- List<VisualScript::DataConnection> data_connections;
-
- script->get_data_connection_list(name, &data_connections);
-
- for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) {
- undo_redo->add_undo_method(script.ptr(), "data_connect", name, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ List<VisualScript::DataConnection> datcons;
+ script->get_data_connection_list(&datcons);
+ for (const List<VisualScript::DataConnection>::Element *E = datcons.front(); E; E = E->next()) {
+ if (E->get().from_node == fn_node) {
+ undo_redo->add_undo_method(script.ptr(), "data_connect", fn_node, E->get().from_port, E->get().to_node, E->get().to_port);
+ }
}
-
undo_redo->add_do_method(this, "_update_members");
undo_redo->add_undo_method(this, "_update_members");
undo_redo->add_do_method(this, "_update_graph");
@@ -4584,7 +4182,6 @@ void VisualScriptEditor::_member_option(int p_option) {
}
} break;
case MEMBER_VARIABLE: {
-
String name = member_name;
if (p_option == MEMBER_REMOVE) {
@@ -4625,14 +4222,13 @@ void VisualScriptEditor::_member_option(int p_option) {
}
}
-void VisualScriptEditor::add_syntax_highlighter(SyntaxHighlighter *p_highlighter) {
+void VisualScriptEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
}
-void VisualScriptEditor::set_syntax_highlighter(SyntaxHighlighter *p_highlighter) {
+void VisualScriptEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) {
}
void VisualScriptEditor::_bind_methods() {
-
ClassDB::bind_method("_move_node", &VisualScriptEditor::_move_node);
ClassDB::bind_method("_update_graph", &VisualScriptEditor::_update_graph, DEFVAL(-1));
@@ -4652,10 +4248,11 @@ void VisualScriptEditor::_bind_methods() {
ClassDB::bind_method("_update_members", &VisualScriptEditor::_update_members);
ClassDB::bind_method("_generic_search", &VisualScriptEditor::_generic_search);
+
+ ClassDB::bind_method(D_METHOD("add_syntax_highlighter", "highlighter"), &VisualScriptEditor::add_syntax_highlighter);
}
VisualScriptEditor::VisualScriptEditor() {
-
if (!clipboard) {
clipboard = memnew(Clipboard);
}
@@ -4664,6 +4261,7 @@ VisualScriptEditor::VisualScriptEditor() {
saved_position = Vector2(0, 0);
edit_menu = memnew(MenuButton);
+ edit_menu->set_shortcut_context(this);
edit_menu->set_text(TTR("Edit"));
edit_menu->set_switch_on_hover(true);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/delete_selected"), EDIT_DELETE_NODES);
@@ -4720,10 +4318,10 @@ VisualScriptEditor::VisualScriptEditor() {
graph = memnew(GraphEdit);
add_child(graph);
graph->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- graph->set_anchors_and_margins_preset(Control::PRESET_WIDE);
+ graph->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
graph->connect("node_selected", callable_mp(this, &VisualScriptEditor::_node_selected));
- graph->connect("_begin_node_move", callable_mp(this, &VisualScriptEditor::_begin_node_move));
- graph->connect("_end_node_move", callable_mp(this, &VisualScriptEditor::_end_node_move));
+ graph->connect("begin_node_move", callable_mp(this, &VisualScriptEditor::_begin_node_move));
+ graph->connect("end_node_move", callable_mp(this, &VisualScriptEditor::_end_node_move));
graph->connect("delete_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_delete));
graph->connect("duplicate_nodes_request", callable_mp(this, &VisualScriptEditor::_on_nodes_duplicate));
graph->connect("gui_input", callable_mp(this, &VisualScriptEditor::_graph_gui_input));
@@ -4792,8 +4390,8 @@ VisualScriptEditor::VisualScriptEditor() {
function_create_dialog = memnew(ConfirmationDialog);
function_create_dialog->set_title(TTR("Create Function"));
function_create_dialog->add_child(function_vb);
- function_create_dialog->get_ok()->set_text(TTR("Create"));
- function_create_dialog->get_ok()->connect("pressed", callable_mp(this, &VisualScriptEditor::_create_function));
+ function_create_dialog->get_ok_button()->set_text(TTR("Create"));
+ function_create_dialog->get_ok_button()->connect("pressed", callable_mp(this, &VisualScriptEditor::_create_function));
add_child(function_create_dialog);
select_func_text = memnew(Label);
@@ -4804,9 +4402,9 @@ VisualScriptEditor::VisualScriptEditor() {
add_child(select_func_text);
hint_text = memnew(Label);
- hint_text->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -100);
- hint_text->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
- hint_text->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ hint_text->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -100);
+ hint_text->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
+ hint_text->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
hint_text->set_align(Label::ALIGN_CENTER);
hint_text->set_valign(Label::VALIGN_CENTER);
graph->add_child(hint_text);
@@ -4836,7 +4434,7 @@ VisualScriptEditor::VisualScriptEditor() {
graph->connect("connection_to_empty", callable_mp(this, &VisualScriptEditor::_graph_connect_to_empty));
edit_signal_dialog = memnew(AcceptDialog);
- edit_signal_dialog->get_ok()->set_text(TTR("Close"));
+ edit_signal_dialog->get_ok_button()->set_text(TTR("Close"));
add_child(edit_signal_dialog);
signal_editor = memnew(VisualScriptEditorSignalEdit);
@@ -4846,7 +4444,7 @@ VisualScriptEditor::VisualScriptEditor() {
edit_signal_edit->edit(signal_editor);
edit_variable_dialog = memnew(AcceptDialog);
- edit_variable_dialog->get_ok()->set_text(TTR("Close"));
+ edit_variable_dialog->get_ok_button()->set_text(TTR("Close"));
add_child(edit_variable_dialog);
variable_editor = memnew(VisualScriptEditorVariableEdit);
@@ -4865,7 +4463,6 @@ VisualScriptEditor::VisualScriptEditor() {
updating_members = false;
set_process_input(true);
- set_process_unhandled_input(true);
default_value_edit = memnew(CustomPropertyEditor);
add_child(default_value_edit);
@@ -4879,7 +4476,7 @@ VisualScriptEditor::VisualScriptEditor() {
new_connect_node_select = memnew(VisualScriptPropertySelector);
add_child(new_connect_node_select);
new_connect_node_select->connect("selected", callable_mp(this, &VisualScriptEditor::_selected_connect_node));
- new_connect_node_select->get_cancel()->connect("pressed", callable_mp(this, &VisualScriptEditor::_cancel_connect_node));
+ new_connect_node_select->get_cancel_button()->connect("pressed", callable_mp(this, &VisualScriptEditor::_cancel_connect_node));
new_virtual_method_select = memnew(VisualScriptPropertySelector);
add_child(new_virtual_method_select);
@@ -4887,14 +4484,12 @@ VisualScriptEditor::VisualScriptEditor() {
}
VisualScriptEditor::~VisualScriptEditor() {
-
undo_redo->clear_history(); // Avoid crashes.
memdelete(signal_editor);
memdelete(variable_editor);
}
static ScriptEditorBase *create_editor(const RES &p_resource) {
-
if (Object::cast_to<VisualScript>(*p_resource)) {
return memnew(VisualScriptEditor);
}
@@ -4905,12 +4500,12 @@ static ScriptEditorBase *create_editor(const RES &p_resource) {
VisualScriptEditor::Clipboard *VisualScriptEditor::clipboard = nullptr;
void VisualScriptEditor::free_clipboard() {
- if (clipboard)
+ if (clipboard) {
memdelete(clipboard);
+ }
}
static void register_editor_callback() {
-
ScriptEditor::register_create_script_editor_function(create_editor);
ED_SHORTCUT("visual_script_editor/delete_selected", TTR("Delete Selected"), KEY_DELETE);
@@ -4925,13 +4520,11 @@ static void register_editor_callback() {
}
void VisualScriptEditor::register_editor() {
-
// Too early to register stuff here, request a callback.
EditorNode::add_plugin_init_callback(register_editor_callback);
}
Ref<VisualScriptNode> _VisualScriptEditor::create_node_custom(const String &p_name) {
-
Ref<VisualScriptCustomNode> node;
node.instance();
node->set_script(singleton->custom_nodes[p_name]);
diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h
index d9494e4d04..bb6f194286 100644
--- a/modules/visual_script/visual_script_editor.h
+++ b/modules/visual_script/visual_script_editor.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -64,7 +64,6 @@ class VisualScriptEditor : public ScriptEditorBase {
};
enum PortAction {
-
CREATE_CALL_SET_GET,
CREATE_ACTION,
};
@@ -137,8 +136,6 @@ class VisualScriptEditor : public ScriptEditorBase {
};
HashMap<StringName, Ref<StyleBox>> node_styles;
- StringName edited_func;
- StringName default_func;
void _update_graph_connections();
void _update_graph(int p_only_id = -1);
@@ -146,13 +143,13 @@ class VisualScriptEditor : public ScriptEditorBase {
bool updating_members;
void _update_members();
+ String _sanitized_variant_text(const StringName &property_name);
StringName selected;
String _validate_name(const String &p_name) const;
struct Clipboard {
-
Map<int, Ref<VisualScriptNode>> nodes;
Map<int, Vector2> nodes_positions;
@@ -177,7 +174,7 @@ class VisualScriptEditor : public ScriptEditorBase {
Vector2 mouse_up_position;
- void _port_action_menu(int p_option, const StringName &p_func);
+ void _port_action_menu(int p_option);
void connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id);
@@ -185,13 +182,13 @@ class VisualScriptEditor : public ScriptEditorBase {
void connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id);
void _cancel_connect_node();
- int _create_new_node_from_name(const String &p_text, const Vector2 &p_point, const StringName &p_func = StringName());
+ int _create_new_node_from_name(const String &p_text, const Vector2 &p_point);
void _selected_new_virtual_method(const String &p_text, const String &p_category, const bool p_connecting);
int error_line;
void _node_selected(Node *p_node);
- void _center_on_node(const StringName &p_func, int p_id);
+ void _center_on_node(int p_id);
void _node_filter_changed(const String &p_text);
void _change_base_type_callback();
@@ -202,7 +199,7 @@ class VisualScriptEditor : public ScriptEditorBase {
void _begin_node_move();
void _end_node_move();
- void _move_node(const StringName &p_func, int p_id, const Vector2 &p_to);
+ void _move_node(int p_id, const Vector2 &p_to);
void _get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes);
@@ -212,7 +209,7 @@ class VisualScriptEditor : public ScriptEditorBase {
void _graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot);
void _graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos);
- void _node_ports_changed(const String &p_func, int p_id);
+ void _node_ports_changed(int p_id);
void _node_create();
void _update_available_nodes();
@@ -229,10 +226,8 @@ class VisualScriptEditor : public ScriptEditorBase {
void _port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input);
Vector2 _get_available_pos(bool centered = true, Vector2 ofs = Vector2()) const;
- StringName _get_function_of_node(int p_id) const;
- void _move_nodes_with_rescan(const StringName &p_func_from, const StringName &p_func_to, int p_id);
- bool node_has_sequence_connections(const StringName &p_func, int p_id);
+ bool node_has_sequence_connections(int p_id);
void _generic_search(String p_base_type = "", Vector2 pos = Vector2(), bool node_centered = false);
@@ -289,39 +284,40 @@ protected:
static void _bind_methods();
public:
- virtual void add_syntax_highlighter(SyntaxHighlighter *p_highlighter);
- virtual void set_syntax_highlighter(SyntaxHighlighter *p_highlighter);
-
- virtual void apply_code();
- virtual RES get_edited_resource() const;
- virtual void set_edited_resource(const RES &p_res);
- virtual Vector<String> get_functions();
- virtual void reload_text();
- virtual String get_name();
- virtual Ref<Texture2D> get_theme_icon();
- virtual bool is_unsaved();
- virtual Variant get_edit_state();
- virtual void set_edit_state(const Variant &p_state);
- virtual void goto_line(int p_line, bool p_with_error = false);
- 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();
- virtual void tag_saved_version();
- virtual void reload(bool p_soft);
- virtual void get_breakpoints(List<int> *p_breakpoints);
- virtual void add_callback(const String &p_function, PackedStringArray p_args);
- virtual void update_settings();
- virtual bool show_members_overview();
- virtual void set_debugger_active(bool p_active);
- virtual void set_tooltip_request_func(String p_method, Object *p_obj);
- virtual Control *get_edit_menu();
- virtual void clear_edit_menu();
- virtual bool can_lose_focus_on_node_selection() { return false; }
- virtual void validate();
+ virtual void add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override;
+ virtual void set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override;
+
+ virtual void apply_code() override;
+ virtual RES get_edited_resource() const override;
+ virtual void set_edited_resource(const RES &p_res) override;
+ virtual void enable_editor() override;
+ virtual Vector<String> get_functions() override;
+ virtual void reload_text() override;
+ virtual String get_name() override;
+ virtual Ref<Texture2D> get_theme_icon() override;
+ virtual bool is_unsaved() override;
+ virtual Variant get_edit_state() override;
+ virtual void set_edit_state(const Variant &p_state) override;
+ virtual void goto_line(int p_line, bool p_with_error = false) override;
+ virtual void set_executing_line(int p_line) override;
+ virtual void clear_executing_line() override;
+ virtual void trim_trailing_whitespace() override;
+ virtual void insert_final_newline() override;
+ virtual void convert_indent_to_spaces() override;
+ virtual void convert_indent_to_tabs() override;
+ virtual void ensure_focus() override;
+ virtual void tag_saved_version() override;
+ virtual void reload(bool p_soft) override;
+ virtual Array get_breakpoints() override;
+ virtual void add_callback(const String &p_function, PackedStringArray p_args) override;
+ virtual void update_settings() override;
+ virtual bool show_members_overview() override;
+ virtual void set_debugger_active(bool p_active) override;
+ virtual void set_tooltip_request_func(String p_method, Object *p_obj) override;
+ virtual Control *get_edit_menu() override;
+ virtual void clear_edit_menu() override;
+ virtual bool can_lose_focus_on_node_selection() override { return false; }
+ virtual void validate() override;
static void register_editor();
diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp
index 71ed483d65..9596fda95c 100644
--- a/modules/visual_script/visual_script_expression.cpp
+++ b/modules/visual_script/visual_script_expression.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,7 +31,6 @@
#include "visual_script_expression.h"
bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_value) {
-
if (String(p_name) == "expression") {
expression = p_value;
expression_dirty = true;
@@ -52,7 +51,6 @@ bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_val
}
if (String(p_name) == "input_count") {
-
int from = inputs.size();
inputs.resize(int(p_value));
for (int i = from; i < inputs.size(); i++) {
@@ -70,17 +68,14 @@ bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_val
}
if (String(p_name).begins_with("input_")) {
-
int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int();
ERR_FAIL_INDEX_V(idx, inputs.size(), false);
String what = String(p_name).get_slice("/", 1);
if (what == "type") {
-
inputs.write[idx].type = Variant::Type(int(p_value));
} else if (what == "name") {
-
inputs.write[idx].name = p_value;
} else {
return false;
@@ -95,7 +90,6 @@ bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_val
}
bool VisualScriptExpression::_get(const StringName &p_name, Variant &r_ret) const {
-
if (String(p_name) == "expression") {
r_ret = expression;
return true;
@@ -117,17 +111,14 @@ bool VisualScriptExpression::_get(const StringName &p_name, Variant &r_ret) cons
}
if (String(p_name).begins_with("input_")) {
-
int idx = String(p_name).get_slicec('_', 1).get_slicec('/', 0).to_int();
ERR_FAIL_INDEX_V(idx, inputs.size(), false);
String what = String(p_name).get_slice("/", 1);
if (what == "type") {
-
r_ret = inputs[idx].type;
} else if (what == "name") {
-
r_ret = inputs[idx].name;
} else {
return false;
@@ -138,8 +129,8 @@ bool VisualScriptExpression::_get(const StringName &p_name, Variant &r_ret) cons
return false;
}
-void VisualScriptExpression::_get_property_list(List<PropertyInfo> *p_list) const {
+void VisualScriptExpression::_get_property_list(List<PropertyInfo> *p_list) const {
String argt = "Any";
for (int i = 1; i < Variant::VARIANT_MAX; i++) {
argt += "," + Variant::get_type_name(Variant::Type(i));
@@ -151,117 +142,99 @@ void VisualScriptExpression::_get_property_list(List<PropertyInfo> *p_list) cons
p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced"));
for (int i = 0; i < inputs.size(); i++) {
-
p_list->push_back(PropertyInfo(Variant::INT, "input_" + itos(i) + "/type", PROPERTY_HINT_ENUM, argt));
p_list->push_back(PropertyInfo(Variant::STRING, "input_" + itos(i) + "/name"));
}
}
int VisualScriptExpression::get_output_sequence_port_count() const {
-
return sequenced ? 1 : 0;
}
-bool VisualScriptExpression::has_input_sequence_port() const {
+bool VisualScriptExpression::has_input_sequence_port() const {
return sequenced;
}
String VisualScriptExpression::get_output_sequence_port_text(int p_port) const {
-
return String();
}
int VisualScriptExpression::get_input_value_port_count() const {
-
return inputs.size();
}
-int VisualScriptExpression::get_output_value_port_count() const {
+int VisualScriptExpression::get_output_value_port_count() const {
return 1;
}
PropertyInfo VisualScriptExpression::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo(inputs[p_idx].type, inputs[p_idx].name);
}
-PropertyInfo VisualScriptExpression::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptExpression::get_output_value_port_info(int p_idx) const {
return PropertyInfo(output_type, "result");
}
String VisualScriptExpression::get_caption() const {
-
return "Expression";
}
-String VisualScriptExpression::get_text() const {
+String VisualScriptExpression::get_text() const {
return expression;
}
Error VisualScriptExpression::_get_token(Token &r_token) {
-
while (true) {
#define GET_CHAR() (str_ofs >= expression.length() ? 0 : expression[str_ofs++])
- CharType cchar = GET_CHAR();
+ char32_t cchar = GET_CHAR();
if (cchar == 0) {
r_token.type = TK_EOF;
return OK;
}
switch (cchar) {
-
case 0: {
r_token.type = TK_EOF;
return OK;
} break;
case '{': {
-
r_token.type = TK_CURLY_BRACKET_OPEN;
return OK;
};
case '}': {
-
r_token.type = TK_CURLY_BRACKET_CLOSE;
return OK;
};
case '[': {
-
r_token.type = TK_BRACKET_OPEN;
return OK;
};
case ']': {
-
r_token.type = TK_BRACKET_CLOSE;
return OK;
};
case '(': {
-
r_token.type = TK_PARENTHESIS_OPEN;
return OK;
};
case ')': {
-
r_token.type = TK_PARENTHESIS_CLOSE;
return OK;
};
case ',': {
-
r_token.type = TK_COMMA;
return OK;
};
case ':': {
-
r_token.type = TK_COLON;
return OK;
};
case '.': {
-
r_token.type = TK_PERIOD;
return OK;
};
case '=': {
-
cchar = GET_CHAR();
if (cchar == '=') {
r_token.type = TK_OP_EQUAL;
@@ -273,7 +246,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '!': {
-
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_NOT_EQUAL;
str_ofs++;
@@ -283,7 +255,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '>': {
-
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_GREATER_EQUAL;
str_ofs++;
@@ -296,7 +267,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '<': {
-
if (expression[str_ofs] == '=') {
r_token.type = TK_OP_LESS_EQUAL;
str_ofs++;
@@ -329,7 +299,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '&': {
-
if (expression[str_ofs] == '&') {
r_token.type = TK_OP_AND;
str_ofs++;
@@ -339,7 +308,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '|': {
-
if (expression[str_ofs] == '|') {
r_token.type = TK_OP_OR;
str_ofs++;
@@ -349,23 +317,19 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return OK;
};
case '^': {
-
r_token.type = TK_OP_BIT_XOR;
return OK;
};
case '~': {
-
r_token.type = TK_OP_BIT_INVERT;
return OK;
};
case '"': {
-
String str;
while (true) {
-
- CharType ch = GET_CHAR();
+ char32_t ch = GET_CHAR();
if (ch == 0) {
_set_error("Unterminated String");
@@ -376,25 +340,34 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} else if (ch == '\\') {
//escaped characters...
- CharType next = GET_CHAR();
+ char32_t next = GET_CHAR();
if (next == 0) {
_set_error("Unterminated String");
r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
- CharType res = 0;
+ char32_t res = 0;
switch (next) {
-
- case 'b': res = 8; break;
- case 't': res = 9; break;
- case 'n': res = 10; break;
- case 'f': res = 12; break;
- case 'r': res = 13; break;
+ case 'b':
+ res = 8;
+ break;
+ case 't':
+ res = 9;
+ break;
+ case 'n':
+ res = 10;
+ break;
+ case 'f':
+ res = 12;
+ break;
+ case 'r':
+ res = 13;
+ break;
case 'u': {
// hex number
for (int j = 0; j < 4; j++) {
- CharType c = GET_CHAR();
+ char32_t c = GET_CHAR();
if (c == 0) {
_set_error("Unterminated String");
@@ -402,12 +375,11 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
return ERR_PARSE_ERROR;
}
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
-
_set_error("Malformed hex constant in string");
r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
- CharType v;
+ char32_t v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'a' && c <= 'f') {
@@ -444,7 +416,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} break;
default: {
-
if (cchar <= 32) {
break;
}
@@ -460,16 +431,14 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
#define READING_DONE 4
int reading = READING_INT;
- CharType c = cchar;
+ char32_t c = cchar;
bool exp_sign = false;
bool exp_beg = false;
bool is_float = false;
while (true) {
-
switch (reading) {
case READING_INT: {
-
if (c >= '0' && c <= '9') {
//pass
} else if (c == '.') {
@@ -483,9 +452,7 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} break;
case READING_DEC: {
-
if (c >= '0' && c <= '9') {
-
} else if (c == 'e') {
reading = READING_EXP;
@@ -495,13 +462,13 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} break;
case READING_EXP: {
-
if (c >= '0' && c <= '9') {
exp_beg = true;
} else if ((c == '-' || c == '+') && !exp_sign && !exp_beg) {
- if (c == '-')
+ if (c == '-') {
is_float = true;
+ }
exp_sign = true;
} else {
@@ -510,8 +477,9 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} break;
}
- if (reading == READING_DONE)
+ if (reading == READING_DONE) {
break;
+ }
num += String::chr(c);
c = GET_CHAR();
}
@@ -520,19 +488,18 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
r_token.type = TK_CONSTANT;
- if (is_float)
- r_token.value = num.to_double();
- else
+ if (is_float) {
+ r_token.value = num.to_float();
+ } else {
r_token.value = num.to_int();
+ }
return OK;
} else if ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_') {
-
String id;
bool first = true;
while ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_' || (!first && cchar >= '0' && cchar <= '9')) {
-
id += String::chr(cchar);
cchar = GET_CHAR();
first = false;
@@ -572,7 +539,6 @@ Error VisualScriptExpression::_get_token(Token &r_token) {
} else if (id == "self") {
r_token.type = TK_SELF;
} else {
-
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
if (id == Variant::get_type_name(Variant::Type(i))) {
r_token.type = TK_BASIC_TYPE;
@@ -647,7 +613,6 @@ const char *VisualScriptExpression::token_name[TK_MAX] = {
};
VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
-
Vector<Expression> expression;
while (true) {
@@ -656,8 +621,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
Token tk;
_get_token(tk);
- if (error_set)
+ if (error_set) {
return nullptr;
+ }
switch (tk.type) {
case TK_CURLY_BRACKET_OPEN: {
@@ -665,7 +631,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
DictionaryNode *dn = alloc_node<DictionaryNode>();
while (true) {
-
int cofs = str_ofs;
_get_token(tk);
if (tk.type == TK_CURLY_BRACKET_CLOSE) {
@@ -674,8 +639,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
str_ofs = cofs; //revert
//parse an expression
ENode *expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
dn->dict.push_back(expr2);
_get_token(tk);
@@ -685,8 +651,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
}
expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
dn->dict.push_back(expr2);
@@ -709,7 +676,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
ArrayNode *an = alloc_node<ArrayNode>();
while (true) {
-
int cofs = str_ofs;
_get_token(tk);
if (tk.type == TK_BRACKET_CLOSE) {
@@ -718,8 +684,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
str_ofs = cofs; //revert
//parse an expression
ENode *expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
an->array.push_back(expr2);
cofs = str_ofs;
@@ -738,8 +705,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
case TK_PARENTHESIS_OPEN: {
//a suexpression
ENode *e = _parse_expression();
- if (error_set)
+ if (error_set) {
return nullptr;
+ }
_get_token(tk);
if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')'");
@@ -750,7 +718,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
} break;
case TK_IDENTIFIER: {
-
String what = tk.value;
int index = -1;
for (int i = 0; i < inputs.size(); i++) {
@@ -770,7 +737,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
}
} break;
case TK_SELF: {
-
SelfNode *self = alloc_node<SelfNode>();
expr = self;
} break;
@@ -793,7 +759,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
constructor->data_type = bt;
while (true) {
-
int cofs = str_ofs;
_get_token(tk);
if (tk.type == TK_PARENTHESIS_CLOSE) {
@@ -802,8 +767,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
str_ofs = cofs; //revert
//parse an expression
ENode *expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
constructor->arguments.push_back(expr2);
@@ -834,7 +800,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
bifunc->func = VisualScriptBuiltinFunc::BuiltinFunc(int(tk.value));
while (true) {
-
int cofs = str_ofs;
_get_token(tk);
if (tk.type == TK_PARENTHESIS_CLOSE) {
@@ -843,8 +808,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
str_ofs = cofs; //revert
//parse an expression
ENode *expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
bifunc->arguments.push_back(expr2);
@@ -868,7 +834,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
} break;
case TK_OP_SUB: {
-
Expression e;
e.is_op = true;
e.op = Variant::OP_NEGATE;
@@ -876,7 +841,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
continue;
} break;
case TK_OP_NOT: {
-
Expression e;
e.is_op = true;
e.op = Variant::OP_NOT;
@@ -895,8 +859,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
while (true) {
int cofs2 = str_ofs;
_get_token(tk);
- if (error_set)
+ if (error_set) {
return nullptr;
+ }
bool done = false;
@@ -908,8 +873,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
index->base = expr;
ENode *what = _parse_expression();
- if (!what)
+ if (!what) {
return nullptr;
+ }
index->index = what;
@@ -940,7 +906,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
func_call->base = expr;
while (true) {
-
int cofs3 = str_ofs;
_get_token(tk);
if (tk.type == TK_PARENTHESIS_CLOSE) {
@@ -949,8 +914,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
str_ofs = cofs3; //revert
//parse an expression
ENode *expr2 = _parse_expression();
- if (!expr2)
+ if (!expr2) {
return nullptr;
+ }
func_call->arguments.push_back(expr2);
@@ -983,8 +949,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
} break;
}
- if (done)
+ if (done) {
break;
+ }
}
//push expression
@@ -999,33 +966,76 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
int cofs = str_ofs;
_get_token(tk);
- if (error_set)
+ if (error_set) {
return nullptr;
+ }
Variant::Operator op = Variant::OP_MAX;
switch (tk.type) {
- case TK_OP_IN: op = Variant::OP_IN; break;
- case TK_OP_EQUAL: op = Variant::OP_EQUAL; break;
- case TK_OP_NOT_EQUAL: op = Variant::OP_NOT_EQUAL; break;
- case TK_OP_LESS: op = Variant::OP_LESS; break;
- case TK_OP_LESS_EQUAL: op = Variant::OP_LESS_EQUAL; break;
- case TK_OP_GREATER: op = Variant::OP_GREATER; break;
- case TK_OP_GREATER_EQUAL: op = Variant::OP_GREATER_EQUAL; break;
- case TK_OP_AND: op = Variant::OP_AND; break;
- case TK_OP_OR: op = Variant::OP_OR; break;
- case TK_OP_NOT: op = Variant::OP_NOT; break;
- case TK_OP_ADD: op = Variant::OP_ADD; break;
- case TK_OP_SUB: op = Variant::OP_SUBTRACT; break;
- case TK_OP_MUL: op = Variant::OP_MULTIPLY; break;
- case TK_OP_DIV: op = Variant::OP_DIVIDE; break;
- case TK_OP_MOD: op = Variant::OP_MODULE; break;
- case TK_OP_SHIFT_LEFT: op = Variant::OP_SHIFT_LEFT; break;
- case TK_OP_SHIFT_RIGHT: op = Variant::OP_SHIFT_RIGHT; break;
- case TK_OP_BIT_AND: op = Variant::OP_BIT_AND; break;
- case TK_OP_BIT_OR: op = Variant::OP_BIT_OR; break;
- case TK_OP_BIT_XOR: op = Variant::OP_BIT_XOR; break;
- case TK_OP_BIT_INVERT: op = Variant::OP_BIT_NEGATE; break;
+ case TK_OP_IN:
+ op = Variant::OP_IN;
+ break;
+ case TK_OP_EQUAL:
+ op = Variant::OP_EQUAL;
+ break;
+ case TK_OP_NOT_EQUAL:
+ op = Variant::OP_NOT_EQUAL;
+ break;
+ case TK_OP_LESS:
+ op = Variant::OP_LESS;
+ break;
+ case TK_OP_LESS_EQUAL:
+ op = Variant::OP_LESS_EQUAL;
+ break;
+ case TK_OP_GREATER:
+ op = Variant::OP_GREATER;
+ break;
+ case TK_OP_GREATER_EQUAL:
+ op = Variant::OP_GREATER_EQUAL;
+ break;
+ case TK_OP_AND:
+ op = Variant::OP_AND;
+ break;
+ case TK_OP_OR:
+ op = Variant::OP_OR;
+ break;
+ case TK_OP_NOT:
+ op = Variant::OP_NOT;
+ break;
+ case TK_OP_ADD:
+ op = Variant::OP_ADD;
+ break;
+ case TK_OP_SUB:
+ op = Variant::OP_SUBTRACT;
+ break;
+ case TK_OP_MUL:
+ op = Variant::OP_MULTIPLY;
+ break;
+ case TK_OP_DIV:
+ op = Variant::OP_DIVIDE;
+ break;
+ case TK_OP_MOD:
+ op = Variant::OP_MODULE;
+ break;
+ case TK_OP_SHIFT_LEFT:
+ op = Variant::OP_SHIFT_LEFT;
+ break;
+ case TK_OP_SHIFT_RIGHT:
+ op = Variant::OP_SHIFT_RIGHT;
+ break;
+ case TK_OP_BIT_AND:
+ op = Variant::OP_BIT_AND;
+ break;
+ case TK_OP_BIT_OR:
+ op = Variant::OP_BIT_OR;
+ break;
+ case TK_OP_BIT_XOR:
+ op = Variant::OP_BIT_XOR;
+ break;
+ case TK_OP_BIT_INVERT:
+ op = Variant::OP_BIT_NEGATE;
+ break;
default: {
};
}
@@ -1047,15 +1057,12 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
/* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
while (expression.size() > 1) {
-
int next_op = -1;
int min_priority = 0xFFFFF;
bool is_unary = false;
for (int i = 0; i < expression.size(); i++) {
-
if (!expression[i].is_op) {
-
continue;
}
@@ -1064,7 +1071,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
bool unary = false;
switch (expression[i].op) {
-
case Variant::OP_BIT_NEGATE:
priority = 0;
unary = true;
@@ -1074,36 +1080,74 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
unary = true;
break;
- case Variant::OP_MULTIPLY: priority = 2; break;
- case Variant::OP_DIVIDE: priority = 2; break;
- case Variant::OP_MODULE: priority = 2; break;
+ case Variant::OP_MULTIPLY:
+ priority = 2;
+ break;
+ case Variant::OP_DIVIDE:
+ priority = 2;
+ break;
+ case Variant::OP_MODULE:
+ priority = 2;
+ break;
- case Variant::OP_ADD: priority = 3; break;
- case Variant::OP_SUBTRACT: priority = 3; break;
+ case Variant::OP_ADD:
+ priority = 3;
+ break;
+ case Variant::OP_SUBTRACT:
+ priority = 3;
+ break;
- case Variant::OP_SHIFT_LEFT: priority = 4; break;
- case Variant::OP_SHIFT_RIGHT: priority = 4; break;
+ case Variant::OP_SHIFT_LEFT:
+ priority = 4;
+ break;
+ case Variant::OP_SHIFT_RIGHT:
+ priority = 4;
+ break;
- case Variant::OP_BIT_AND: priority = 5; break;
- case Variant::OP_BIT_XOR: priority = 6; break;
- case Variant::OP_BIT_OR: priority = 7; break;
+ case Variant::OP_BIT_AND:
+ priority = 5;
+ break;
+ case Variant::OP_BIT_XOR:
+ priority = 6;
+ break;
+ case Variant::OP_BIT_OR:
+ priority = 7;
+ break;
- case Variant::OP_LESS: priority = 8; break;
- case Variant::OP_LESS_EQUAL: priority = 8; break;
- case Variant::OP_GREATER: priority = 8; break;
- case Variant::OP_GREATER_EQUAL: priority = 8; break;
+ case Variant::OP_LESS:
+ priority = 8;
+ break;
+ case Variant::OP_LESS_EQUAL:
+ priority = 8;
+ break;
+ case Variant::OP_GREATER:
+ priority = 8;
+ break;
+ case Variant::OP_GREATER_EQUAL:
+ priority = 8;
+ break;
- case Variant::OP_EQUAL: priority = 8; break;
- case Variant::OP_NOT_EQUAL: priority = 8; break;
+ case Variant::OP_EQUAL:
+ priority = 8;
+ break;
+ case Variant::OP_NOT_EQUAL:
+ priority = 8;
+ break;
- case Variant::OP_IN: priority = 10; break;
+ case Variant::OP_IN:
+ priority = 10;
+ break;
case Variant::OP_NOT:
priority = 11;
unary = true;
break;
- case Variant::OP_AND: priority = 12; break;
- case Variant::OP_OR: priority = 13; break;
+ case Variant::OP_AND:
+ priority = 12;
+ break;
+ case Variant::OP_OR:
+ priority = 13;
+ break;
default: {
_set_error("Parser bug, invalid operator in expression: " + itos(expression[i].op));
@@ -1122,17 +1166,14 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
}
if (next_op == -1) {
-
_set_error("Yet another parser bug....");
ERR_FAIL_V(nullptr);
}
// OK! create operator..
if (is_unary) {
-
int expr_pos = next_op;
while (expression[expr_pos].is_op) {
-
expr_pos++;
if (expr_pos == expression.size()) {
//can happen..
@@ -1143,7 +1184,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
//consecutively do unary operators
for (int i = expr_pos - 1; i >= next_op; i--) {
-
OperatorNode *op = alloc_node<OperatorNode>();
op->op = expression[i].op;
op->nodes[0] = expression[i + 1].node;
@@ -1154,7 +1194,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
}
} else {
-
if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug...");
ERR_FAIL_V(nullptr);
@@ -1164,7 +1203,6 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
op->op = expression[next_op].op;
if (expression[next_op - 1].is_op) {
-
_set_error("Parser bug...");
ERR_FAIL_V(nullptr);
}
@@ -1193,9 +1231,9 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
}
bool VisualScriptExpression::_compile_expression() {
-
- if (!expression_dirty)
+ if (!expression_dirty) {
return error_set;
+ }
if (nodes) {
memdelete(nodes);
@@ -1230,38 +1268,35 @@ public:
//virtual int get_working_memory_size() const { return 0; }
//execute by parsing the tree directly
virtual bool _execute(const Variant **p_inputs, VisualScriptExpression::ENode *p_node, Variant &r_ret, String &r_error_str, Callable::CallError &ce) {
-
switch (p_node->type) {
case VisualScriptExpression::ENode::TYPE_INPUT: {
-
const VisualScriptExpression::InputNode *in = static_cast<const VisualScriptExpression::InputNode *>(p_node);
r_ret = *p_inputs[in->index];
} break;
case VisualScriptExpression::ENode::TYPE_CONSTANT: {
-
const VisualScriptExpression::ConstantNode *c = static_cast<const VisualScriptExpression::ConstantNode *>(p_node);
r_ret = c->value;
} break;
case VisualScriptExpression::ENode::TYPE_SELF: {
-
r_ret = instance->get_owner_ptr();
} break;
case VisualScriptExpression::ENode::TYPE_OPERATOR: {
-
const VisualScriptExpression::OperatorNode *op = static_cast<const VisualScriptExpression::OperatorNode *>(p_node);
Variant a;
bool ret = _execute(p_inputs, op->nodes[0], a, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
Variant b;
if (op->nodes[1]) {
ret = _execute(p_inputs, op->nodes[1], b, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
}
bool valid = true;
@@ -1273,19 +1308,20 @@ public:
} break;
case VisualScriptExpression::ENode::TYPE_INDEX: {
-
const VisualScriptExpression::IndexNode *index = static_cast<const VisualScriptExpression::IndexNode *>(p_node);
Variant base;
bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
Variant idx;
ret = _execute(p_inputs, index->index, idx, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
bool valid;
r_ret = base.get(idx, &valid);
@@ -1296,16 +1332,16 @@ public:
} break;
case VisualScriptExpression::ENode::TYPE_NAMED_INDEX: {
-
const VisualScriptExpression::NamedIndexNode *index = static_cast<const VisualScriptExpression::NamedIndexNode *>(p_node);
Variant base;
bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
bool valid;
- r_ret = base.get_named(index->name, &valid);
+ r_ret = base.get_named(index->name, valid);
if (!valid) {
r_error_str = "Invalid index '" + String(index->name) + "' for base of type " + Variant::get_type_name(base.get_type()) + ".";
return true;
@@ -1318,11 +1354,11 @@ public:
Array arr;
arr.resize(array->array.size());
for (int i = 0; i < array->array.size(); i++) {
-
Variant value;
bool ret = _execute(p_inputs, array->array[i], value, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
arr[i] = value;
}
@@ -1334,16 +1370,17 @@ public:
Dictionary d;
for (int i = 0; i < dictionary->dict.size(); i += 2) {
-
Variant key;
bool ret = _execute(p_inputs, dictionary->dict[i + 0], key, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
Variant value;
ret = _execute(p_inputs, dictionary->dict[i + 1], value, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
d[key] = value;
}
@@ -1351,7 +1388,6 @@ public:
r_ret = d;
} break;
case VisualScriptExpression::ENode::TYPE_CONSTRUCTOR: {
-
const VisualScriptExpression::ConstructorNode *constructor = static_cast<const VisualScriptExpression::ConstructorNode *>(p_node);
Vector<Variant> arr;
@@ -1360,16 +1396,16 @@ public:
argp.resize(constructor->arguments.size());
for (int i = 0; i < constructor->arguments.size(); i++) {
-
Variant value;
bool ret = _execute(p_inputs, constructor->arguments[i], value, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
arr.write[i] = value;
argp.write[i] = &arr[i];
}
- r_ret = Variant::construct(constructor->data_type, (const Variant **)argp.ptr(), argp.size(), ce);
+ Variant::construct(constructor->data_type, r_ret, (const Variant **)argp.ptr(), argp.size(), ce);
if (ce.error != Callable::CallError::CALL_OK) {
r_error_str = "Invalid arguments to construct '" + Variant::get_type_name(constructor->data_type) + "'.";
@@ -1378,7 +1414,6 @@ public:
} break;
case VisualScriptExpression::ENode::TYPE_BUILTIN_FUNC: {
-
const VisualScriptExpression::BuiltinFuncNode *bifunc = static_cast<const VisualScriptExpression::BuiltinFuncNode *>(p_node);
Vector<Variant> arr;
@@ -1387,11 +1422,11 @@ public:
argp.resize(bifunc->arguments.size());
for (int i = 0; i < bifunc->arguments.size(); i++) {
-
Variant value;
bool ret = _execute(p_inputs, bifunc->arguments[i], value, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
arr.write[i] = value;
argp.write[i] = &arr[i];
}
@@ -1405,13 +1440,13 @@ public:
} break;
case VisualScriptExpression::ENode::TYPE_CALL: {
-
const VisualScriptExpression::CallNode *call = static_cast<const VisualScriptExpression::CallNode *>(p_node);
Variant base;
bool ret = _execute(p_inputs, call->base, base, r_error_str, ce);
- if (ret)
+ if (ret) {
return true;
+ }
Vector<Variant> arr;
Vector<const Variant *> argp;
@@ -1419,16 +1454,16 @@ public:
argp.resize(call->arguments.size());
for (int i = 0; i < call->arguments.size(); i++) {
-
Variant value;
bool ret2 = _execute(p_inputs, call->arguments[i], value, r_error_str, ce);
- if (ret2)
+ if (ret2) {
return true;
+ }
arr.write[i] = value;
argp.write[i] = &arr[i];
}
- r_ret = base.call(call->method, (const Variant **)argp.ptr(), argp.size(), ce);
+ base.call(call->method, (const Variant **)argp.ptr(), argp.size(), r_ret, ce);
if (ce.error != Callable::CallError::CALL_OK) {
r_error_str = "On call to '" + String(call->method) + "':";
@@ -1441,7 +1476,6 @@ public:
}
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!expression->root || expression->error_set) {
r_error_str = expression->error_str;
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -1455,7 +1489,6 @@ public:
#ifdef DEBUG_ENABLED
if (!error && expression->output_type != Variant::NIL && !Variant::can_convert_strict(p_outputs[0]->get_type(), expression->output_type)) {
-
r_error_str += "Can't convert expression result from " + Variant::get_type_name(p_outputs[0]->get_type()) + " to " + Variant::get_type_name(expression->output_type) + ".";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
}
@@ -1466,7 +1499,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptExpression::instance(VisualScriptInstance *p_instance) {
-
_compile_expression();
VisualScriptNodeInstanceExpression *instance = memnew(VisualScriptNodeInstanceExpression);
instance->instance = p_instance;
@@ -1484,13 +1516,11 @@ VisualScriptExpression::VisualScriptExpression() {
}
VisualScriptExpression::~VisualScriptExpression() {
-
if (nodes) {
memdelete(nodes);
}
}
void register_visual_script_expression_node() {
-
VisualScriptLanguage::singleton->add_register_func("operators/expression", create_node_generic<VisualScriptExpression>);
}
diff --git a/modules/visual_script/visual_script_expression.h b/modules/visual_script/visual_script_expression.h
index 61b50ff99d..7fe665769d 100644
--- a/modules/visual_script/visual_script_expression.h
+++ b/modules/visual_script/visual_script_expression.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
#include "visual_script_builtin_funcs.h"
class VisualScriptExpression : public VisualScriptNode {
-
GDCLASS(VisualScriptExpression, VisualScriptNode);
friend class VisualScriptNodeInstanceExpression;
struct Input {
-
Variant::Type type;
String name;
@@ -101,14 +99,14 @@ class VisualScriptExpression : public VisualScriptNode {
static const char *token_name[TK_MAX];
struct Token {
-
TokenType type;
Variant value;
};
void _set_error(const String &p_err) {
- if (error_set)
+ if (error_set) {
return;
+ }
error_str = p_err;
error_set = true;
}
@@ -119,7 +117,6 @@ class VisualScriptExpression : public VisualScriptNode {
bool error_set;
struct ENode {
-
enum Type {
TYPE_INPUT,
TYPE_CONSTANT,
@@ -147,7 +144,6 @@ class VisualScriptExpression : public VisualScriptNode {
};
struct Expression {
-
bool is_op;
union {
Variant::Operator op;
@@ -158,7 +154,6 @@ class VisualScriptExpression : public VisualScriptNode {
ENode *_parse_expression();
struct InputNode : public ENode {
-
int index;
InputNode() {
type = TYPE_INPUT;
@@ -166,7 +161,6 @@ class VisualScriptExpression : public VisualScriptNode {
};
struct ConstantNode : public ENode {
-
Variant value;
ConstantNode() {
type = TYPE_CONSTANT;
@@ -174,7 +168,6 @@ class VisualScriptExpression : public VisualScriptNode {
};
struct OperatorNode : public ENode {
-
Variant::Operator op;
ENode *nodes[2];
@@ -185,7 +178,6 @@ class VisualScriptExpression : public VisualScriptNode {
};
struct SelfNode : public ENode {
-
SelfNode() {
type = TYPE_SELF;
}
@@ -267,22 +259,22 @@ protected:
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "operators"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "operators"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptExpression();
~VisualScriptExpression();
diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp
index 8a644c6860..0049e254c4 100644
--- a/modules/visual_script/visual_script_flow_control.cpp
+++ b/modules/visual_script/visual_script_flow_control.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,87 +30,79 @@
#include "visual_script_flow_control.h"
+#include "core/config/project_settings.h"
#include "core/io/resource_loader.h"
#include "core/os/keyboard.h"
-#include "core/project_settings.h"
//////////////////////////////////////////
////////////////RETURN////////////////////
//////////////////////////////////////////
int VisualScriptReturn::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptReturn::has_input_sequence_port() const {
-
return true;
}
int VisualScriptReturn::get_input_value_port_count() const {
-
return with_value ? 1 : 0;
}
-int VisualScriptReturn::get_output_value_port_count() const {
+int VisualScriptReturn::get_output_value_port_count() const {
return 0;
}
String VisualScriptReturn::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptReturn::get_input_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "result";
pinfo.type = type;
return pinfo;
}
+
PropertyInfo VisualScriptReturn::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
String VisualScriptReturn::get_caption() const {
-
return "Return";
}
String VisualScriptReturn::get_text() const {
-
return get_name();
}
void VisualScriptReturn::set_return_type(Variant::Type p_type) {
-
- if (type == p_type)
+ if (type == p_type) {
return;
+ }
type = p_type;
ports_changed_notify();
}
Variant::Type VisualScriptReturn::get_return_type() const {
-
return type;
}
void VisualScriptReturn::set_enable_return_value(bool p_enable) {
- if (with_value == p_enable)
+ if (with_value == p_enable) {
return;
+ }
with_value = p_enable;
ports_changed_notify();
}
bool VisualScriptReturn::is_return_value_enabled() const {
-
return with_value;
}
void VisualScriptReturn::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_return_type", "type"), &VisualScriptReturn::set_return_type);
ClassDB::bind_method(D_METHOD("get_return_type"), &VisualScriptReturn::get_return_type);
ClassDB::bind_method(D_METHOD("set_enable_return_value", "enable"), &VisualScriptReturn::set_enable_return_value);
@@ -136,7 +128,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (with_value) {
*p_working_mem = *p_inputs[0];
return STEP_EXIT_FUNCTION_BIT;
@@ -148,7 +139,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptReturn::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceReturn *instance = memnew(VisualScriptNodeInstanceReturn);
instance->node = this;
instance->instance = p_instance;
@@ -157,14 +147,12 @@ VisualScriptNodeInstance *VisualScriptReturn::instance(VisualScriptInstance *p_i
}
VisualScriptReturn::VisualScriptReturn() {
-
with_value = false;
type = Variant::NIL;
}
template <bool with_value>
static Ref<VisualScriptNode> create_return_node(const String &p_name) {
-
Ref<VisualScriptReturn> node;
node.instance();
node->set_enable_return_value(with_value);
@@ -176,52 +164,47 @@ static Ref<VisualScriptNode> create_return_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptCondition::get_output_sequence_port_count() const {
-
return 3;
}
bool VisualScriptCondition::has_input_sequence_port() const {
-
return true;
}
int VisualScriptCondition::get_input_value_port_count() const {
-
return 1;
}
-int VisualScriptCondition::get_output_value_port_count() const {
+int VisualScriptCondition::get_output_value_port_count() const {
return 0;
}
String VisualScriptCondition::get_output_sequence_port_text(int p_port) const {
-
- if (p_port == 0)
+ if (p_port == 0) {
return "true";
- else if (p_port == 1)
+ } else if (p_port == 1) {
return "false";
- else
+ } else {
return "done";
+ }
}
PropertyInfo VisualScriptCondition::get_input_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "cond";
pinfo.type = Variant::BOOL;
return pinfo;
}
+
PropertyInfo VisualScriptCondition::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
String VisualScriptCondition::get_caption() const {
-
return "Condition";
}
String VisualScriptCondition::get_text() const {
-
return "if (cond) is: ";
}
@@ -238,18 +221,17 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
- if (p_start_mode == START_MODE_CONTINUE_SEQUENCE)
+ if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) {
return 2;
- else if (p_inputs[0]->operator bool())
+ } else if (p_inputs[0]->operator bool()) {
return 0 | STEP_FLAG_PUSH_STACK_BIT;
- else
+ } else {
return 1 | STEP_FLAG_PUSH_STACK_BIT;
+ }
}
};
VisualScriptNodeInstance *VisualScriptCondition::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceCondition *instance = memnew(VisualScriptNodeInstanceCondition);
instance->node = this;
instance->instance = p_instance;
@@ -264,50 +246,45 @@ VisualScriptCondition::VisualScriptCondition() {
//////////////////////////////////////////
int VisualScriptWhile::get_output_sequence_port_count() const {
-
return 2;
}
bool VisualScriptWhile::has_input_sequence_port() const {
-
return true;
}
int VisualScriptWhile::get_input_value_port_count() const {
-
return 1;
}
-int VisualScriptWhile::get_output_value_port_count() const {
+int VisualScriptWhile::get_output_value_port_count() const {
return 0;
}
String VisualScriptWhile::get_output_sequence_port_text(int p_port) const {
-
- if (p_port == 0)
+ if (p_port == 0) {
return "repeat";
- else
+ } else {
return "exit";
+ }
}
PropertyInfo VisualScriptWhile::get_input_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "cond";
pinfo.type = Variant::BOOL;
return pinfo;
}
+
PropertyInfo VisualScriptWhile::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
String VisualScriptWhile::get_caption() const {
-
return "While";
}
String VisualScriptWhile::get_text() const {
-
return "while (cond): ";
}
@@ -324,23 +301,23 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
bool keep_going = p_inputs[0]->operator bool();
- if (keep_going)
+ if (keep_going) {
return 0 | STEP_FLAG_PUSH_STACK_BIT;
- else
+ } else {
return 1;
+ }
}
};
VisualScriptNodeInstance *VisualScriptWhile::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceWhile *instance = memnew(VisualScriptNodeInstanceWhile);
instance->node = this;
instance->instance = p_instance;
return instance;
}
+
VisualScriptWhile::VisualScriptWhile() {
}
@@ -349,52 +326,48 @@ VisualScriptWhile::VisualScriptWhile() {
//////////////////////////////////////////
int VisualScriptIterator::get_output_sequence_port_count() const {
-
return 2;
}
bool VisualScriptIterator::has_input_sequence_port() const {
-
return true;
}
int VisualScriptIterator::get_input_value_port_count() const {
-
return 1;
}
-int VisualScriptIterator::get_output_value_port_count() const {
+int VisualScriptIterator::get_output_value_port_count() const {
return 1;
}
String VisualScriptIterator::get_output_sequence_port_text(int p_port) const {
-
- if (p_port == 0)
+ if (p_port == 0) {
return "each";
- else
+ } else {
return "exit";
+ }
}
PropertyInfo VisualScriptIterator::get_input_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "input";
pinfo.type = Variant::NIL;
return pinfo;
}
+
PropertyInfo VisualScriptIterator::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = "elem";
pinfo.type = Variant::NIL;
return pinfo;
}
-String VisualScriptIterator::get_caption() const {
+String VisualScriptIterator::get_caption() const {
return "Iterator";
}
String VisualScriptIterator::get_text() const {
-
return "for (elem) in (input): ";
}
@@ -411,7 +384,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
p_working_mem[0] = *p_inputs[0];
bool valid;
@@ -423,8 +395,9 @@ public:
return 0;
}
- if (!can_iter)
+ if (!can_iter) {
return 1; //nothing to iterate
+ }
*p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
@@ -445,8 +418,9 @@ public:
return 0;
}
- if (!can_iter)
+ if (!can_iter) {
return 1; //nothing to iterate
+ }
*p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
@@ -462,7 +436,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptIterator::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceIterator *instance = memnew(VisualScriptNodeInstanceIterator);
instance->node = this;
instance->instance = p_instance;
@@ -477,62 +450,56 @@ VisualScriptIterator::VisualScriptIterator() {
//////////////////////////////////////////
int VisualScriptSequence::get_output_sequence_port_count() const {
-
return steps;
}
bool VisualScriptSequence::has_input_sequence_port() const {
-
return true;
}
int VisualScriptSequence::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptSequence::get_output_value_port_count() const {
+int VisualScriptSequence::get_output_value_port_count() const {
return 1;
}
String VisualScriptSequence::get_output_sequence_port_text(int p_port) const {
-
return itos(p_port + 1);
}
PropertyInfo VisualScriptSequence::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
+
PropertyInfo VisualScriptSequence::get_output_value_port_info(int p_idx) const {
return PropertyInfo(Variant::INT, "current");
}
-String VisualScriptSequence::get_caption() const {
+String VisualScriptSequence::get_caption() const {
return "Sequence";
}
String VisualScriptSequence::get_text() const {
-
return "in order: ";
}
void VisualScriptSequence::set_steps(int p_steps) {
-
ERR_FAIL_COND(p_steps < 1);
- if (steps == p_steps)
+ if (steps == p_steps) {
return;
+ }
steps = p_steps;
ports_changed_notify();
}
int VisualScriptSequence::get_steps() const {
-
return steps;
}
void VisualScriptSequence::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_steps", "steps"), &VisualScriptSequence::set_steps);
ClassDB::bind_method(D_METHOD("get_steps"), &VisualScriptSequence::get_steps);
@@ -550,9 +517,7 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
-
p_working_mem[0] = 0;
}
@@ -560,9 +525,9 @@ public:
*p_outputs[0] = step;
- if (step + 1 == steps)
+ if (step + 1 == steps) {
return step;
- else {
+ } else {
p_working_mem[0] = step + 1;
return step | STEP_FLAG_PUSH_STACK_BIT;
}
@@ -570,15 +535,14 @@ public:
};
VisualScriptNodeInstance *VisualScriptSequence::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSequence *instance = memnew(VisualScriptNodeInstanceSequence);
instance->node = this;
instance->instance = p_instance;
instance->steps = steps;
return instance;
}
-VisualScriptSequence::VisualScriptSequence() {
+VisualScriptSequence::VisualScriptSequence() {
steps = 1;
}
@@ -587,52 +551,46 @@ VisualScriptSequence::VisualScriptSequence() {
//////////////////////////////////////////
int VisualScriptSwitch::get_output_sequence_port_count() const {
-
return case_values.size() + 1;
}
bool VisualScriptSwitch::has_input_sequence_port() const {
-
return true;
}
int VisualScriptSwitch::get_input_value_port_count() const {
-
return case_values.size() + 1;
}
-int VisualScriptSwitch::get_output_value_port_count() const {
+int VisualScriptSwitch::get_output_value_port_count() const {
return 0;
}
String VisualScriptSwitch::get_output_sequence_port_text(int p_port) const {
-
- if (p_port == case_values.size())
+ if (p_port == case_values.size()) {
return "done";
+ }
return String();
}
PropertyInfo VisualScriptSwitch::get_input_value_port_info(int p_idx) const {
-
if (p_idx < case_values.size()) {
return PropertyInfo(case_values[p_idx].type, " =");
- } else
+ } else {
return PropertyInfo(Variant::NIL, "input");
+ }
}
PropertyInfo VisualScriptSwitch::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptSwitch::get_caption() const {
-
return "Switch";
}
String VisualScriptSwitch::get_text() const {
-
return "'input' is:";
}
@@ -646,13 +604,11 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) {
return case_count; //exit
}
for (int i = 0; i < case_count; i++) {
-
if (*p_inputs[i] == *p_inputs[case_count]) {
return i | STEP_FLAG_PUSH_STACK_BIT;
}
@@ -663,7 +619,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptSwitch::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSwitch *instance = memnew(VisualScriptNodeInstanceSwitch);
instance->instance = p_instance;
instance->case_count = case_values.size();
@@ -671,7 +626,6 @@ VisualScriptNodeInstance *VisualScriptSwitch::instance(VisualScriptInstance *p_i
}
bool VisualScriptSwitch::_set(const StringName &p_name, const Variant &p_value) {
-
if (String(p_name) == "case_count") {
case_values.resize(p_value);
_change_notify();
@@ -680,7 +634,6 @@ bool VisualScriptSwitch::_set(const StringName &p_name, const Variant &p_value)
}
if (String(p_name).begins_with("case/")) {
-
int idx = String(p_name).get_slice("/", 1).to_int();
ERR_FAIL_INDEX_V(idx, case_values.size(), false);
@@ -695,14 +648,12 @@ bool VisualScriptSwitch::_set(const StringName &p_name, const Variant &p_value)
}
bool VisualScriptSwitch::_get(const StringName &p_name, Variant &r_ret) const {
-
if (String(p_name) == "case_count") {
r_ret = case_values.size();
return true;
}
if (String(p_name).begins_with("case/")) {
-
int idx = String(p_name).get_slice("/", 1).to_int();
ERR_FAIL_INDEX_V(idx, case_values.size(), false);
@@ -712,8 +663,8 @@ bool VisualScriptSwitch::_get(const StringName &p_name, Variant &r_ret) const {
return false;
}
-void VisualScriptSwitch::_get_property_list(List<PropertyInfo> *p_list) const {
+void VisualScriptSwitch::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::INT, "case_count", PROPERTY_HINT_RANGE, "0,128"));
String argt = "Any";
@@ -737,56 +688,49 @@ VisualScriptSwitch::VisualScriptSwitch() {
//////////////////////////////////////////
int VisualScriptTypeCast::get_output_sequence_port_count() const {
-
return 2;
}
bool VisualScriptTypeCast::has_input_sequence_port() const {
-
return true;
}
int VisualScriptTypeCast::get_input_value_port_count() const {
-
return 1;
}
-int VisualScriptTypeCast::get_output_value_port_count() const {
+int VisualScriptTypeCast::get_output_value_port_count() const {
return 1;
}
String VisualScriptTypeCast::get_output_sequence_port_text(int p_port) const {
-
return p_port == 0 ? "yes" : "no";
}
PropertyInfo VisualScriptTypeCast::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::OBJECT, "instance");
}
PropertyInfo VisualScriptTypeCast::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_TYPE_STRING, get_base_type());
}
String VisualScriptTypeCast::get_caption() const {
-
return "Type Cast";
}
String VisualScriptTypeCast::get_text() const {
-
- if (script != String())
+ if (script != String()) {
return "Is " + script.get_file() + "?";
- else
+ } else {
return "Is " + base_type + "?";
+ }
}
void VisualScriptTypeCast::set_base_type(const StringName &p_type) {
-
- if (base_type == p_type)
+ if (base_type == p_type) {
return;
+ }
base_type = p_type;
_change_notify();
@@ -794,26 +738,24 @@ void VisualScriptTypeCast::set_base_type(const StringName &p_type) {
}
StringName VisualScriptTypeCast::get_base_type() const {
-
return base_type;
}
void VisualScriptTypeCast::set_base_script(const String &p_path) {
-
- if (script == p_path)
+ if (script == p_path) {
return;
+ }
script = p_path;
_change_notify();
ports_changed_notify();
}
-String VisualScriptTypeCast::get_base_script() const {
+String VisualScriptTypeCast::get_base_script() const {
return script;
}
VisualScriptTypeCast::TypeGuess VisualScriptTypeCast::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
TypeGuess tg;
tg.type = Variant::OBJECT;
if (script != String()) {
@@ -837,7 +779,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Object *obj = *p_inputs[0];
*p_outputs[0] = Variant();
@@ -849,7 +790,6 @@ public:
}
if (script != String()) {
-
Ref<Script> obj_script = obj->get_script();
if (!obj_script.is_valid()) {
return 1; //well, definitely not the script because object we got has no script.
@@ -867,7 +807,6 @@ public:
}
while (obj_script.is_valid()) {
-
if (cast_script == obj_script) {
*p_outputs[0] = *p_inputs[0]; //copy
return 0; // it is the script, yey
@@ -882,13 +821,13 @@ public:
if (ClassDB::is_parent_class(obj->get_class_name(), base_type)) {
*p_outputs[0] = *p_inputs[0]; //copy
return 0;
- } else
+ } else {
return 1;
+ }
}
};
VisualScriptNodeInstance *VisualScriptTypeCast::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceTypeCast *instance = memnew(VisualScriptNodeInstanceTypeCast);
instance->instance = p_instance;
instance->base_type = base_type;
@@ -897,7 +836,6 @@ VisualScriptNodeInstance *VisualScriptTypeCast::instance(VisualScriptInstance *p
}
void VisualScriptTypeCast::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_base_type", "type"), &VisualScriptTypeCast::set_base_type);
ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptTypeCast::get_base_type);
@@ -911,8 +849,9 @@ void VisualScriptTypeCast::_bind_methods() {
String script_ext_hint;
for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
- if (script_ext_hint != String())
+ if (script_ext_hint != String()) {
script_ext_hint += ",";
+ }
script_ext_hint += "*." + E->get();
}
@@ -921,12 +860,10 @@ void VisualScriptTypeCast::_bind_methods() {
}
VisualScriptTypeCast::VisualScriptTypeCast() {
-
base_type = "Object";
}
void register_visual_script_flow_control_nodes() {
-
VisualScriptLanguage::singleton->add_register_func("flow_control/return", create_return_node<false>);
VisualScriptLanguage::singleton->add_register_func("flow_control/return_with_value", create_return_node<true>);
VisualScriptLanguage::singleton->add_register_func("flow_control/condition", create_node_generic<VisualScriptCondition>);
diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h
index 8597d051db..46a72bb92d 100644
--- a/modules/visual_script/visual_script_flow_control.h
+++ b/modules/visual_script/visual_script_flow_control.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "visual_script.h"
class VisualScriptReturn : public VisualScriptNode {
-
GDCLASS(VisualScriptReturn, VisualScriptNode);
Variant::Type type;
@@ -44,20 +43,20 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
void set_return_type(Variant::Type);
Variant::Type get_return_type() const;
@@ -65,97 +64,93 @@ public:
void set_enable_return_value(bool p_enable);
bool is_return_value_enabled() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptReturn();
};
class VisualScriptCondition : public VisualScriptNode {
-
GDCLASS(VisualScriptCondition, VisualScriptNode);
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptCondition();
};
class VisualScriptWhile : public VisualScriptNode {
-
GDCLASS(VisualScriptWhile, VisualScriptNode);
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptWhile();
};
class VisualScriptIterator : public VisualScriptNode {
-
GDCLASS(VisualScriptIterator, VisualScriptNode);
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptIterator();
};
class VisualScriptSequence : public VisualScriptNode {
-
GDCLASS(VisualScriptSequence, VisualScriptNode);
int steps;
@@ -164,31 +159,30 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
void set_steps(int p_steps);
int get_steps() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptSequence();
};
class VisualScriptSwitch : public VisualScriptNode {
-
GDCLASS(VisualScriptSwitch, VisualScriptNode);
struct Case {
@@ -208,29 +202,28 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
- virtual bool has_mixed_input_and_sequence_ports() const { return true; }
+ virtual String get_output_sequence_port_text(int p_port) const override;
+ virtual bool has_mixed_input_and_sequence_ports() const override { return true; }
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptSwitch();
};
class VisualScriptTypeCast : public VisualScriptNode {
-
GDCLASS(VisualScriptTypeCast, VisualScriptNode);
StringName base_type;
@@ -240,20 +233,20 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
void set_base_type(const StringName &p_type);
StringName get_base_type() const;
@@ -261,9 +254,9 @@ public:
void set_base_script(const String &p_path);
String get_base_script() const;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptTypeCast();
};
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
index 3b6ae369ae..d016b938de 100644
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ b/modules/visual_script/visual_script_func_nodes.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "visual_script_func_nodes.h"
-#include "core/engine.h"
+#include "core/config/engine.h"
#include "core/io/resource_loader.h"
#include "core/os/os.h"
#include "scene/main/node.h"
@@ -42,33 +42,34 @@
//////////////////////////////////////////
int VisualScriptFunctionCall::get_output_sequence_port_count() 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)))
+ if ((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function))) {
return 0;
- else
+ } else {
return 1;
+ }
}
bool VisualScriptFunctionCall::has_input_sequence_port() const {
-
- 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)));
+ return !((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function)));
}
#ifdef TOOLS_ENABLED
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
-
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene)
+ if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
return nullptr;
+ }
Ref<Script> scr = p_current_node->get_script();
- if (scr.is_valid() && scr == script)
+ if (scr.is_valid() && scr == script) {
return p_current_node;
+ }
for (int i = 0; i < p_current_node->get_child_count(); i++) {
Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n)
+ if (n) {
return n;
+ }
}
return nullptr;
@@ -76,30 +77,34 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const
#endif
Node *VisualScriptFunctionCall::_get_base_node() const {
-
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return nullptr;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return nullptr;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return nullptr;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return nullptr;
+ }
- if (!script_node->has_node(base_path))
+ if (!script_node->has_node(base_path)) {
return nullptr;
+ }
Node *path_to = script_node->get_node(base_path);
@@ -111,26 +116,28 @@ Node *VisualScriptFunctionCall::_get_base_node() const {
}
StringName VisualScriptFunctionCall::_get_base_type() const {
-
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid())
+ if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
return get_visual_script()->get_instance_base_type();
- else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
+ } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
Node *path = _get_base_node();
- if (path)
+ if (path) {
return path->get_class();
+ }
}
return base_type;
}
int VisualScriptFunctionCall::get_input_value_port_count() const {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
- Vector<Variant::Type> types = Variant::get_method_argument_types(basic_type, function);
+ Vector<Variant::Type> types;
+ int argc = Variant::get_builtin_method_argument_count(basic_type, function);
+ for (int i = 0; i < argc; i++) {
+ types.push_back(Variant::get_builtin_method_argument_type(basic_type, function, i));
+ }
return types.size() + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) + 1;
} else {
-
MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
int defaulted_args = mb->get_argument_count() < use_default_args ? mb->get_argument_count() : use_default_args;
@@ -141,12 +148,10 @@ int VisualScriptFunctionCall::get_input_value_port_count() const {
return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args;
}
}
-int VisualScriptFunctionCall::get_output_value_port_count() const {
+int VisualScriptFunctionCall::get_output_value_port_count() const {
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
- bool returns = false;
- Variant::get_method_return_type(basic_type, function, &returns);
+ bool returns = Variant::has_builtin_method_return_value(basic_type, function);
return returns ? 1 : 0;
} else {
@@ -154,8 +159,9 @@ int VisualScriptFunctionCall::get_output_value_port_count() const {
MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
ret = mb->has_return() ? 1 : 0;
- } else
+ } else {
ret = 1; //it is assumed that script always returns something
+ }
if (call_mode == CALL_MODE_INSTANCE) {
ret++;
@@ -166,12 +172,10 @@ int VisualScriptFunctionCall::get_output_value_port_count() const {
}
String VisualScriptFunctionCall::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptFunctionCall::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;
@@ -184,7 +188,6 @@ PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) cons
}
if (rpc_call_mode >= RPC_RELIABLE_TO_ID) {
-
if (p_idx == 0) {
return PropertyInfo(Variant::INT, "peer_id");
} else {
@@ -195,13 +198,8 @@ PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) cons
#ifdef DEBUG_METHODS_ENABLED
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
- Vector<StringName> names = Variant::get_method_argument_names(basic_type, function);
- Vector<Variant::Type> types = Variant::get_method_argument_types(basic_type, function);
- return PropertyInfo(types[p_idx], names[p_idx]);
-
+ return PropertyInfo(Variant::get_builtin_method_argument_type(basic_type, function, p_idx), Variant::get_builtin_method_argument_name(basic_type, function, p_idx));
} else {
-
MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
return mb->get_argument_info(p_idx);
@@ -219,14 +217,11 @@ PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) cons
}
PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) const {
-
#ifdef DEBUG_METHODS_ENABLED
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
- return PropertyInfo(Variant::get_method_return_type(basic_type, function), "");
+ return PropertyInfo(Variant::get_builtin_method_return_type(basic_type, function), "");
} else {
-
if (call_mode == CALL_MODE_INSTANCE) {
if (p_idx == 0) {
return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type());
@@ -239,7 +234,6 @@ PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) con
/*MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
if (mb) {
-
ret = mb->get_argument_info(-1);
} else {*/
@@ -260,20 +254,21 @@ PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) con
}
String VisualScriptFunctionCall::get_caption() const {
- if (call_mode == CALL_MODE_SELF)
+ if (call_mode == CALL_MODE_SELF) {
return " " + String(function) + "()";
- if (call_mode == CALL_MODE_SINGLETON)
+ }
+ if (call_mode == CALL_MODE_SINGLETON) {
return String(singleton) + ":" + String(function) + "()";
- else if (call_mode == CALL_MODE_BASIC_TYPE)
+ } else if (call_mode == CALL_MODE_BASIC_TYPE) {
return Variant::get_type_name(basic_type) + "." + String(function) + "()";
- else if (call_mode == CALL_MODE_NODE_PATH)
+ } else if (call_mode == CALL_MODE_NODE_PATH) {
return " [" + String(base_path.simplified()) + "]." + String(function) + "()";
- else
+ } else {
return " " + base_type + "." + String(function) + "()";
+ }
}
String VisualScriptFunctionCall::get_text() const {
-
if (rpc_call_mode) {
return "RPC";
}
@@ -281,9 +276,9 @@ String VisualScriptFunctionCall::get_text() const {
}
void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) {
-
- if (basic_type == p_type)
+ if (basic_type == p_type) {
return;
+ }
basic_type = p_type;
_change_notify();
@@ -291,14 +286,13 @@ void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) {
}
Variant::Type VisualScriptFunctionCall::get_basic_type() const {
-
return basic_type;
}
void VisualScriptFunctionCall::set_base_type(const StringName &p_type) {
-
- if (base_type == p_type)
+ if (base_type == p_type) {
return;
+ }
base_type = p_type;
_change_notify();
@@ -306,14 +300,13 @@ void VisualScriptFunctionCall::set_base_type(const StringName &p_type) {
}
StringName VisualScriptFunctionCall::get_base_type() const {
-
return base_type;
}
void VisualScriptFunctionCall::set_base_script(const String &p_path) {
-
- if (base_script == p_path)
+ if (base_script == p_path) {
return;
+ }
base_script = p_path;
_change_notify();
@@ -321,14 +314,13 @@ void VisualScriptFunctionCall::set_base_script(const String &p_path) {
}
String VisualScriptFunctionCall::get_base_script() const {
-
return base_script;
}
void VisualScriptFunctionCall::set_singleton(const StringName &p_type) {
-
- if (singleton == p_type)
+ if (singleton == p_type) {
return;
+ }
singleton = p_type;
Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
@@ -341,7 +333,6 @@ void VisualScriptFunctionCall::set_singleton(const StringName &p_type) {
}
StringName VisualScriptFunctionCall::get_singleton() const {
-
return singleton;
}
@@ -350,7 +341,6 @@ void VisualScriptFunctionCall::_update_method_cache() {
Ref<Script> script;
if (call_mode == CALL_MODE_NODE_PATH) {
-
Node *node = _get_base_node();
if (node) {
type = node->get_class();
@@ -358,7 +348,6 @@ void VisualScriptFunctionCall::_update_method_cache() {
script = node->get_script();
}
} else if (call_mode == CALL_MODE_SELF) {
-
if (get_visual_script().is_valid()) {
type = get_visual_script()->get_instance_base_type();
base_type = type; //cache, too
@@ -366,7 +355,6 @@ void VisualScriptFunctionCall::_update_method_cache() {
}
} else if (call_mode == CALL_MODE_SINGLETON) {
-
Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
if (obj) {
type = obj->get_class();
@@ -374,17 +362,13 @@ void VisualScriptFunctionCall::_update_method_cache() {
}
} else if (call_mode == CALL_MODE_INSTANCE) {
-
type = base_type;
if (base_script != String()) {
-
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
@@ -421,21 +405,20 @@ void VisualScriptFunctionCall::_update_method_cache() {
}
}
} else if (script.is_valid() && script->has_method(function)) {
-
method_cache = script->get_method_info(function);
use_default_args = method_cache.default_arguments.size();
}
}
void VisualScriptFunctionCall::set_function(const StringName &p_type) {
-
- if (function == p_type)
+ if (function == p_type) {
return;
+ }
function = p_type;
if (call_mode == CALL_MODE_BASIC_TYPE) {
- use_default_args = Variant::get_method_default_arguments(basic_type, function).size();
+ use_default_args = Variant::get_builtin_method_default_arguments(basic_type, function).size();
} else {
//update all caches
@@ -445,15 +428,15 @@ void VisualScriptFunctionCall::set_function(const StringName &p_type) {
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptFunctionCall::get_function() const {
+StringName VisualScriptFunctionCall::get_function() const {
return function;
}
void VisualScriptFunctionCall::set_base_path(const NodePath &p_type) {
-
- if (base_path == p_type)
+ if (base_path == p_type) {
return;
+ }
base_path = p_type;
_change_notify();
@@ -461,59 +444,54 @@ void VisualScriptFunctionCall::set_base_path(const NodePath &p_type) {
}
NodePath VisualScriptFunctionCall::get_base_path() const {
-
return base_path;
}
void VisualScriptFunctionCall::set_call_mode(CallMode p_mode) {
-
- if (call_mode == p_mode)
+ if (call_mode == p_mode) {
return;
+ }
call_mode = p_mode;
_change_notify();
ports_changed_notify();
}
-VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() const {
+VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() const {
return call_mode;
}
void VisualScriptFunctionCall::set_use_default_args(int p_amount) {
-
- if (use_default_args == p_amount)
+ if (use_default_args == p_amount) {
return;
+ }
use_default_args = p_amount;
ports_changed_notify();
}
void VisualScriptFunctionCall::set_rpc_call_mode(VisualScriptFunctionCall::RPCCallMode p_mode) {
-
- if (rpc_call_mode == p_mode)
+ if (rpc_call_mode == p_mode) {
return;
+ }
rpc_call_mode = p_mode;
ports_changed_notify();
_change_notify();
}
VisualScriptFunctionCall::RPCCallMode VisualScriptFunctionCall::get_rpc_call_mode() const {
-
return rpc_call_mode;
}
int VisualScriptFunctionCall::get_use_default_args() const {
-
return use_default_args;
}
void VisualScriptFunctionCall::set_validate(bool p_amount) {
-
validate = p_amount;
}
bool VisualScriptFunctionCall::get_validate() const {
-
return validate;
}
@@ -523,12 +501,10 @@ void VisualScriptFunctionCall::_set_argument_cache(const Dictionary &p_cache) {
}
Dictionary VisualScriptFunctionCall::_get_argument_cache() const {
-
return method_cache;
}
void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const {
-
if (property.name == "base_type") {
if (call_mode != CALL_MODE_INSTANCE) {
property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
@@ -556,8 +532,9 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
property.hint = PROPERTY_HINT_ENUM;
String sl;
for (List<Engine::Singleton>::Element *E = names.front(); E; E = E->next()) {
- if (sl != String())
+ if (sl != String()) {
sl += ",";
+ }
sl += E->get().name;
}
property.hint_string = sl;
@@ -568,7 +545,6 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
if (call_mode != CALL_MODE_NODE_PATH) {
property.usage = 0;
} else {
-
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
@@ -577,9 +553,7 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
}
if (property.name == "function") {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
property.hint = PROPERTY_HINT_METHOD_OF_VARIANT_TYPE;
property.hint_string = Variant::get_type_name(basic_type);
@@ -587,13 +561,11 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
property.hint = PROPERTY_HINT_METHOD_OF_SCRIPT;
property.hint_string = itos(get_visual_script()->get_instance_id());
} else if (call_mode == CALL_MODE_SINGLETON) {
-
Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
if (obj) {
property.hint = PROPERTY_HINT_METHOD_OF_INSTANCE;
property.hint_string = itos(obj->get_instance_id());
} else {
-
property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
property.hint_string = base_type; //should be cached
}
@@ -603,15 +575,12 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
Ref<Script> script = Ref<Resource>(ResourceCache::get(base_script));
if (script.is_valid()) {
-
property.hint = PROPERTY_HINT_METHOD_OF_SCRIPT;
property.hint_string = itos(script->get_instance_id());
}
@@ -631,18 +600,15 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
}
if (property.name == "use_default_args") {
-
property.hint = PROPERTY_HINT_RANGE;
int mc = 0;
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
- mc = Variant::get_method_default_arguments(basic_type, function).size();
+ mc = Variant::get_builtin_method_default_arguments(basic_type, function).size();
} else {
MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
-
mc = mb->get_default_argument_count();
}
}
@@ -650,7 +616,6 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
if (mc == 0) {
property.usage = 0; //do not show
} else {
-
property.hint_string = "0," + itos(mc) + ",1";
}
}
@@ -663,7 +628,6 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
}
void VisualScriptFunctionCall::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptFunctionCall::set_base_type);
ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptFunctionCall::get_base_type);
@@ -699,8 +663,9 @@ void VisualScriptFunctionCall::_bind_methods() {
String bt;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0)
+ if (i > 0) {
bt += ",";
+ }
bt += Variant::get_type_name(Variant::Type(i));
}
@@ -712,8 +677,9 @@ void VisualScriptFunctionCall::_bind_methods() {
String script_ext_hint;
for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
- if (script_ext_hint != String())
+ if (script_ext_hint != String()) {
script_ext_hint += ",";
+ }
script_ext_hint += "*." + E->get();
}
@@ -761,13 +727,14 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
_FORCE_INLINE_ bool call_rpc(Object *p_base, const Variant **p_args, int p_argcount) {
-
- if (!p_base)
+ if (!p_base) {
return false;
+ }
Node *node = Object::cast_to<Node>(p_base);
- if (!node)
+ if (!node) {
return false;
+ }
int to_id = 0;
bool reliable = true;
@@ -789,11 +756,8 @@ public:
}
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
switch (call_mode) {
-
case VisualScriptFunctionCall::CALL_MODE_SELF: {
-
Object *object = instance->get_owner_ptr();
if (rpc_mode) {
@@ -805,7 +769,6 @@ public:
}
} break;
case VisualScriptFunctionCall::CALL_MODE_NODE_PATH: {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -831,7 +794,6 @@ public:
} break;
case VisualScriptFunctionCall::CALL_MODE_INSTANCE:
case VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE: {
-
Variant v = *p_inputs[0];
if (rpc_mode) {
@@ -842,19 +804,21 @@ public:
} else if (returns) {
if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
if (returns >= 2) {
- *p_outputs[1] = v.call(function, p_inputs + 1, input_args, r_error);
+ v.call(function, p_inputs + 1, input_args, *p_outputs[1], r_error);
} else if (returns == 1) {
- v.call(function, p_inputs + 1, input_args, r_error);
+ Variant ret;
+ v.call(function, p_inputs + 1, input_args, ret, r_error);
} else {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = "Invalid returns count for call_mode == CALL_MODE_INSTANCE";
return 0;
}
} else {
- *p_outputs[0] = v.call(function, p_inputs + 1, input_args, r_error);
+ v.call(function, p_inputs + 1, input_args, *p_outputs[0], r_error);
}
} else {
- v.call(function, p_inputs + 1, input_args, r_error);
+ Variant ret;
+ v.call(function, p_inputs + 1, input_args, ret, r_error);
}
if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
@@ -863,7 +827,6 @@ public:
} break;
case VisualScriptFunctionCall::CALL_MODE_SINGLETON: {
-
Object *object = Engine::get_singleton()->get_singleton_object(singleton);
if (!object) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -882,7 +845,6 @@ public:
}
if (!validate) {
-
//ignore call errors if validation is disabled
r_error.error = Callable::CallError::CALL_OK;
r_error_str = String();
@@ -893,7 +855,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptFunctionCall::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceFunctionCall *instance = memnew(VisualScriptNodeInstanceFunctionCall);
instance->node = this;
instance->instance = p_instance;
@@ -909,7 +870,6 @@ VisualScriptNodeInstance *VisualScriptFunctionCall::instance(VisualScriptInstanc
}
VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
return p_inputs[0];
}
@@ -918,7 +878,6 @@ VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(
}
VisualScriptFunctionCall::VisualScriptFunctionCall() {
-
validate = true;
call_mode = CALL_MODE_SELF;
basic_type = Variant::NIL;
@@ -929,7 +888,6 @@ VisualScriptFunctionCall::VisualScriptFunctionCall() {
template <VisualScriptFunctionCall::CallMode cmode>
static Ref<VisualScriptNode> create_function_call_node(const String &p_name) {
-
Ref<VisualScriptFunctionCall> node;
node.instance();
node->set_call_mode(cmode);
@@ -941,41 +899,43 @@ static Ref<VisualScriptNode> create_function_call_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptPropertySet::get_output_sequence_port_count() const {
-
return call_mode != CALL_MODE_BASIC_TYPE ? 1 : 0;
}
bool VisualScriptPropertySet::has_input_sequence_port() const {
-
return call_mode != CALL_MODE_BASIC_TYPE;
}
Node *VisualScriptPropertySet::_get_base_node() const {
-
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return nullptr;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return nullptr;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return nullptr;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return nullptr;
+ }
- if (!script_node->has_node(base_path))
+ if (!script_node->has_node(base_path)) {
return nullptr;
+ }
Node *path_to = script_node->get_node(base_path);
@@ -987,41 +947,37 @@ Node *VisualScriptPropertySet::_get_base_node() const {
}
StringName VisualScriptPropertySet::_get_base_type() const {
-
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid())
+ if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
return get_visual_script()->get_instance_base_type();
- else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
+ } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
Node *path = _get_base_node();
- if (path)
+ if (path) {
return path->get_class();
+ }
}
return base_type;
}
int VisualScriptPropertySet::get_input_value_port_count() const {
-
int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1;
return pc;
}
-int VisualScriptPropertySet::get_output_value_port_count() const {
+int VisualScriptPropertySet::get_output_value_port_count() const {
return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0;
}
String VisualScriptPropertySet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
void VisualScriptPropertySet::_adjust_input_index(PropertyInfo &pinfo) const {
-
if (index != StringName()) {
-
Variant v;
Callable::CallError ce;
- v = Variant::construct(pinfo.type, nullptr, 0, ce);
+ Variant::construct(pinfo.type, v, nullptr, 0, ce);
Variant i = v.get(index);
pinfo.type = i.get_type();
}
@@ -1065,7 +1021,6 @@ PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) cons
}
String VisualScriptPropertySet::get_caption() const {
-
static const char *opname[ASSIGN_OP_MAX] = {
"Set", "Add", "Subtract", "Multiply", "Divide", "Mod", "ShiftLeft", "ShiftRight", "BitAnd", "BitOr", "BitXor"
};
@@ -1079,7 +1034,6 @@ String VisualScriptPropertySet::get_caption() const {
}
String VisualScriptPropertySet::get_text() const {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
return String("On ") + Variant::get_type_name(basic_type);
}
@@ -1096,22 +1050,21 @@ String VisualScriptPropertySet::get_text() const {
void VisualScriptPropertySet::_update_base_type() {
//cache it because this information may not be available on load
if (call_mode == CALL_MODE_NODE_PATH) {
-
Node *node = _get_base_node();
if (node) {
base_type = node->get_class();
}
} else if (call_mode == CALL_MODE_SELF) {
-
if (get_visual_script().is_valid()) {
base_type = get_visual_script()->get_instance_base_type();
}
}
}
-void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) {
- if (basic_type == p_type)
+void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) {
+ if (basic_type == p_type) {
return;
+ }
basic_type = p_type;
_change_notify();
@@ -1120,14 +1073,13 @@ void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) {
}
Variant::Type VisualScriptPropertySet::get_basic_type() const {
-
return basic_type;
}
void VisualScriptPropertySet::set_base_type(const StringName &p_type) {
-
- if (base_type == p_type)
+ if (base_type == p_type) {
return;
+ }
base_type = p_type;
_change_notify();
@@ -1135,14 +1087,13 @@ void VisualScriptPropertySet::set_base_type(const StringName &p_type) {
}
StringName VisualScriptPropertySet::get_base_type() const {
-
return base_type;
}
void VisualScriptPropertySet::set_base_script(const String &p_path) {
-
- if (base_script == p_path)
+ if (base_script == p_path) {
return;
+ }
base_script = p_path;
_change_notify();
@@ -1150,45 +1101,40 @@ void VisualScriptPropertySet::set_base_script(const String &p_path) {
}
String VisualScriptPropertySet::get_base_script() const {
-
return base_script;
}
void VisualScriptPropertySet::_update_cache() {
-
- if (!Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()))
+ if (!Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop())) {
return;
+ }
- if (!Engine::get_singleton()->is_editor_hint()) //only update cache if editor exists, it's pointless otherwise
+ if (!Engine::get_singleton()->is_editor_hint()) { //only update cache if editor exists, it's pointless otherwise
return;
+ }
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
//not super efficient..
Variant v;
Callable::CallError ce;
- v = Variant::construct(basic_type, nullptr, 0, ce);
+ Variant::construct(basic_type, v, nullptr, 0, ce);
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
-
if (E->get().name == property) {
-
type_cache = E->get();
}
}
} else {
-
StringName type;
Ref<Script> script;
Node *node = nullptr;
if (call_mode == CALL_MODE_NODE_PATH) {
-
node = _get_base_node();
if (node) {
type = node->get_class();
@@ -1196,24 +1142,19 @@ void VisualScriptPropertySet::_update_cache() {
script = node->get_script();
}
} else if (call_mode == CALL_MODE_SELF) {
-
if (get_visual_script().is_valid()) {
type = get_visual_script()->get_instance_base_type();
base_type = type; //cache, too
script = get_visual_script();
}
} else if (call_mode == CALL_MODE_INSTANCE) {
-
type = base_type;
if (base_script != String()) {
-
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
@@ -1224,19 +1165,16 @@ void VisualScriptPropertySet::_update_cache() {
List<PropertyInfo> pinfo;
if (node) {
-
node->get_property_list(&pinfo);
} else {
ClassDB::get_property_list(type, &pinfo);
}
if (script.is_valid()) {
-
script->get_script_property_list(&pinfo);
}
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
-
if (E->get().name == property) {
type_cache = E->get();
return;
@@ -1246,9 +1184,9 @@ void VisualScriptPropertySet::_update_cache() {
}
void VisualScriptPropertySet::set_property(const StringName &p_type) {
-
- if (property == p_type)
+ if (property == p_type) {
return;
+ }
property = p_type;
index = StringName();
@@ -1256,15 +1194,15 @@ void VisualScriptPropertySet::set_property(const StringName &p_type) {
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptPropertySet::get_property() const {
+StringName VisualScriptPropertySet::get_property() const {
return property;
}
void VisualScriptPropertySet::set_base_path(const NodePath &p_type) {
-
- if (base_path == p_type)
+ if (base_path == p_type) {
return;
+ }
base_path = p_type;
_update_base_type();
@@ -1273,22 +1211,21 @@ void VisualScriptPropertySet::set_base_path(const NodePath &p_type) {
}
NodePath VisualScriptPropertySet::get_base_path() const {
-
return base_path;
}
void VisualScriptPropertySet::set_call_mode(CallMode p_mode) {
-
- if (call_mode == p_mode)
+ if (call_mode == p_mode) {
return;
+ }
call_mode = p_mode;
_update_base_type();
_change_notify();
ports_changed_notify();
}
-VisualScriptPropertySet::CallMode VisualScriptPropertySet::get_call_mode() const {
+VisualScriptPropertySet::CallMode VisualScriptPropertySet::get_call_mode() const {
return call_mode;
}
@@ -1297,14 +1234,13 @@ void VisualScriptPropertySet::_set_type_cache(const Dictionary &p_type) {
}
Dictionary VisualScriptPropertySet::_get_type_cache() const {
-
return type_cache;
}
void VisualScriptPropertySet::set_index(const StringName &p_type) {
-
- if (index == p_type)
+ if (index == p_type) {
return;
+ }
index = p_type;
_update_cache();
_change_notify();
@@ -1312,15 +1248,14 @@ void VisualScriptPropertySet::set_index(const StringName &p_type) {
}
StringName VisualScriptPropertySet::get_index() const {
-
return index;
}
void VisualScriptPropertySet::set_assign_op(AssignOp p_op) {
-
ERR_FAIL_INDEX(p_op, ASSIGN_OP_MAX);
- if (assign_op == p_op)
+ if (assign_op == p_op) {
return;
+ }
assign_op = p_op;
_update_cache();
@@ -1333,7 +1268,6 @@ VisualScriptPropertySet::AssignOp VisualScriptPropertySet::get_assign_op() const
}
void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
-
if (property.name == "base_type") {
if (call_mode != CALL_MODE_INSTANCE) {
property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
@@ -1356,7 +1290,6 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
if (call_mode != CALL_MODE_NODE_PATH) {
property.usage = 0;
} else {
-
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
@@ -1365,9 +1298,7 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
}
if (property.name == "property") {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
property.hint_string = Variant::get_type_name(basic_type);
@@ -1380,15 +1311,12 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
Ref<Script> script = Ref<Resource>(ResourceCache::get(base_script));
if (script.is_valid()) {
-
property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
property.hint_string = itos(script->get_instance_id());
}
@@ -1408,9 +1336,9 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
}
if (property.name == "index") {
-
Callable::CallError ce;
- Variant v = Variant::construct(type_cache.type, nullptr, 0, ce);
+ Variant v;
+ Variant::construct(type_cache.type, v, nullptr, 0, ce);
List<PropertyInfo> plist;
v.get_property_list(&plist);
String options = "";
@@ -1421,13 +1349,13 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
property.hint = PROPERTY_HINT_ENUM;
property.hint_string = options;
property.type = Variant::STRING;
- if (options == "")
+ if (options == "") {
property.usage = 0; //hide if type has no usable index
+ }
}
}
void VisualScriptPropertySet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertySet::set_base_type);
ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertySet::get_base_type);
@@ -1457,8 +1385,9 @@ void VisualScriptPropertySet::_bind_methods() {
String bt;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0)
+ if (i > 0) {
bt += ",";
+ }
bt += Variant::get_type_name(Variant::Type(i));
}
@@ -1470,8 +1399,9 @@ void VisualScriptPropertySet::_bind_methods() {
String script_ext_hint;
for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
- if (script_ext_hint != String())
+ if (script_ext_hint != String()) {
script_ext_hint += ",";
+ }
script_ext_hint += "*." + E->get();
}
@@ -1520,14 +1450,12 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
_FORCE_INLINE_ void _process_get(Variant &source, const Variant &p_argument, bool &valid) {
-
if (index != StringName() && assign_op == VisualScriptPropertySet::ASSIGN_OP_NONE) {
- source.set_named(index, p_argument, &valid);
+ source.set_named(index, p_argument, valid);
} else {
-
Variant value;
if (index != StringName()) {
- value = source.get_named(index, &valid);
+ value = source.get_named(index, valid);
} else {
value = source;
}
@@ -1571,7 +1499,7 @@ public:
}
if (index != StringName()) {
- source.set_named(index, value, &valid);
+ source.set_named(index, value, valid);
} else {
source = value;
}
@@ -1579,11 +1507,8 @@ public:
}
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
switch (call_mode) {
-
case VisualScriptPropertySet::CALL_MODE_SELF: {
-
Object *object = instance->get_owner_ptr();
bool valid;
@@ -1602,7 +1527,6 @@ public:
}
} break;
case VisualScriptPropertySet::CALL_MODE_NODE_PATH: {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -1620,7 +1544,6 @@ public:
bool valid;
if (needs_get) {
-
Variant value = another->get(property, &valid);
_process_get(value, *p_inputs[0], valid);
another->set(property, value, &valid);
@@ -1636,18 +1559,17 @@ public:
} break;
case VisualScriptPropertySet::CALL_MODE_INSTANCE:
case VisualScriptPropertySet::CALL_MODE_BASIC_TYPE: {
-
Variant v = *p_inputs[0];
bool valid;
if (needs_get) {
- Variant value = v.get_named(property, &valid);
+ Variant value = v.get_named(property, valid);
_process_get(value, *p_inputs[1], valid);
- v.set_named(property, value, &valid);
+ v.set_named(property, value, valid);
} else {
- v.set_named(property, *p_inputs[1], &valid);
+ v.set_named(property, *p_inputs[1], valid);
}
if (!valid) {
@@ -1664,7 +1586,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptPropertySet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstancePropertySet *instance = memnew(VisualScriptNodeInstancePropertySet);
instance->node = this;
instance->instance = p_instance;
@@ -1678,15 +1599,14 @@ VisualScriptNodeInstance *VisualScriptPropertySet::instance(VisualScriptInstance
}
VisualScriptPropertySet::TypeGuess VisualScriptPropertySet::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
return p_inputs[0];
}
return VisualScriptNode::guess_output_type(p_inputs, p_output);
}
-VisualScriptPropertySet::VisualScriptPropertySet() {
+VisualScriptPropertySet::VisualScriptPropertySet() {
assign_op = ASSIGN_OP_NONE;
call_mode = CALL_MODE_SELF;
base_type = "Object";
@@ -1695,7 +1615,6 @@ VisualScriptPropertySet::VisualScriptPropertySet() {
template <VisualScriptPropertySet::CallMode cmode>
static Ref<VisualScriptNode> create_property_set_node(const String &p_name) {
-
Ref<VisualScriptPropertySet> node;
node.instance();
node->set_call_mode(cmode);
@@ -1707,55 +1626,57 @@ static Ref<VisualScriptNode> create_property_set_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptPropertyGet::get_output_sequence_port_count() const {
-
return 0; // (call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?0:1;
}
bool VisualScriptPropertyGet::has_input_sequence_port() const {
-
return false; //(call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?false:true;
}
+
void VisualScriptPropertyGet::_update_base_type() {
//cache it because this information may not be available on load
if (call_mode == CALL_MODE_NODE_PATH) {
-
Node *node = _get_base_node();
if (node) {
base_type = node->get_class();
}
} else if (call_mode == CALL_MODE_SELF) {
-
if (get_visual_script().is_valid()) {
base_type = get_visual_script()->get_instance_base_type();
}
}
}
-Node *VisualScriptPropertyGet::_get_base_node() const {
+Node *VisualScriptPropertyGet::_get_base_node() const {
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return nullptr;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return nullptr;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return nullptr;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return nullptr;
+ }
- if (!script_node->has_node(base_path))
+ if (!script_node->has_node(base_path)) {
return nullptr;
+ }
Node *path_to = script_node->get_node(base_path);
@@ -1767,34 +1688,31 @@ Node *VisualScriptPropertyGet::_get_base_node() const {
}
StringName VisualScriptPropertyGet::_get_base_type() const {
-
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid())
+ if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
return get_visual_script()->get_instance_base_type();
- else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
+ } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
Node *path = _get_base_node();
- if (path)
+ if (path) {
return path->get_class();
+ }
}
return base_type;
}
int VisualScriptPropertyGet::get_input_value_port_count() const {
-
return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0;
}
-int VisualScriptPropertyGet::get_output_value_port_count() const {
+int VisualScriptPropertyGet::get_output_value_port_count() const {
return 1;
}
String VisualScriptPropertyGet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptPropertyGet::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;
@@ -1819,12 +1737,10 @@ PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) cons
}
String VisualScriptPropertyGet::get_caption() const {
-
return String("Get ") + property;
}
String VisualScriptPropertyGet::get_text() const {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
return String("On ") + Variant::get_type_name(basic_type);
}
@@ -1839,9 +1755,9 @@ String VisualScriptPropertyGet::get_text() const {
}
void VisualScriptPropertyGet::set_base_type(const StringName &p_type) {
-
- if (base_type == p_type)
+ if (base_type == p_type) {
return;
+ }
base_type = p_type;
_change_notify();
@@ -1849,14 +1765,13 @@ void VisualScriptPropertyGet::set_base_type(const StringName &p_type) {
}
StringName VisualScriptPropertyGet::get_base_type() const {
-
return base_type;
}
void VisualScriptPropertyGet::set_base_script(const String &p_path) {
-
- if (base_script == p_path)
+ if (base_script == p_path) {
return;
+ }
base_script = p_path;
_change_notify();
@@ -1864,40 +1779,33 @@ void VisualScriptPropertyGet::set_base_script(const String &p_path) {
}
String VisualScriptPropertyGet::get_base_script() const {
-
return base_script;
}
void VisualScriptPropertyGet::_update_cache() {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
//not super efficient..
Variant v;
Callable::CallError ce;
- v = Variant::construct(basic_type, nullptr, 0, ce);
+ Variant::construct(basic_type, v, nullptr, 0, ce);
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
-
if (E->get().name == property) {
-
type_cache = E->get().type;
return;
}
}
} else {
-
StringName type;
Ref<Script> script;
Node *node = nullptr;
if (call_mode == CALL_MODE_NODE_PATH) {
-
node = _get_base_node();
if (node) {
type = node->get_class();
@@ -1905,24 +1813,19 @@ void VisualScriptPropertyGet::_update_cache() {
script = node->get_script();
}
} else if (call_mode == CALL_MODE_SELF) {
-
if (get_visual_script().is_valid()) {
type = get_visual_script()->get_instance_base_type();
base_type = type; //cache, too
script = get_visual_script();
}
} else if (call_mode == CALL_MODE_INSTANCE) {
-
type = base_type;
if (base_script != String()) {
-
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
@@ -1942,7 +1845,6 @@ void VisualScriptPropertyGet::_update_cache() {
}
if (node) {
-
Variant prop = node->get(property, &valid);
if (valid) {
type_cache = prop.get_type();
@@ -1951,7 +1853,6 @@ void VisualScriptPropertyGet::_update_cache() {
}
if (script.is_valid()) {
-
type_ret = script->get_static_property_type(property, &valid);
if (valid) {
@@ -1963,9 +1864,9 @@ void VisualScriptPropertyGet::_update_cache() {
}
void VisualScriptPropertyGet::set_property(const StringName &p_type) {
-
- if (property == p_type)
+ if (property == p_type) {
return;
+ }
property = p_type;
@@ -1973,15 +1874,15 @@ void VisualScriptPropertyGet::set_property(const StringName &p_type) {
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptPropertyGet::get_property() const {
+StringName VisualScriptPropertyGet::get_property() const {
return property;
}
void VisualScriptPropertyGet::set_base_path(const NodePath &p_type) {
-
- if (base_path == p_type)
+ if (base_path == p_type) {
return;
+ }
base_path = p_type;
_change_notify();
@@ -1990,29 +1891,28 @@ void VisualScriptPropertyGet::set_base_path(const NodePath &p_type) {
}
NodePath VisualScriptPropertyGet::get_base_path() const {
-
return base_path;
}
void VisualScriptPropertyGet::set_call_mode(CallMode p_mode) {
-
- if (call_mode == p_mode)
+ if (call_mode == p_mode) {
return;
+ }
call_mode = p_mode;
_change_notify();
_update_base_type();
ports_changed_notify();
}
-VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const {
+VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const {
return call_mode;
}
void VisualScriptPropertyGet::set_basic_type(Variant::Type p_type) {
-
- if (basic_type == p_type)
+ if (basic_type == p_type) {
return;
+ }
basic_type = p_type;
_change_notify();
@@ -2020,7 +1920,6 @@ void VisualScriptPropertyGet::set_basic_type(Variant::Type p_type) {
}
Variant::Type VisualScriptPropertyGet::get_basic_type() const {
-
return basic_type;
}
@@ -2029,14 +1928,13 @@ void VisualScriptPropertyGet::_set_type_cache(Variant::Type p_type) {
}
Variant::Type VisualScriptPropertyGet::_get_type_cache() const {
-
return type_cache;
}
void VisualScriptPropertyGet::set_index(const StringName &p_type) {
-
- if (index == p_type)
+ if (index == p_type) {
return;
+ }
index = p_type;
_update_cache();
_change_notify();
@@ -2044,12 +1942,10 @@ void VisualScriptPropertyGet::set_index(const StringName &p_type) {
}
StringName VisualScriptPropertyGet::get_index() const {
-
return index;
}
void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
-
if (property.name == "base_type") {
if (call_mode != CALL_MODE_INSTANCE) {
property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
@@ -2072,7 +1968,6 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
if (call_mode != CALL_MODE_NODE_PATH) {
property.usage = 0;
} else {
-
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
@@ -2081,9 +1976,7 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
}
if (property.name == "property") {
-
if (call_mode == CALL_MODE_BASIC_TYPE) {
-
property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
property.hint_string = Variant::get_type_name(basic_type);
@@ -2096,15 +1989,12 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
-
ScriptServer::edit_request_func(base_script); //make sure it's loaded
}
if (ResourceCache::has(base_script)) {
-
Ref<Script> script = Ref<Resource>(ResourceCache::get(base_script));
if (script.is_valid()) {
-
property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
property.hint_string = itos(script->get_instance_id());
}
@@ -2123,9 +2013,9 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
}
if (property.name == "index") {
-
Callable::CallError ce;
- Variant v = Variant::construct(type_cache, nullptr, 0, ce);
+ Variant v;
+ Variant::construct(type_cache, v, nullptr, 0, ce);
List<PropertyInfo> plist;
v.get_property_list(&plist);
String options = "";
@@ -2136,13 +2026,13 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
property.hint = PROPERTY_HINT_ENUM;
property.hint_string = options;
property.type = Variant::STRING;
- if (options == "")
+ if (options == "") {
property.usage = 0; //hide if type has no usable index
+ }
}
}
void VisualScriptPropertyGet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertyGet::set_base_type);
ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertyGet::get_base_type);
@@ -2169,8 +2059,9 @@ void VisualScriptPropertyGet::_bind_methods() {
String bt;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0)
+ if (i > 0) {
bt += ",";
+ }
bt += Variant::get_type_name(Variant::Type(i));
}
@@ -2182,8 +2073,9 @@ void VisualScriptPropertyGet::_bind_methods() {
String script_ext_hint;
for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
- if (script_ext_hint != String())
+ if (script_ext_hint != String()) {
script_ext_hint += ",";
+ }
script_ext_hint += "." + E->get();
}
@@ -2199,6 +2091,7 @@ void VisualScriptPropertyGet::_bind_methods() {
BIND_ENUM_CONSTANT(CALL_MODE_SELF);
BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH);
BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE);
+ BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE);
}
class VisualScriptNodeInstancePropertyGet : public VisualScriptNodeInstance {
@@ -2212,11 +2105,8 @@ public:
VisualScriptInstance *instance;
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
switch (call_mode) {
-
case VisualScriptPropertyGet::CALL_MODE_SELF: {
-
Object *object = instance->get_owner_ptr();
bool valid;
@@ -2224,7 +2114,7 @@ public:
*p_outputs[0] = object->get(property, &valid);
if (index != StringName()) {
- *p_outputs[0] = p_outputs[0]->get_named(index);
+ *p_outputs[0] = p_outputs[0]->get_named(index, valid);
}
if (!valid) {
@@ -2234,7 +2124,6 @@ public:
}
} break;
case VisualScriptPropertyGet::CALL_MODE_NODE_PATH: {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -2254,7 +2143,7 @@ public:
*p_outputs[0] = another->get(property, &valid);
if (index != StringName()) {
- *p_outputs[0] = p_outputs[0]->get_named(index);
+ *p_outputs[0] = p_outputs[0]->get_named(index, valid);
}
if (!valid) {
@@ -2265,13 +2154,12 @@ public:
} break;
default: {
-
bool valid;
Variant v = *p_inputs[0];
*p_outputs[0] = v.get(property, &valid);
if (index != StringName()) {
- *p_outputs[0] = p_outputs[0]->get_named(index);
+ *p_outputs[0] = p_outputs[0]->get_named(index, valid);
}
if (!valid) {
@@ -2286,7 +2174,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptPropertyGet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstancePropertyGet *instance = memnew(VisualScriptNodeInstancePropertyGet);
instance->node = this;
instance->instance = p_instance;
@@ -2299,7 +2186,6 @@ VisualScriptNodeInstance *VisualScriptPropertyGet::instance(VisualScriptInstance
}
VisualScriptPropertyGet::VisualScriptPropertyGet() {
-
call_mode = CALL_MODE_SELF;
base_type = "Object";
basic_type = Variant::NIL;
@@ -2308,7 +2194,6 @@ VisualScriptPropertyGet::VisualScriptPropertyGet() {
template <VisualScriptPropertyGet::CallMode cmode>
static Ref<VisualScriptNode> create_property_get_node(const String &p_name) {
-
Ref<VisualScriptPropertyGet> node;
node.instance();
node->set_call_mode(cmode);
@@ -2320,44 +2205,40 @@ static Ref<VisualScriptNode> create_property_get_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptEmitSignal::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptEmitSignal::has_input_sequence_port() const {
-
return true;
}
int VisualScriptEmitSignal::get_input_value_port_count() const {
-
Ref<VisualScript> vs = get_visual_script();
if (vs.is_valid()) {
-
- if (!vs->has_custom_signal(name))
+ if (!vs->has_custom_signal(name)) {
return 0;
+ }
return vs->custom_signal_get_argument_count(name);
}
return 0;
}
+
int VisualScriptEmitSignal::get_output_value_port_count() const {
return 0;
}
String VisualScriptEmitSignal::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const {
-
Ref<VisualScript> vs = get_visual_script();
if (vs.is_valid()) {
-
- if (!vs->has_custom_signal(name))
+ if (!vs->has_custom_signal(name)) {
return PropertyInfo();
+ }
return PropertyInfo(vs->custom_signal_get_argument_type(name, p_idx), vs->custom_signal_get_argument_name(name, p_idx));
}
@@ -2366,32 +2247,29 @@ PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const
}
PropertyInfo VisualScriptEmitSignal::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptEmitSignal::get_caption() const {
-
return "Emit " + String(name);
}
void VisualScriptEmitSignal::set_signal(const StringName &p_type) {
-
- if (name == p_type)
+ if (name == p_type) {
return;
+ }
name = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptEmitSignal::get_signal() const {
+StringName VisualScriptEmitSignal::get_signal() const {
return name;
}
void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const {
-
if (property.name == "signal") {
property.hint = PROPERTY_HINT_ENUM;
@@ -2399,15 +2277,14 @@ void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const {
Ref<VisualScript> vs = get_visual_script();
if (vs.is_valid()) {
-
vs->get_custom_signal_list(&sigs);
}
String ml;
for (List<StringName>::Element *E = sigs.front(); E; E = E->next()) {
-
- if (ml != String())
+ if (ml != String()) {
ml += ",";
+ }
ml += E->get();
}
@@ -2416,7 +2293,6 @@ void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const {
}
void VisualScriptEmitSignal::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_signal", "name"), &VisualScriptEmitSignal::set_signal);
ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptEmitSignal::get_signal);
@@ -2435,7 +2311,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Object *obj = instance->get_owner_ptr();
obj->emit_signal(name, p_inputs, argcount);
@@ -2445,7 +2320,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptEmitSignal::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceEmitSignal *instance = memnew(VisualScriptNodeInstanceEmitSignal);
instance->node = this;
instance->instance = p_instance;
@@ -2458,7 +2332,6 @@ VisualScriptEmitSignal::VisualScriptEmitSignal() {
}
static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) {
-
Vector<String> path = p_name.split("/");
ERR_FAIL_COND_V(path.size() < 4, Ref<VisualScriptNode>());
String base_type = path[2];
@@ -2470,7 +2343,6 @@ static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) {
Variant::Type type = Variant::VARIANT_MAX;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
-
if (Variant::get_type_name(Variant::Type(i)) == base_type) {
type = Variant::Type(i);
break;
@@ -2487,7 +2359,6 @@ static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) {
}
void register_visual_script_func_nodes() {
-
VisualScriptLanguage::singleton->add_register_func("functions/call", create_node_generic<VisualScriptFunctionCall>);
VisualScriptLanguage::singleton->add_register_func("functions/set", create_node_generic<VisualScriptPropertySet>);
VisualScriptLanguage::singleton->add_register_func("functions/get", create_node_generic<VisualScriptPropertyGet>);
@@ -2497,11 +2368,11 @@ void register_visual_script_func_nodes() {
VisualScriptLanguage::singleton->add_register_func("functions/emit_signal", create_node_generic<VisualScriptEmitSignal>);
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
-
Variant::Type t = Variant::Type(i);
String type_name = Variant::get_type_name(t);
Callable::CallError ce;
- Variant vt = Variant::construct(t, nullptr, 0, ce);
+ Variant vt;
+ Variant::construct(t, vt, nullptr, 0, ce);
List<MethodInfo> ml;
vt.get_method_list(&ml);
diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h
index 2dba0ae3c1..2ff9b7a981 100644
--- a/modules/visual_script/visual_script_func_nodes.h
+++ b/modules/visual_script/visual_script_func_nodes.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "visual_script.h"
class VisualScriptFunctionCall : public VisualScriptNode {
-
GDCLASS(VisualScriptFunctionCall, VisualScriptNode);
public:
@@ -76,25 +75,25 @@ private:
Dictionary _get_argument_cache() const;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
void set_basic_type(Variant::Type p_type);
Variant::Type get_basic_type() const;
@@ -126,9 +125,9 @@ public:
void set_rpc_call_mode(RPCCallMode p_mode);
RPCCallMode get_rpc_call_mode() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptFunctionCall();
};
@@ -137,7 +136,6 @@ VARIANT_ENUM_CAST(VisualScriptFunctionCall::CallMode);
VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode);
class VisualScriptPropertySet : public VisualScriptNode {
-
GDCLASS(VisualScriptPropertySet, VisualScriptNode);
public:
@@ -189,25 +187,25 @@ private:
void _adjust_input_index(PropertyInfo &pinfo) const;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
void set_base_type(const StringName &p_type);
StringName get_base_type() const;
@@ -233,8 +231,8 @@ public:
void set_assign_op(AssignOp p_op);
AssignOp get_assign_op() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptPropertySet();
};
@@ -243,7 +241,6 @@ VARIANT_ENUM_CAST(VisualScriptPropertySet::CallMode);
VARIANT_ENUM_CAST(VisualScriptPropertySet::AssignOp);
class VisualScriptPropertyGet : public VisualScriptNode {
-
GDCLASS(VisualScriptPropertyGet, VisualScriptNode);
public:
@@ -276,25 +273,25 @@ private:
Variant::Type _get_type_cache() const;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
void set_base_type(const StringName &p_type);
StringName get_base_type() const;
@@ -317,7 +314,7 @@ public:
void set_index(const StringName &p_type);
StringName get_index() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptPropertyGet();
};
@@ -325,37 +322,36 @@ public:
VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode);
class VisualScriptEmitSignal : public VisualScriptNode {
-
GDCLASS(VisualScriptEmitSignal, VisualScriptNode);
private:
StringName name;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
+ virtual String get_caption() const override;
//virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_category() const override { return "functions"; }
void set_signal(const StringName &p_type);
StringName get_signal() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptEmitSignal();
};
diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp
index 52399d29d0..ae2b548f21 100644
--- a/modules/visual_script/visual_script_nodes.cpp
+++ b/modules/visual_script/visual_script_nodes.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,11 +30,11 @@
#include "visual_script_nodes.h"
-#include "core/engine.h"
-#include "core/global_constants.h"
+#include "core/config/engine.h"
+#include "core/config/project_settings.h"
+#include "core/core_constants.h"
#include "core/input/input.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "scene/main/node.h"
#include "scene/main/scene_tree.h"
@@ -43,13 +43,12 @@
//////////////////////////////////////////
bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value) {
-
if (p_name == "argument_count") {
-
int new_argc = p_value;
int argc = arguments.size();
- if (argc == new_argc)
+ if (argc == new_argc) {
return true;
+ }
arguments.resize(new_argc);
@@ -66,7 +65,6 @@ bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value
ERR_FAIL_INDEX_V(idx, arguments.size(), false);
String what = String(p_name).get_slice("/", 1);
if (what == "type") {
-
Variant::Type new_type = Variant::Type(int(p_value));
arguments.write[idx].type = new_type;
ports_changed_notify();
@@ -75,7 +73,6 @@ bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value
}
if (what == "name") {
-
arguments.write[idx].name = p_value;
ports_changed_notify();
return true;
@@ -107,7 +104,6 @@ bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value
}
bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const {
-
if (p_name == "argument_count") {
r_ret = arguments.size();
return true;
@@ -148,8 +144,8 @@ bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const
return false;
}
-void VisualScriptFunction::_get_property_list(List<PropertyInfo> *p_list) const {
+void VisualScriptFunction::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::INT, "argument_count", PROPERTY_HINT_RANGE, "0,256"));
String argt = "Any";
for (int i = 1; i < Variant::VARIANT_MAX; i++) {
@@ -171,35 +167,30 @@ void VisualScriptFunction::_get_property_list(List<PropertyInfo> *p_list) const
}
int VisualScriptFunction::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptFunction::has_input_sequence_port() const {
-
return false;
}
int VisualScriptFunction::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptFunction::get_output_value_port_count() const {
+int VisualScriptFunction::get_output_value_port_count() const {
return arguments.size();
}
String VisualScriptFunction::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const {
-
ERR_FAIL_V(PropertyInfo());
}
-PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, arguments.size(), PropertyInfo());
PropertyInfo out;
out.type = arguments[p_idx].type;
@@ -210,55 +201,53 @@ PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const {
}
String VisualScriptFunction::get_caption() const {
-
return "Function";
}
String VisualScriptFunction::get_text() const {
-
return get_name(); //use name as function name I guess
}
void VisualScriptFunction::add_argument(Variant::Type p_type, const String &p_name, int p_index, const PropertyHint p_hint, const String &p_hint_string) {
-
Argument arg;
arg.name = p_name;
arg.type = p_type;
arg.hint = p_hint;
arg.hint_string = p_hint_string;
- if (p_index >= 0)
+ if (p_index >= 0) {
arguments.insert(p_index, arg);
- else
+ } else {
arguments.push_back(arg);
+ }
ports_changed_notify();
}
-void VisualScriptFunction::set_argument_type(int p_argidx, Variant::Type p_type) {
+void VisualScriptFunction::set_argument_type(int p_argidx, Variant::Type p_type) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments.write[p_argidx].type = p_type;
ports_changed_notify();
}
-Variant::Type VisualScriptFunction::get_argument_type(int p_argidx) const {
+Variant::Type VisualScriptFunction::get_argument_type(int p_argidx) const {
ERR_FAIL_INDEX_V(p_argidx, arguments.size(), Variant::NIL);
return arguments[p_argidx].type;
}
-void VisualScriptFunction::set_argument_name(int p_argidx, const String &p_name) {
+void VisualScriptFunction::set_argument_name(int p_argidx, const String &p_name) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments.write[p_argidx].name = p_name;
ports_changed_notify();
}
-String VisualScriptFunction::get_argument_name(int p_argidx) const {
+String VisualScriptFunction::get_argument_name(int p_argidx) const {
ERR_FAIL_INDEX_V(p_argidx, arguments.size(), String());
return arguments[p_argidx].name;
}
-void VisualScriptFunction::remove_argument(int p_argidx) {
+void VisualScriptFunction::remove_argument(int p_argidx) {
ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments.remove(p_argidx);
@@ -266,7 +255,6 @@ void VisualScriptFunction::remove_argument(int p_argidx) {
}
int VisualScriptFunction::get_argument_count() const {
-
return arguments.size();
}
@@ -286,7 +274,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
int ac = node->get_argument_count();
for (int i = 0; i < ac; i++) {
@@ -310,7 +297,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction);
instance->node = this;
instance->instance = p_instance;
@@ -318,7 +304,6 @@ VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p
}
VisualScriptFunction::VisualScriptFunction() {
-
stack_size = 256;
stack_less = false;
sequenced = true;
@@ -335,23 +320,19 @@ bool VisualScriptFunction::is_stack_less() const {
}
void VisualScriptFunction::set_sequenced(bool p_enable) {
-
sequenced = p_enable;
}
bool VisualScriptFunction::is_sequenced() const {
-
return sequenced;
}
void VisualScriptFunction::set_stack_size(int p_size) {
-
ERR_FAIL_COND(p_size < 1 || p_size > 100000);
stack_size = p_size;
}
int VisualScriptFunction::get_stack_size() const {
-
return stack_size;
}
@@ -360,10 +341,12 @@ int VisualScriptFunction::get_stack_size() const {
//////////////////////////////////////////
int VisualScriptLists::get_output_sequence_port_count() const {
- if (sequenced)
+ if (sequenced) {
return 1;
+ }
return 0;
}
+
bool VisualScriptLists::has_input_sequence_port() const {
return sequenced;
}
@@ -375,6 +358,7 @@ String VisualScriptLists::get_output_sequence_port_text(int p_port) const {
int VisualScriptLists::get_input_value_port_count() const {
return inputports.size();
}
+
int VisualScriptLists::get_output_value_port_count() const {
return outputports.size();
}
@@ -387,6 +371,7 @@ PropertyInfo VisualScriptLists::get_input_value_port_info(int p_idx) const {
pi.type = inputports[p_idx].type;
return pi;
}
+
PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, outputports.size(), PropertyInfo());
@@ -399,9 +384,11 @@ PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const {
bool VisualScriptLists::is_input_port_editable() const {
return ((flags & INPUT_EDITABLE) == INPUT_EDITABLE);
}
+
bool VisualScriptLists::is_input_port_name_editable() const {
return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
}
+
bool VisualScriptLists::is_input_port_type_editable() const {
return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
}
@@ -409,22 +396,23 @@ bool VisualScriptLists::is_input_port_type_editable() const {
bool VisualScriptLists::is_output_port_editable() const {
return ((flags & OUTPUT_EDITABLE) == OUTPUT_EDITABLE);
}
+
bool VisualScriptLists::is_output_port_name_editable() const {
return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE);
}
+
bool VisualScriptLists::is_output_port_type_editable() const {
return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE);
}
// for the inspector
bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
-
if (p_name == "input_count" && is_input_port_editable()) {
-
int new_argc = p_value;
int argc = inputports.size();
- if (argc == new_argc)
+ if (argc == new_argc) {
return true;
+ }
inputports.resize(new_argc);
@@ -441,7 +429,6 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
ERR_FAIL_INDEX_V(idx, inputports.size(), false);
String what = String(p_name).get_slice("/", 1);
if (what == "type") {
-
Variant::Type new_type = Variant::Type(int(p_value));
inputports.write[idx].type = new_type;
ports_changed_notify();
@@ -450,7 +437,6 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
}
if (what == "name") {
-
inputports.write[idx].name = p_value;
ports_changed_notify();
return true;
@@ -458,11 +444,11 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
}
if (p_name == "output_count" && is_output_port_editable()) {
-
int new_argc = p_value;
int argc = outputports.size();
- if (argc == new_argc)
+ if (argc == new_argc) {
return true;
+ }
outputports.resize(new_argc);
@@ -479,7 +465,6 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
ERR_FAIL_INDEX_V(idx, outputports.size(), false);
String what = String(p_name).get_slice("/", 1);
if (what == "type") {
-
Variant::Type new_type = Variant::Type(int(p_value));
outputports.write[idx].type = new_type;
ports_changed_notify();
@@ -488,7 +473,6 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
}
if (what == "name") {
-
outputports.write[idx].name = p_value;
ports_changed_notify();
return true;
@@ -503,8 +487,8 @@ bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) {
return false;
}
-bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const {
+bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name == "input_count" && is_input_port_editable()) {
r_ret = inputports.size();
return true;
@@ -548,8 +532,8 @@ bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const {
return false;
}
-void VisualScriptLists::_get_property_list(List<PropertyInfo> *p_list) const {
+void VisualScriptLists::_get_property_list(List<PropertyInfo> *p_list) const {
if (is_input_port_editable()) {
p_list->push_back(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,256"));
String argt = "Any";
@@ -580,25 +564,27 @@ void VisualScriptLists::_get_property_list(List<PropertyInfo> *p_list) const {
// input data port interaction
void VisualScriptLists::add_input_data_port(Variant::Type p_type, const String &p_name, int p_index) {
-
- if (!is_input_port_editable())
+ if (!is_input_port_editable()) {
return;
+ }
Port inp;
inp.name = p_name;
inp.type = p_type;
- if (p_index >= 0)
+ if (p_index >= 0) {
inputports.insert(p_index, inp);
- else
+ } else {
inputports.push_back(inp);
+ }
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::set_input_data_port_type(int p_idx, Variant::Type p_type) {
- if (!is_input_port_type_editable())
+void VisualScriptLists::set_input_data_port_type(int p_idx, Variant::Type p_type) {
+ if (!is_input_port_type_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_idx, inputports.size());
@@ -606,10 +592,11 @@ void VisualScriptLists::set_input_data_port_type(int p_idx, Variant::Type p_type
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::set_input_data_port_name(int p_idx, const String &p_name) {
- if (!is_input_port_name_editable())
+void VisualScriptLists::set_input_data_port_name(int p_idx, const String &p_name) {
+ if (!is_input_port_name_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_idx, inputports.size());
@@ -617,10 +604,11 @@ void VisualScriptLists::set_input_data_port_name(int p_idx, const String &p_name
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::remove_input_data_port(int p_argidx) {
- if (!is_input_port_editable())
+void VisualScriptLists::remove_input_data_port(int p_argidx) {
+ if (!is_input_port_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_argidx, inputports.size());
@@ -632,25 +620,27 @@ void VisualScriptLists::remove_input_data_port(int p_argidx) {
// output data port interaction
void VisualScriptLists::add_output_data_port(Variant::Type p_type, const String &p_name, int p_index) {
-
- if (!is_output_port_editable())
+ if (!is_output_port_editable()) {
return;
+ }
Port out;
out.name = p_name;
out.type = p_type;
- if (p_index >= 0)
+ if (p_index >= 0) {
outputports.insert(p_index, out);
- else
+ } else {
outputports.push_back(out);
+ }
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::set_output_data_port_type(int p_idx, Variant::Type p_type) {
- if (!is_output_port_type_editable())
+void VisualScriptLists::set_output_data_port_type(int p_idx, Variant::Type p_type) {
+ if (!is_output_port_type_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_idx, outputports.size());
@@ -658,10 +648,11 @@ void VisualScriptLists::set_output_data_port_type(int p_idx, Variant::Type p_typ
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::set_output_data_port_name(int p_idx, const String &p_name) {
- if (!is_output_port_name_editable())
+void VisualScriptLists::set_output_data_port_name(int p_idx, const String &p_name) {
+ if (!is_output_port_name_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_idx, outputports.size());
@@ -669,10 +660,11 @@ void VisualScriptLists::set_output_data_port_name(int p_idx, const String &p_nam
ports_changed_notify();
_change_notify();
}
-void VisualScriptLists::remove_output_data_port(int p_argidx) {
- if (!is_output_port_editable())
+void VisualScriptLists::remove_output_data_port(int p_argidx) {
+ if (!is_output_port_editable()) {
return;
+ }
ERR_FAIL_INDEX(p_argidx, outputports.size());
@@ -684,11 +676,13 @@ void VisualScriptLists::remove_output_data_port(int p_argidx) {
// sequences
void VisualScriptLists::set_sequenced(bool p_enable) {
- if (sequenced == p_enable)
+ if (sequenced == p_enable) {
return;
+ }
sequenced = p_enable;
ports_changed_notify();
}
+
bool VisualScriptLists::is_sequenced() const {
return sequenced;
}
@@ -716,10 +710,12 @@ void VisualScriptLists::_bind_methods() {
//////////////////////////////////////////
int VisualScriptComposeArray::get_output_sequence_port_count() const {
- if (sequenced)
+ if (sequenced) {
return 1;
+ }
return 0;
}
+
bool VisualScriptComposeArray::has_input_sequence_port() const {
return sequenced;
}
@@ -731,6 +727,7 @@ String VisualScriptComposeArray::get_output_sequence_port_text(int p_port) const
int VisualScriptComposeArray::get_input_value_port_count() const {
return inputports.size();
}
+
int VisualScriptComposeArray::get_output_value_port_count() const {
return 1;
}
@@ -743,6 +740,7 @@ PropertyInfo VisualScriptComposeArray::get_input_value_port_info(int p_idx) cons
pi.type = inputports[p_idx].type;
return pi;
}
+
PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) const {
PropertyInfo pi;
pi.name = "out";
@@ -753,6 +751,7 @@ PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) con
String VisualScriptComposeArray::get_caption() const {
return "Compose Array";
}
+
String VisualScriptComposeArray::get_text() const {
return "";
}
@@ -763,11 +762,11 @@ public:
virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (input_count > 0) {
Array arr;
- for (int i = 0; i < input_count; i++)
+ for (int i = 0; i < input_count; i++) {
arr.push_back((*p_inputs[i]));
+ }
Variant va = Variant(arr);
*p_outputs[0] = va;
@@ -778,7 +777,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptComposeArray::instance(VisualScriptInstance *p_instance) {
-
VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode);
instance->input_count = inputports.size();
return instance;
@@ -795,31 +793,26 @@ VisualScriptComposeArray::VisualScriptComposeArray() {
//////////////////////////////////////////
int VisualScriptOperator::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptOperator::has_input_sequence_port() const {
-
return false;
}
int VisualScriptOperator::get_input_value_port_count() const {
-
return (op == Variant::OP_BIT_NEGATE || op == Variant::OP_NOT || op == Variant::OP_NEGATE || op == Variant::OP_POSITIVE) ? 1 : 2;
}
-int VisualScriptOperator::get_output_value_port_count() const {
+int VisualScriptOperator::get_output_value_port_count() const {
return 1;
}
String VisualScriptOperator::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const {
-
static const Variant::Type port_types[Variant::OP_MAX][2] = {
{ Variant::NIL, Variant::NIL }, //OP_EQUAL,
{ Variant::NIL, Variant::NIL }, //OP_NOT_EQUAL,
@@ -835,7 +828,6 @@ PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const {
{ Variant::NIL, Variant::NIL }, //OP_NEGATE,
{ Variant::NIL, Variant::NIL }, //OP_POSITIVE,
{ Variant::INT, Variant::INT }, //OP_MODULE,
- { Variant::STRING, Variant::STRING }, //OP_STRING_CONCAT,
//bitwise
{ Variant::INT, Variant::INT }, //OP_SHIFT_LEFT,
{ Variant::INT, Variant::INT }, //OP_SHIFT_RIGHT,
@@ -857,10 +849,12 @@ PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = p_idx == 0 ? "A" : "B";
pinfo.type = port_types[op][p_idx];
- if (pinfo.type == Variant::NIL)
+ if (pinfo.type == Variant::NIL) {
pinfo.type = typed;
+ }
return pinfo;
}
+
PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
static const Variant::Type port_types[Variant::OP_MAX] = {
//comparison
@@ -878,7 +872,6 @@ PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
Variant::NIL, //OP_NEGATE,
Variant::NIL, //OP_POSITIVE,
Variant::INT, //OP_MODULE,
- Variant::STRING, //OP_STRING_CONCAT,
//bitwise
Variant::INT, //OP_SHIFT_LEFT,
Variant::INT, //OP_SHIFT_RIGHT,
@@ -898,8 +891,9 @@ PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
pinfo.name = "";
pinfo.type = port_types[op];
- if (pinfo.type == Variant::NIL)
+ if (pinfo.type == Variant::NIL) {
pinfo.type = typed;
+ }
return pinfo;
}
@@ -937,71 +931,67 @@ static const char *op_names[] = {
};
String VisualScriptOperator::get_caption() const {
-
- static const wchar_t *op_names[] = {
+ static const char32_t *op_names[] = {
//comparison
- L"A = B", //OP_EQUAL,
- L"A \u2260 B", //OP_NOT_EQUAL,
- L"A < B", //OP_LESS,
- L"A \u2264 B", //OP_LESS_EQUAL,
- L"A > B", //OP_GREATER,
- L"A \u2265 B", //OP_GREATER_EQUAL,
+ U"A = B", //OP_EQUAL,
+ U"A \u2260 B", //OP_NOT_EQUAL,
+ U"A < B", //OP_LESS,
+ U"A \u2264 B", //OP_LESS_EQUAL,
+ U"A > B", //OP_GREATER,
+ U"A \u2265 B", //OP_GREATER_EQUAL,
//mathematic
- L"A + B", //OP_ADD,
- L"A - B", //OP_SUBTRACT,
- L"A \u00D7 B", //OP_MULTIPLY,
- L"A \u00F7 B", //OP_DIVIDE,
- L"\u00AC A", //OP_NEGATE,
- L"+ A", //OP_POSITIVE,
- L"A mod B", //OP_MODULE,
- L"A .. B", //OP_STRING_CONCAT,
+ U"A + B", //OP_ADD,
+ U"A - B", //OP_SUBTRACT,
+ U"A \u00D7 B", //OP_MULTIPLY,
+ U"A \u00F7 B", //OP_DIVIDE,
+ U"\u00AC A", //OP_NEGATE,
+ U"+ A", //OP_POSITIVE,
+ U"A mod B", //OP_MODULE,
+ U"A .. B", //OP_STRING_CONCAT,
//bitwise
- L"A << B", //OP_SHIFT_LEFT,
- L"A >> B", //OP_SHIFT_RIGHT,
- L"A & B", //OP_BIT_AND,
- L"A | B", //OP_BIT_OR,
- L"A ^ B", //OP_BIT_XOR,
- L"~A", //OP_BIT_NEGATE,
+ U"A << B", //OP_SHIFT_LEFT,
+ U"A >> B", //OP_SHIFT_RIGHT,
+ U"A & B", //OP_BIT_AND,
+ U"A | B", //OP_BIT_OR,
+ U"A ^ B", //OP_BIT_XOR,
+ U"~A", //OP_BIT_NEGATE,
//logic
- L"A and B", //OP_AND,
- L"A or B", //OP_OR,
- L"A xor B", //OP_XOR,
- L"not A", //OP_NOT,
- L"A in B", //OP_IN,
+ U"A and B", //OP_AND,
+ U"A or B", //OP_OR,
+ U"A xor B", //OP_XOR,
+ U"not A", //OP_NOT,
+ U"A in B", //OP_IN,
};
return op_names[op];
}
void VisualScriptOperator::set_operator(Variant::Operator p_op) {
-
- if (op == p_op)
+ if (op == p_op) {
return;
+ }
op = p_op;
ports_changed_notify();
}
Variant::Operator VisualScriptOperator::get_operator() const {
-
return op;
}
void VisualScriptOperator::set_typed(Variant::Type p_op) {
-
- if (typed == p_op)
+ if (typed == p_op) {
return;
+ }
typed = p_op;
ports_changed_notify();
}
Variant::Type VisualScriptOperator::get_typed() const {
-
return typed;
}
void VisualScriptOperator::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualScriptOperator::set_operator);
ClassDB::bind_method(D_METHOD("get_operator"), &VisualScriptOperator::get_operator);
@@ -1010,8 +1000,9 @@ void VisualScriptOperator::_bind_methods() {
String types;
for (int i = 0; i < Variant::OP_MAX; i++) {
- if (i > 0)
+ if (i > 0) {
types += ",";
+ }
types += op_names[i];
}
@@ -1032,25 +1023,23 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
bool valid;
if (unary) {
-
Variant::evaluate(op, *p_inputs[0], Variant(), *p_outputs[0], valid);
} else {
Variant::evaluate(op, *p_inputs[0], *p_inputs[1], *p_outputs[0], valid);
}
if (!valid) {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
if (p_outputs[0]->get_type() == Variant::STRING) {
r_error_str = *p_outputs[0];
} else {
- if (unary)
+ if (unary) {
r_error_str = String(op_names[op]) + RTR(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type());
- else
+ } else {
r_error_str = String(op_names[op]) + RTR(": Invalid arguments: ") + "A: " + Variant::get_type_name(p_inputs[0]->get_type()) + " B: " + Variant::get_type_name(p_inputs[1]->get_type());
+ }
}
}
@@ -1059,7 +1048,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator);
instance->unary = get_input_value_port_count() == 1;
instance->op = op;
@@ -1067,14 +1055,12 @@ VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p
}
VisualScriptOperator::VisualScriptOperator() {
-
op = Variant::OP_ADD;
typed = Variant::NIL;
}
template <Variant::Operator OP>
static Ref<VisualScriptNode> create_op_node(const String &p_name) {
-
Ref<VisualScriptOperator> node;
node.instance();
node->set_operator(OP);
@@ -1086,31 +1072,26 @@ static Ref<VisualScriptNode> create_op_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptSelect::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptSelect::has_input_sequence_port() const {
-
return false;
}
int VisualScriptSelect::get_input_value_port_count() const {
-
return 3;
}
-int VisualScriptSelect::get_output_value_port_count() const {
+int VisualScriptSelect::get_output_value_port_count() const {
return 1;
}
String VisualScriptSelect::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptSelect::get_input_value_port_info(int p_idx) const {
-
if (p_idx == 0) {
return PropertyInfo(Variant::BOOL, "cond");
} else if (p_idx == 1) {
@@ -1119,37 +1100,33 @@ PropertyInfo VisualScriptSelect::get_input_value_port_info(int p_idx) const {
return PropertyInfo(typed, "b");
}
}
-PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const {
return PropertyInfo(typed, "out");
}
String VisualScriptSelect::get_caption() const {
-
return "Select";
}
String VisualScriptSelect::get_text() const {
-
return "a if cond, else b";
}
void VisualScriptSelect::set_typed(Variant::Type p_op) {
-
- if (typed == p_op)
+ if (typed == p_op) {
return;
+ }
typed = p_op;
ports_changed_notify();
}
Variant::Type VisualScriptSelect::get_typed() const {
-
return typed;
}
void VisualScriptSelect::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_typed", "type"), &VisualScriptSelect::set_typed);
ClassDB::bind_method(D_METHOD("get_typed"), &VisualScriptSelect::get_typed);
@@ -1166,25 +1143,23 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
bool cond = *p_inputs[0];
- if (cond)
+ if (cond) {
*p_outputs[0] = *p_inputs[1];
- else
+ } else {
*p_outputs[0] = *p_inputs[2];
+ }
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSelect::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSelect *instance = memnew(VisualScriptNodeInstanceSelect);
return instance;
}
VisualScriptSelect::VisualScriptSelect() {
-
typed = Variant::NIL;
}
@@ -1193,36 +1168,30 @@ VisualScriptSelect::VisualScriptSelect() {
//////////////////////////////////////////
int VisualScriptVariableGet::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptVariableGet::has_input_sequence_port() const {
-
return false;
}
int VisualScriptVariableGet::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptVariableGet::get_output_value_port_count() const {
+int VisualScriptVariableGet::get_output_value_port_count() const {
return 1;
}
String VisualScriptVariableGet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptVariableGet::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "value";
if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
@@ -1235,24 +1204,22 @@ PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) cons
}
String VisualScriptVariableGet::get_caption() const {
-
return "Get " + variable;
}
-void VisualScriptVariableGet::set_variable(StringName p_variable) {
- if (variable == p_variable)
+void VisualScriptVariableGet::set_variable(StringName p_variable) {
+ if (variable == p_variable) {
return;
+ }
variable = p_variable;
ports_changed_notify();
}
StringName VisualScriptVariableGet::get_variable() const {
-
return variable;
}
void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
-
if (property.name == "var_name" && get_visual_script().is_valid()) {
Ref<VisualScript> vs = get_visual_script();
List<StringName> vars;
@@ -1260,8 +1227,9 @@ void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
String vhint;
for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
- if (vhint != String())
+ if (vhint != String()) {
vhint += ",";
+ }
vhint += E->get().operator String();
}
@@ -1272,7 +1240,6 @@ void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
}
void VisualScriptVariableGet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableGet::set_variable);
ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableGet::get_variable);
@@ -1286,7 +1253,6 @@ public:
StringName variable;
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!instance->get_variable(variable, p_outputs[0])) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = RTR("VariableGet not found in script: ") + "'" + String(variable) + "'";
@@ -1297,13 +1263,13 @@ public:
};
VisualScriptNodeInstance *VisualScriptVariableGet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet);
instance->node = this;
instance->instance = p_instance;
instance->variable = variable;
return instance;
}
+
VisualScriptVariableGet::VisualScriptVariableGet() {
}
@@ -1312,31 +1278,26 @@ VisualScriptVariableGet::VisualScriptVariableGet() {
//////////////////////////////////////////
int VisualScriptVariableSet::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptVariableSet::has_input_sequence_port() const {
-
return true;
}
int VisualScriptVariableSet::get_input_value_port_count() const {
-
return 1;
}
-int VisualScriptVariableSet::get_output_value_port_count() const {
+int VisualScriptVariableSet::get_output_value_port_count() const {
return 0;
}
String VisualScriptVariableSet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptVariableSet::get_input_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = "set";
if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
@@ -1349,30 +1310,26 @@ PropertyInfo VisualScriptVariableSet::get_input_value_port_info(int p_idx) const
}
PropertyInfo VisualScriptVariableSet::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptVariableSet::get_caption() const {
-
return "Set " + variable;
}
void VisualScriptVariableSet::set_variable(StringName p_variable) {
-
- if (variable == p_variable)
+ if (variable == p_variable) {
return;
+ }
variable = p_variable;
ports_changed_notify();
}
StringName VisualScriptVariableSet::get_variable() const {
-
return variable;
}
void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
-
if (property.name == "var_name" && get_visual_script().is_valid()) {
Ref<VisualScript> vs = get_visual_script();
List<StringName> vars;
@@ -1380,8 +1337,9 @@ void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
String vhint;
for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
- if (vhint != String())
+ if (vhint != String()) {
vhint += ",";
+ }
vhint += E->get().operator String();
}
@@ -1392,7 +1350,6 @@ void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
}
void VisualScriptVariableSet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableSet::set_variable);
ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableSet::get_variable);
@@ -1408,9 +1365,7 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!instance->set_variable(variable, *p_inputs[0])) {
-
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_error_str = RTR("VariableSet not found in script: ") + "'" + String(variable) + "'";
}
@@ -1420,13 +1375,13 @@ public:
};
VisualScriptNodeInstance *VisualScriptVariableSet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet);
instance->node = this;
instance->instance = p_instance;
instance->variable = variable;
return instance;
}
+
VisualScriptVariableSet::VisualScriptVariableSet() {
}
@@ -1435,36 +1390,30 @@ VisualScriptVariableSet::VisualScriptVariableSet() {
//////////////////////////////////////////
int VisualScriptConstant::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptConstant::has_input_sequence_port() const {
-
return false;
}
int VisualScriptConstant::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptConstant::get_output_value_port_count() const {
+int VisualScriptConstant::get_output_value_port_count() const {
return 1;
}
String VisualScriptConstant::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptConstant::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.name = String(value);
pinfo.type = type;
@@ -1472,51 +1421,48 @@ PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const {
}
String VisualScriptConstant::get_caption() const {
-
return "Constant";
}
void VisualScriptConstant::set_constant_type(Variant::Type p_type) {
-
- if (type == p_type)
+ if (type == p_type) {
return;
+ }
type = p_type;
Callable::CallError ce;
- value = Variant::construct(type, nullptr, 0, ce);
+ Variant::construct(type, value, nullptr, 0, ce);
ports_changed_notify();
_change_notify();
}
Variant::Type VisualScriptConstant::get_constant_type() const {
-
return type;
}
void VisualScriptConstant::set_constant_value(Variant p_value) {
-
- if (value == p_value)
+ if (value == p_value) {
return;
+ }
value = p_value;
ports_changed_notify();
}
-Variant VisualScriptConstant::get_constant_value() const {
+Variant VisualScriptConstant::get_constant_value() const {
return value;
}
void VisualScriptConstant::_validate_property(PropertyInfo &property) const {
-
if (property.name == "value") {
property.type = type;
- if (type == Variant::NIL)
+ if (type == Variant::NIL) {
property.usage = 0; //do not save if nil
+ }
}
}
void VisualScriptConstant::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_constant_type", "type"), &VisualScriptConstant::set_constant_type);
ClassDB::bind_method(D_METHOD("get_constant_type"), &VisualScriptConstant::get_constant_type);
@@ -1538,21 +1484,18 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = constant;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptConstant::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant);
instance->constant = value;
return instance;
}
VisualScriptConstant::VisualScriptConstant() {
-
type = Variant::NIL;
}
@@ -1561,36 +1504,30 @@ VisualScriptConstant::VisualScriptConstant() {
//////////////////////////////////////////
int VisualScriptPreload::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptPreload::has_input_sequence_port() const {
-
return false;
}
int VisualScriptPreload::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptPreload::get_output_value_port_count() const {
+int VisualScriptPreload::get_output_value_port_count() const {
return 1;
}
String VisualScriptPreload::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptPreload::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const {
-
PropertyInfo pinfo;
pinfo.type = Variant::OBJECT;
if (preload.is_valid()) {
@@ -1611,26 +1548,23 @@ PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const {
}
String VisualScriptPreload::get_caption() const {
-
return "Preload";
}
void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) {
-
- if (preload == p_preload)
+ if (preload == p_preload) {
return;
+ }
preload = p_preload;
ports_changed_notify();
}
Ref<Resource> VisualScriptPreload::get_preload() const {
-
return preload;
}
void VisualScriptPreload::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_preload", "resource"), &VisualScriptPreload::set_preload);
ClassDB::bind_method(D_METHOD("get_preload"), &VisualScriptPreload::get_preload);
@@ -1643,14 +1577,12 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = preload;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptPreload::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload);
instance->preload = preload;
return instance;
@@ -1664,31 +1596,26 @@ VisualScriptPreload::VisualScriptPreload() {
//////////////////////////////////////////
int VisualScriptIndexGet::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptIndexGet::has_input_sequence_port() const {
-
return false;
}
int VisualScriptIndexGet::get_input_value_port_count() const {
-
return 2;
}
-int VisualScriptIndexGet::get_output_value_port_count() const {
+int VisualScriptIndexGet::get_output_value_port_count() const {
return 1;
}
String VisualScriptIndexGet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const {
-
if (p_idx == 0) {
return PropertyInfo(Variant::NIL, "base");
} else {
@@ -1697,12 +1624,10 @@ PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const {
}
PropertyInfo VisualScriptIndexGet::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptIndexGet::get_caption() const {
-
return "Get Index";
}
@@ -1711,7 +1636,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
bool valid;
*p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid);
@@ -1724,10 +1648,10 @@ public:
};
VisualScriptNodeInstance *VisualScriptIndexGet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet);
return instance;
}
+
VisualScriptIndexGet::VisualScriptIndexGet() {
}
@@ -1736,31 +1660,26 @@ VisualScriptIndexGet::VisualScriptIndexGet() {
//////////////////////////////////////////
int VisualScriptIndexSet::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptIndexSet::has_input_sequence_port() const {
-
return true;
}
int VisualScriptIndexSet::get_input_value_port_count() const {
-
return 3;
}
-int VisualScriptIndexSet::get_output_value_port_count() const {
+int VisualScriptIndexSet::get_output_value_port_count() const {
return 0;
}
String VisualScriptIndexSet::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const {
-
if (p_idx == 0) {
return PropertyInfo(Variant::NIL, "base");
} else if (p_idx == 1) {
@@ -1772,12 +1691,10 @@ PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const {
}
PropertyInfo VisualScriptIndexSet::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptIndexSet::get_caption() const {
-
return "Set Index";
}
@@ -1786,10 +1703,11 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
bool valid;
+ // *p_output[0] points to the same place as *p_inputs[2] so we need a temp to store the value before the change in the next line
+ Variant temp = *p_inputs[2];
*p_outputs[0] = *p_inputs[0];
- p_outputs[0]->set(*p_inputs[1], *p_inputs[2], &valid);
+ p_outputs[0]->set(*p_inputs[1], temp, &valid);
if (!valid) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -1800,10 +1718,10 @@ public:
};
VisualScriptNodeInstance *VisualScriptIndexSet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet);
return instance;
}
+
VisualScriptIndexSet::VisualScriptIndexSet() {
}
@@ -1812,46 +1730,39 @@ VisualScriptIndexSet::VisualScriptIndexSet() {
//////////////////////////////////////////
int VisualScriptGlobalConstant::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptGlobalConstant::has_input_sequence_port() const {
-
return false;
}
int VisualScriptGlobalConstant::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptGlobalConstant::get_output_value_port_count() const {
+int VisualScriptGlobalConstant::get_output_value_port_count() const {
return 1;
}
String VisualScriptGlobalConstant::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const {
- String name = GlobalConstants::get_global_constant_name(index);
+ String name = CoreConstants::get_global_constant_name(index);
return PropertyInfo(Variant::INT, name);
}
String VisualScriptGlobalConstant::get_caption() const {
-
return "Global Constant";
}
void VisualScriptGlobalConstant::set_global_constant(int p_which) {
-
index = p_which;
_change_notify();
ports_changed_notify();
@@ -1867,37 +1778,33 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
- *p_outputs[0] = GlobalConstants::get_global_constant_value(index);
+ *p_outputs[0] = CoreConstants::get_global_constant_value(index);
return 0;
}
};
VisualScriptNodeInstance *VisualScriptGlobalConstant::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceGlobalConstant *instance = memnew(VisualScriptNodeInstanceGlobalConstant);
instance->index = index;
return instance;
}
void VisualScriptGlobalConstant::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_global_constant", "index"), &VisualScriptGlobalConstant::set_global_constant);
ClassDB::bind_method(D_METHOD("get_global_constant"), &VisualScriptGlobalConstant::get_global_constant);
String cc;
- for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
-
- if (i > 0)
+ for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
+ if (i > 0) {
cc += ",";
- cc += GlobalConstants::get_global_constant_name(i);
+ }
+ cc += CoreConstants::get_global_constant_name(i);
}
ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_global_constant", "get_global_constant");
}
VisualScriptGlobalConstant::VisualScriptGlobalConstant() {
-
index = 0;
}
@@ -1906,31 +1813,26 @@ VisualScriptGlobalConstant::VisualScriptGlobalConstant() {
//////////////////////////////////////////
int VisualScriptClassConstant::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptClassConstant::has_input_sequence_port() const {
-
return false;
}
int VisualScriptClassConstant::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptClassConstant::get_output_value_port_count() const {
+int VisualScriptClassConstant::get_output_value_port_count() const {
return 1;
}
String VisualScriptClassConstant::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
@@ -1943,12 +1845,10 @@ PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) co
}
String VisualScriptClassConstant::get_caption() const {
-
return "Class Constant";
}
void VisualScriptClassConstant::set_class_constant(const StringName &p_which) {
-
name = p_which;
_change_notify();
ports_changed_notify();
@@ -1959,7 +1859,6 @@ StringName VisualScriptClassConstant::get_class_constant() {
}
void VisualScriptClassConstant::set_base_type(const StringName &p_which) {
-
base_type = p_which;
List<String> constants;
ClassDB::get_integer_constant_list(base_type, &constants, true);
@@ -1992,7 +1891,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!valid) {
r_error_str = "Invalid constant name, pick a valid class constant.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -2004,16 +1902,13 @@ public:
};
VisualScriptNodeInstance *VisualScriptClassConstant::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant);
instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid);
return instance;
}
void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const {
-
if (property.name == "constant") {
-
List<String> constants;
ClassDB::get_integer_constant_list(base_type, &constants, true);
@@ -2028,7 +1923,6 @@ void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const
}
void VisualScriptClassConstant::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_class_constant", "name"), &VisualScriptClassConstant::set_class_constant);
ClassDB::bind_method(D_METHOD("get_class_constant"), &VisualScriptClassConstant::get_class_constant);
@@ -2040,7 +1934,6 @@ void VisualScriptClassConstant::_bind_methods() {
}
VisualScriptClassConstant::VisualScriptClassConstant() {
-
base_type = "Object";
}
@@ -2049,41 +1942,34 @@ VisualScriptClassConstant::VisualScriptClassConstant() {
//////////////////////////////////////////
int VisualScriptBasicTypeConstant::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptBasicTypeConstant::has_input_sequence_port() const {
-
return false;
}
int VisualScriptBasicTypeConstant::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptBasicTypeConstant::get_output_value_port_count() const {
+int VisualScriptBasicTypeConstant::get_output_value_port_count() const {
return 1;
}
String VisualScriptBasicTypeConstant::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(type, "value");
}
String VisualScriptBasicTypeConstant::get_caption() const {
-
return "Basic Constant";
}
@@ -2096,7 +1982,6 @@ String VisualScriptBasicTypeConstant::get_text() const {
}
void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName &p_which) {
-
name = p_which;
_change_notify();
ports_changed_notify();
@@ -2107,7 +1992,6 @@ StringName VisualScriptBasicTypeConstant::get_basic_type_constant() const {
}
void VisualScriptBasicTypeConstant::set_basic_type(Variant::Type p_which) {
-
type = p_which;
List<StringName> constants;
@@ -2141,7 +2025,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!valid) {
r_error_str = "Invalid constant name, pick a valid basic type constant.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -2153,16 +2036,13 @@ public:
};
VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant);
instance->value = Variant::get_constant_value(type, name, &instance->valid);
return instance;
}
void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) const {
-
if (property.name == "constant") {
-
List<StringName> constants;
Variant::get_constants_for_type(type, &constants);
@@ -2181,7 +2061,6 @@ void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) c
}
void VisualScriptBasicTypeConstant::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_basic_type", "name"), &VisualScriptBasicTypeConstant::set_basic_type);
ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptBasicTypeConstant::get_basic_type);
@@ -2198,7 +2077,6 @@ void VisualScriptBasicTypeConstant::_bind_methods() {
}
VisualScriptBasicTypeConstant::VisualScriptBasicTypeConstant() {
-
type = Variant::NIL;
}
@@ -2229,46 +2107,38 @@ double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = {
};
int VisualScriptMathConstant::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptMathConstant::has_input_sequence_port() const {
-
return false;
}
int VisualScriptMathConstant::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptMathConstant::get_output_value_port_count() const {
+int VisualScriptMathConstant::get_output_value_port_count() const {
return 1;
}
String VisualScriptMathConstant::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::FLOAT, const_name[constant]);
}
String VisualScriptMathConstant::get_caption() const {
-
return "Math Constant";
}
void VisualScriptMathConstant::set_math_constant(MathConstant p_which) {
-
constant = p_which;
_change_notify();
ports_changed_notify();
@@ -2284,30 +2154,27 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = value;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptMathConstant::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceMathConstant *instance = memnew(VisualScriptNodeInstanceMathConstant);
instance->value = const_value[constant];
return instance;
}
void VisualScriptMathConstant::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_math_constant", "which"), &VisualScriptMathConstant::set_math_constant);
ClassDB::bind_method(D_METHOD("get_math_constant"), &VisualScriptMathConstant::get_math_constant);
String cc;
for (int i = 0; i < MATH_CONSTANT_MAX; i++) {
-
- if (i > 0)
+ if (i > 0) {
cc += ",";
+ }
cc += const_name[i];
}
ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_math_constant", "get_math_constant");
@@ -2324,7 +2191,6 @@ void VisualScriptMathConstant::_bind_methods() {
}
VisualScriptMathConstant::VisualScriptMathConstant() {
-
constant = MATH_CONSTANT_ONE;
}
@@ -2333,46 +2199,38 @@ VisualScriptMathConstant::VisualScriptMathConstant() {
//////////////////////////////////////////
int VisualScriptEngineSingleton::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptEngineSingleton::has_input_sequence_port() const {
-
return false;
}
int VisualScriptEngineSingleton::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptEngineSingleton::get_output_value_port_count() const {
+int VisualScriptEngineSingleton::get_output_value_port_count() const {
return 1;
}
String VisualScriptEngineSingleton::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::OBJECT, singleton);
}
String VisualScriptEngineSingleton::get_caption() const {
-
return "Get Engine Singleton";
}
void VisualScriptEngineSingleton::set_singleton(const String &p_string) {
-
singleton = p_string;
_change_notify();
@@ -2390,21 +2248,18 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = singleton;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptEngineSingleton::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton);
instance->singleton = Engine::get_singleton()->get_singleton_object(singleton);
return instance;
}
VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
Object *obj = Engine::get_singleton()->get_singleton_object(singleton);
TypeGuess tg;
tg.type = Variant::OBJECT;
@@ -2417,7 +2272,6 @@ VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output
}
void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) const {
-
String cc;
List<Engine::Singleton> singletons;
@@ -2425,11 +2279,13 @@ void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) con
Engine::get_singleton()->get_singletons(&singletons);
for (List<Engine::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
- if (E->get().name == "VS" || E->get().name == "PS" || E->get().name == "PS2D" || E->get().name == "AS" || E->get().name == "TS" || E->get().name == "SS" || E->get().name == "SS2D")
+ if (E->get().name == "VS" || E->get().name == "PS" || E->get().name == "PS2D" || E->get().name == "AS" || E->get().name == "TS" || E->get().name == "SS" || E->get().name == "SS2D") {
continue; //skip these, too simple named
+ }
- if (cc != String())
+ if (cc != String()) {
cc += ",";
+ }
cc += E->get().name;
}
@@ -2438,7 +2294,6 @@ void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) con
}
void VisualScriptEngineSingleton::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_singleton", "name"), &VisualScriptEngineSingleton::set_singleton);
ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptEngineSingleton::get_singleton);
@@ -2446,7 +2301,6 @@ void VisualScriptEngineSingleton::_bind_methods() {
}
VisualScriptEngineSingleton::VisualScriptEngineSingleton() {
-
singleton = String();
}
@@ -2455,46 +2309,38 @@ VisualScriptEngineSingleton::VisualScriptEngineSingleton() {
//////////////////////////////////////////
int VisualScriptSceneNode::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptSceneNode::has_input_sequence_port() const {
-
return false;
}
int VisualScriptSceneNode::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptSceneNode::get_output_value_port_count() const {
+int VisualScriptSceneNode::get_output_value_port_count() const {
return 1;
}
String VisualScriptSceneNode::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::OBJECT, path.simplified());
}
String VisualScriptSceneNode::get_caption() const {
-
return "Get Scene Node";
}
void VisualScriptSceneNode::set_node_path(const NodePath &p_path) {
-
path = p_path;
_change_notify();
ports_changed_notify();
@@ -2513,7 +2359,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -2535,7 +2380,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode);
instance->node = this;
instance->instance = p_instance;
@@ -2546,19 +2390,21 @@ VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *
#ifdef TOOLS_ENABLED
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
-
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene)
+ if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
return nullptr;
+ }
Ref<Script> scr = p_current_node->get_script();
- if (scr.is_valid() && scr == script)
+ if (scr.is_valid() && scr == script) {
return p_current_node;
+ }
for (int i = 0; i < p_current_node->get_child_count(); i++) {
Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n)
+ if (n) {
return n;
+ }
}
return nullptr;
@@ -2567,31 +2413,34 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const
#endif
VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
VisualScriptSceneNode::TypeGuess tg;
tg.type = Variant::OBJECT;
tg.gdclass = "Node";
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return tg;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return tg;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return tg;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return tg;
+ }
Node *another = script_node->get_node(path);
@@ -2604,29 +2453,31 @@ VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGu
}
void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const {
-
#ifdef TOOLS_ENABLED
if (property.name == "node_path") {
-
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return;
+ }
property.hint_string = script_node->get_path();
}
@@ -2634,7 +2485,6 @@ void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const {
}
void VisualScriptSceneNode::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_node_path", "path"), &VisualScriptSceneNode::set_node_path);
ClassDB::bind_method(D_METHOD("get_node_path"), &VisualScriptSceneNode::get_node_path);
@@ -2642,7 +2492,6 @@ void VisualScriptSceneNode::_bind_methods() {
}
VisualScriptSceneNode::VisualScriptSceneNode() {
-
path = String(".");
}
@@ -2651,41 +2500,34 @@ VisualScriptSceneNode::VisualScriptSceneNode() {
//////////////////////////////////////////
int VisualScriptSceneTree::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptSceneTree::has_input_sequence_port() const {
-
return false;
}
int VisualScriptSceneTree::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptSceneTree::get_output_value_port_count() const {
+int VisualScriptSceneTree::get_output_value_port_count() const {
return 1;
}
String VisualScriptSceneTree::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::OBJECT, "Scene Tree", PROPERTY_HINT_TYPE_STRING, "SceneTree");
}
String VisualScriptSceneTree::get_caption() const {
-
return "Get Scene Tree";
}
@@ -2697,7 +2539,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -2719,7 +2560,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree);
instance->node = this;
instance->instance = p_instance;
@@ -2727,7 +2567,6 @@ VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *
}
VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
TypeGuess tg;
tg.type = Variant::OBJECT;
tg.gdclass = "SceneTree";
@@ -2748,46 +2587,38 @@ VisualScriptSceneTree::VisualScriptSceneTree() {
//////////////////////////////////////////
int VisualScriptResourcePath::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptResourcePath::has_input_sequence_port() const {
-
return false;
}
int VisualScriptResourcePath::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptResourcePath::get_output_value_port_count() const {
+int VisualScriptResourcePath::get_output_value_port_count() const {
return 1;
}
String VisualScriptResourcePath::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(Variant::STRING, path);
}
String VisualScriptResourcePath::get_caption() const {
-
return "Resource Path";
}
void VisualScriptResourcePath::set_resource_path(const String &p_path) {
-
path = p_path;
_change_notify();
ports_changed_notify();
@@ -2804,21 +2635,18 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = path;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptResourcePath::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceResourcePath *instance = memnew(VisualScriptNodeInstanceResourcePath);
instance->path = path;
return instance;
}
void VisualScriptResourcePath::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_resource_path", "path"), &VisualScriptResourcePath::set_resource_path);
ClassDB::bind_method(D_METHOD("get_resource_path"), &VisualScriptResourcePath::get_resource_path);
@@ -2826,7 +2654,6 @@ void VisualScriptResourcePath::_bind_methods() {
}
VisualScriptResourcePath::VisualScriptResourcePath() {
-
path = "";
}
@@ -2835,47 +2662,41 @@ VisualScriptResourcePath::VisualScriptResourcePath() {
//////////////////////////////////////////
int VisualScriptSelf::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptSelf::has_input_sequence_port() const {
-
return false;
}
int VisualScriptSelf::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptSelf::get_output_value_port_count() const {
+int VisualScriptSelf::get_output_value_port_count() const {
return 1;
}
String VisualScriptSelf::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const {
-
String type_name;
- if (get_visual_script().is_valid())
+ if (get_visual_script().is_valid()) {
type_name = get_visual_script()->get_instance_base_type();
- else
+ } else {
type_name = "instance";
+ }
return PropertyInfo(Variant::OBJECT, type_name);
}
String VisualScriptSelf::get_caption() const {
-
return "Get Self";
}
@@ -2886,28 +2707,26 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = instance->get_owner_ptr();
return 0;
}
};
VisualScriptNodeInstance *VisualScriptSelf::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSelf *instance = memnew(VisualScriptNodeInstanceSelf);
instance->instance = p_instance;
return instance;
}
VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
VisualScriptSceneNode::TypeGuess tg;
tg.type = Variant::OBJECT;
tg.gdclass = "Object";
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return tg;
+ }
tg.gdclass = script->get_instance_base_type();
tg.script = script;
@@ -2926,7 +2745,6 @@ VisualScriptSelf::VisualScriptSelf() {
//////////////////////////////////////////
int VisualScriptCustomNode::get_output_sequence_port_count() const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_count")) {
return get_script_instance()->call("_get_output_sequence_port_count");
}
@@ -2934,7 +2752,6 @@ int VisualScriptCustomNode::get_output_sequence_port_count() const {
}
bool VisualScriptCustomNode::has_input_sequence_port() const {
-
if (get_script_instance() && get_script_instance()->has_method("_has_input_sequence_port")) {
return get_script_instance()->call("_has_input_sequence_port");
}
@@ -2942,14 +2759,13 @@ bool VisualScriptCustomNode::has_input_sequence_port() const {
}
int VisualScriptCustomNode::get_input_value_port_count() const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_count")) {
return get_script_instance()->call("_get_input_value_port_count");
}
return 0;
}
-int VisualScriptCustomNode::get_output_value_port_count() const {
+int VisualScriptCustomNode::get_output_value_port_count() const {
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_count")) {
return get_script_instance()->call("_get_output_value_port_count");
}
@@ -2957,7 +2773,6 @@ int VisualScriptCustomNode::get_output_value_port_count() const {
}
String VisualScriptCustomNode::get_output_sequence_port_text(int p_port) const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_text")) {
return get_script_instance()->call("_get_output_sequence_port_text", p_port);
}
@@ -2966,7 +2781,6 @@ String VisualScriptCustomNode::get_output_sequence_port_text(int p_port) const {
}
PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const {
-
PropertyInfo info;
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_type")) {
info.type = Variant::Type(int(get_script_instance()->call("_get_input_value_port_type", p_idx)));
@@ -2978,7 +2792,6 @@ PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const
}
PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const {
-
PropertyInfo info;
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_type")) {
info.type = Variant::Type(int(get_script_instance()->call("_get_output_value_port_type", p_idx)));
@@ -2990,7 +2803,6 @@ PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const
}
String VisualScriptCustomNode::get_caption() const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_caption")) {
return get_script_instance()->call("_get_caption");
}
@@ -2998,7 +2810,6 @@ String VisualScriptCustomNode::get_caption() const {
}
String VisualScriptCustomNode::get_text() const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_text")) {
return get_script_instance()->call("_get_text");
}
@@ -3006,7 +2817,6 @@ String VisualScriptCustomNode::get_text() const {
}
String VisualScriptCustomNode::get_category() const {
-
if (get_script_instance() && get_script_instance()->has_method("_get_category")) {
return get_script_instance()->call("_get_category");
}
@@ -3023,7 +2833,6 @@ public:
virtual int get_working_memory_size() const { return work_mem_size; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (node->get_script_instance()) {
#ifdef DEBUG_ENABLED
if (!node->get_script_instance()->has_method(VisualScriptLanguage::singleton->_step)) {
@@ -3085,7 +2894,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode);
instance->instance = p_instance;
instance->node = this;
@@ -3106,7 +2914,6 @@ void VisualScriptCustomNode::_script_changed() {
}
void VisualScriptCustomNode::_bind_methods() {
-
BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_sequence_port_count"));
BIND_VMETHOD(MethodInfo(Variant::BOOL, "_has_input_sequence_port"));
@@ -3150,42 +2957,35 @@ VisualScriptCustomNode::VisualScriptCustomNode() {
//////////////////////////////////////////
int VisualScriptSubCall::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptSubCall::has_input_sequence_port() const {
-
return true;
}
int VisualScriptSubCall::get_input_value_port_count() const {
-
Ref<Script> script = get_script();
if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
-
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
return mi.arguments.size();
}
return 0;
}
-int VisualScriptSubCall::get_output_value_port_count() const {
+int VisualScriptSubCall::get_output_value_port_count() const {
return 1;
}
String VisualScriptSubCall::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const {
-
Ref<Script> script = get_script();
if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
-
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
return mi.arguments[p_idx];
}
@@ -3194,7 +2994,6 @@ PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const {
}
PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const {
-
Ref<Script> script = get_script();
if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall);
@@ -3204,25 +3003,24 @@ PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const {
}
String VisualScriptSubCall::get_caption() const {
-
return "SubCall";
}
String VisualScriptSubCall::get_text() const {
-
Ref<Script> script = get_script();
if (script.is_valid()) {
- if (script->get_name() != String())
+ if (script->get_name() != String()) {
return script->get_name();
- if (script->get_path().is_resource_file())
+ }
+ if (script->get_path().is_resource_file()) {
return script->get_path().get_file();
+ }
return script->get_class();
}
return "";
}
String VisualScriptSubCall::get_category() const {
-
return "custom";
}
@@ -3236,7 +3034,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (!valid) {
r_error_str = "Node requires a script with a _subcall(<args>) method to work.";
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -3248,7 +3045,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall);
instance->instance = p_instance;
Ref<Script> script = get_script();
@@ -3262,7 +3058,6 @@ VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_
}
void VisualScriptSubCall::_bind_methods() {
-
MethodInfo scmi(Variant::NIL, "_subcall", PropertyInfo(Variant::NIL, "arguments"));
scmi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
BIND_VMETHOD(scmi);
@@ -3276,87 +3071,78 @@ VisualScriptSubCall::VisualScriptSubCall() {
//////////////////////////////////////////
int VisualScriptComment::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptComment::has_input_sequence_port() const {
-
return false;
}
int VisualScriptComment::get_input_value_port_count() const {
return 0;
}
-int VisualScriptComment::get_output_value_port_count() const {
+int VisualScriptComment::get_output_value_port_count() const {
return 0;
}
String VisualScriptComment::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptComment::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptComment::get_caption() const {
-
return title;
}
String VisualScriptComment::get_text() const {
-
return description;
}
void VisualScriptComment::set_title(const String &p_title) {
-
- if (title == p_title)
+ if (title == p_title) {
return;
+ }
title = p_title;
ports_changed_notify();
}
String VisualScriptComment::get_title() const {
-
return title;
}
void VisualScriptComment::set_description(const String &p_description) {
-
- if (description == p_description)
+ if (description == p_description) {
return;
+ }
description = p_description;
ports_changed_notify();
}
-String VisualScriptComment::get_description() const {
+String VisualScriptComment::get_description() const {
return description;
}
void VisualScriptComment::set_size(const Size2 &p_size) {
-
- if (size == p_size)
+ if (size == p_size) {
return;
+ }
size = p_size;
ports_changed_notify();
}
-Size2 VisualScriptComment::get_size() const {
+Size2 VisualScriptComment::get_size() const {
return size;
}
String VisualScriptComment::get_category() const {
-
return "data";
}
@@ -3367,20 +3153,17 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
return 0;
}
};
VisualScriptNodeInstance *VisualScriptComment::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceComment *instance = memnew(VisualScriptNodeInstanceComment);
instance->instance = p_instance;
return instance;
}
void VisualScriptComment::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_title", "title"), &VisualScriptComment::set_title);
ClassDB::bind_method(D_METHOD("get_title"), &VisualScriptComment::get_title);
@@ -3396,7 +3179,6 @@ void VisualScriptComment::_bind_methods() {
}
VisualScriptComment::VisualScriptComment() {
-
title = "Comment";
size = Size2(150, 150);
}
@@ -3406,70 +3188,60 @@ VisualScriptComment::VisualScriptComment() {
//////////////////////////////////////////
int VisualScriptConstructor::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptConstructor::has_input_sequence_port() const {
-
return false;
}
int VisualScriptConstructor::get_input_value_port_count() const {
return constructor.arguments.size();
}
-int VisualScriptConstructor::get_output_value_port_count() const {
+int VisualScriptConstructor::get_output_value_port_count() const {
return 1;
}
String VisualScriptConstructor::get_output_sequence_port_text(int p_port) const {
-
return "";
}
PropertyInfo VisualScriptConstructor::get_input_value_port_info(int p_idx) const {
-
return constructor.arguments[p_idx];
}
PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(type, "value");
}
String VisualScriptConstructor::get_caption() const {
-
return "Construct " + Variant::get_type_name(type);
}
String VisualScriptConstructor::get_category() const {
-
return "functions";
}
void VisualScriptConstructor::set_constructor_type(Variant::Type p_type) {
-
- if (type == p_type)
+ if (type == p_type) {
return;
+ }
type = p_type;
ports_changed_notify();
}
Variant::Type VisualScriptConstructor::get_constructor_type() const {
-
return type;
}
void VisualScriptConstructor::set_constructor(const Dictionary &p_info) {
-
constructor = MethodInfo::from_dict(p_info);
ports_changed_notify();
}
Dictionary VisualScriptConstructor::get_constructor() const {
-
return constructor;
}
@@ -3482,9 +3254,8 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Callable::CallError ce;
- *p_outputs[0] = Variant::construct(type, p_inputs, argcount, ce);
+ Variant::construct(type, *p_outputs[0], p_inputs, argcount, ce);
if (ce.error != Callable::CallError::CALL_OK) {
r_error_str = "Invalid arguments for constructor";
}
@@ -3494,7 +3265,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor);
instance->instance = p_instance;
instance->type = type;
@@ -3503,7 +3273,6 @@ VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance
}
void VisualScriptConstructor::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_constructor_type", "type"), &VisualScriptConstructor::set_constructor_type);
ClassDB::bind_method(D_METHOD("get_constructor_type"), &VisualScriptConstructor::get_constructor_type);
@@ -3515,14 +3284,12 @@ void VisualScriptConstructor::_bind_methods() {
}
VisualScriptConstructor::VisualScriptConstructor() {
-
type = Variant::NIL;
}
static Map<String, Pair<Variant::Type, MethodInfo>> constructor_map;
static Ref<VisualScriptNode> create_constructor_node(const String &p_name) {
-
ERR_FAIL_COND_V(!constructor_map.has(p_name), Ref<VisualScriptNode>());
Ref<VisualScriptConstructor> vsc;
@@ -3538,69 +3305,60 @@ static Ref<VisualScriptNode> create_constructor_node(const String &p_name) {
//////////////////////////////////////////
int VisualScriptLocalVar::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptLocalVar::has_input_sequence_port() const {
-
return false;
}
int VisualScriptLocalVar::get_input_value_port_count() const {
return 0;
}
-int VisualScriptLocalVar::get_output_value_port_count() const {
+int VisualScriptLocalVar::get_output_value_port_count() const {
return 1;
}
String VisualScriptLocalVar::get_output_sequence_port_text(int p_port) const {
-
return "";
}
PropertyInfo VisualScriptLocalVar::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
-PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, name);
}
String VisualScriptLocalVar::get_caption() const {
-
return "Get Local Var";
}
String VisualScriptLocalVar::get_category() const {
-
return "data";
}
void VisualScriptLocalVar::set_var_name(const StringName &p_name) {
-
- if (name == p_name)
+ if (name == p_name) {
return;
+ }
name = p_name;
ports_changed_notify();
}
StringName VisualScriptLocalVar::get_var_name() const {
-
return name;
}
void VisualScriptLocalVar::set_var_type(Variant::Type p_type) {
-
type = p_type;
ports_changed_notify();
}
Variant::Type VisualScriptLocalVar::get_var_type() const {
-
return type;
}
@@ -3611,14 +3369,12 @@ public:
virtual int get_working_memory_size() const { return 1; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_outputs[0] = *p_working_mem;
return 0;
}
};
VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar);
instance->instance = p_instance;
instance->name = name;
@@ -3627,7 +3383,6 @@ VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p
}
void VisualScriptLocalVar::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_var_name", "name"), &VisualScriptLocalVar::set_var_name);
ClassDB::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVar::get_var_name);
@@ -3644,7 +3399,6 @@ void VisualScriptLocalVar::_bind_methods() {
}
VisualScriptLocalVar::VisualScriptLocalVar() {
-
name = "new_local";
type = Variant::NIL;
}
@@ -3654,74 +3408,64 @@ VisualScriptLocalVar::VisualScriptLocalVar() {
//////////////////////////////////////////
int VisualScriptLocalVarSet::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptLocalVarSet::has_input_sequence_port() const {
-
return true;
}
int VisualScriptLocalVarSet::get_input_value_port_count() const {
return 1;
}
-int VisualScriptLocalVarSet::get_output_value_port_count() const {
+int VisualScriptLocalVarSet::get_output_value_port_count() const {
return 1;
}
String VisualScriptLocalVarSet::get_output_sequence_port_text(int p_port) const {
-
return "";
}
PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo(type, "set");
}
-PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) const {
return PropertyInfo(type, "get");
}
String VisualScriptLocalVarSet::get_caption() const {
-
return "Set Local Var";
}
String VisualScriptLocalVarSet::get_text() const {
-
return name;
}
String VisualScriptLocalVarSet::get_category() const {
-
return "data";
}
void VisualScriptLocalVarSet::set_var_name(const StringName &p_name) {
-
- if (name == p_name)
+ if (name == p_name) {
return;
+ }
name = p_name;
ports_changed_notify();
}
StringName VisualScriptLocalVarSet::get_var_name() const {
-
return name;
}
void VisualScriptLocalVarSet::set_var_type(Variant::Type p_type) {
-
type = p_type;
ports_changed_notify();
}
Variant::Type VisualScriptLocalVarSet::get_var_type() const {
-
return type;
}
@@ -3732,7 +3476,6 @@ public:
virtual int get_working_memory_size() const { return 1; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
*p_working_mem = *p_inputs[0];
*p_outputs[0] = *p_working_mem;
return 0;
@@ -3740,7 +3483,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet);
instance->instance = p_instance;
instance->name = name;
@@ -3749,7 +3491,6 @@ VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance
}
void VisualScriptLocalVarSet::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_var_name", "name"), &VisualScriptLocalVarSet::set_var_name);
ClassDB::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVarSet::get_var_name);
@@ -3766,7 +3507,6 @@ void VisualScriptLocalVarSet::_bind_methods() {
}
VisualScriptLocalVarSet::VisualScriptLocalVarSet() {
-
name = "new_local";
type = Variant::NIL;
}
@@ -3776,34 +3516,30 @@ VisualScriptLocalVarSet::VisualScriptLocalVarSet() {
//////////////////////////////////////////
int VisualScriptInputAction::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptInputAction::has_input_sequence_port() const {
-
return false;
}
int VisualScriptInputAction::get_input_value_port_count() const {
return 0;
}
-int VisualScriptInputAction::get_output_value_port_count() const {
+int VisualScriptInputAction::get_output_value_port_count() const {
return 1;
}
String VisualScriptInputAction::get_output_sequence_port_text(int p_port) const {
-
return "";
}
PropertyInfo VisualScriptInputAction::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
-PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) const {
+PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) const {
String mstr;
switch (mode) {
case MODE_PRESSED: {
@@ -3824,39 +3560,36 @@ PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) cons
}
String VisualScriptInputAction::get_caption() const {
-
return "Action " + name;
}
String VisualScriptInputAction::get_category() const {
-
return "data";
}
void VisualScriptInputAction::set_action_name(const StringName &p_name) {
-
- if (name == p_name)
+ if (name == p_name) {
return;
+ }
name = p_name;
ports_changed_notify();
}
StringName VisualScriptInputAction::get_action_name() const {
-
return name;
}
void VisualScriptInputAction::set_action_mode(Mode p_mode) {
-
- if (mode == p_mode)
+ if (mode == p_mode) {
return;
+ }
mode = p_mode;
ports_changed_notify();
}
-VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const {
+VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const {
return mode;
}
@@ -3867,7 +3600,6 @@ public:
VisualScriptInputAction::Mode mode;
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
switch (mode) {
case VisualScriptInputAction::MODE_PRESSED: {
*p_outputs[0] = Input::get_singleton()->is_action_pressed(action);
@@ -3888,7 +3620,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction);
instance->instance = p_instance;
instance->action = name;
@@ -3898,9 +3629,7 @@ VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance
}
void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
-
if (property.name == "action") {
-
property.hint = PROPERTY_HINT_ENUM;
String actions;
@@ -3911,8 +3640,9 @@ void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
const PropertyInfo &pi = E->get();
- if (!pi.name.begins_with("input/"))
+ if (!pi.name.begins_with("input/")) {
continue;
+ }
String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
@@ -3922,8 +3652,9 @@ void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
al.sort();
for (int i = 0; i < al.size(); i++) {
- if (actions != String())
+ if (actions != String()) {
actions += ",";
+ }
actions += al[i];
}
@@ -3932,7 +3663,6 @@ void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
}
void VisualScriptInputAction::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_action_name", "name"), &VisualScriptInputAction::set_action_name);
ClassDB::bind_method(D_METHOD("get_action_name"), &VisualScriptInputAction::get_action_name);
@@ -3949,7 +3679,6 @@ void VisualScriptInputAction::_bind_methods() {
}
VisualScriptInputAction::VisualScriptInputAction() {
-
name = "";
mode = MODE_PRESSED;
}
@@ -3959,60 +3688,51 @@ VisualScriptInputAction::VisualScriptInputAction() {
//////////////////////////////////////////
int VisualScriptDeconstruct::get_output_sequence_port_count() const {
-
return 0;
}
bool VisualScriptDeconstruct::has_input_sequence_port() const {
-
return false;
}
int VisualScriptDeconstruct::get_input_value_port_count() const {
return 1;
}
-int VisualScriptDeconstruct::get_output_value_port_count() const {
+int VisualScriptDeconstruct::get_output_value_port_count() const {
return elements.size();
}
String VisualScriptDeconstruct::get_output_sequence_port_text(int p_port) const {
-
return "";
}
PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo(type, "value");
}
PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo(elements[p_idx].type, elements[p_idx].name);
}
String VisualScriptDeconstruct::get_caption() const {
-
return "Deconstruct " + Variant::get_type_name(type);
}
String VisualScriptDeconstruct::get_category() const {
-
return "functions";
}
void VisualScriptDeconstruct::_update_elements() {
-
elements.clear();
Variant v;
Callable::CallError ce;
- v = Variant::construct(type, nullptr, 0, ce);
+ Variant::construct(type, v, nullptr, 0, ce);
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
-
Element e;
e.name = E->get().name;
e.type = E->get().type;
@@ -4021,9 +3741,9 @@ void VisualScriptDeconstruct::_update_elements() {
}
void VisualScriptDeconstruct::set_deconstruct_type(Variant::Type p_type) {
-
- if (type == p_type)
+ if (type == p_type) {
return;
+ }
type = p_type;
_update_elements();
@@ -4032,12 +3752,10 @@ void VisualScriptDeconstruct::set_deconstruct_type(Variant::Type p_type) {
}
Variant::Type VisualScriptDeconstruct::get_deconstruct_type() const {
-
return type;
}
void VisualScriptDeconstruct::_set_elem_cache(const Array &p_elements) {
-
ERR_FAIL_COND(p_elements.size() % 2 == 1);
elements.resize(p_elements.size() / 2);
for (int i = 0; i < elements.size(); i++) {
@@ -4047,7 +3765,6 @@ void VisualScriptDeconstruct::_set_elem_cache(const Array &p_elements) {
}
Array VisualScriptDeconstruct::_get_elem_cache() const {
-
Array ret;
for (int i = 0; i < elements.size(); i++) {
ret.push_back(elements[i].name);
@@ -4064,7 +3781,6 @@ public:
//virtual int get_working_memory_size() const { return 0; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
Variant in = *p_inputs[0];
for (int i = 0; i < outputs.size(); i++) {
@@ -4082,7 +3798,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptDeconstruct::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct);
instance->instance = p_instance;
instance->outputs.resize(elements.size());
@@ -4097,7 +3812,6 @@ void VisualScriptDeconstruct::_validate_property(PropertyInfo &property) const {
}
void VisualScriptDeconstruct::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_deconstruct_type", "type"), &VisualScriptDeconstruct::set_deconstruct_type);
ClassDB::bind_method(D_METHOD("get_deconstruct_type"), &VisualScriptDeconstruct::get_deconstruct_type);
@@ -4114,7 +3828,6 @@ void VisualScriptDeconstruct::_bind_methods() {
}
VisualScriptDeconstruct::VisualScriptDeconstruct() {
-
type = Variant::NIL;
}
@@ -4127,7 +3840,6 @@ static Ref<VisualScriptNode> create_node_deconst_typed(const String &p_name) {
}
void register_visual_script_nodes() {
-
VisualScriptLanguage::singleton->add_register_func("data/set_variable", create_node_generic<VisualScriptVariableSet>);
VisualScriptLanguage::singleton->add_register_func("data/get_variable", create_node_generic<VisualScriptVariableGet>);
VisualScriptLanguage::singleton->add_register_func("data/engine_singleton", create_node_generic<VisualScriptEngineSingleton>);
@@ -4167,7 +3879,6 @@ void register_visual_script_nodes() {
VisualScriptLanguage::singleton->add_register_func("operators/math/negate", create_op_node<Variant::OP_NEGATE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/positive", create_op_node<Variant::OP_POSITIVE>);
VisualScriptLanguage::singleton->add_register_func("operators/math/remainder", create_op_node<Variant::OP_MODULE>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/string_concat", create_op_node<Variant::OP_STRING_CONCAT>);
//bitwise
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_left", create_op_node<Variant::OP_SHIFT_LEFT>);
VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_right", create_op_node<Variant::OP_SHIFT_RIGHT>);
@@ -4199,12 +3910,10 @@ void register_visual_script_nodes() {
VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>);
for (int i = 1; i < Variant::VARIANT_MAX; i++) {
-
List<MethodInfo> constructors;
Variant::get_constructor_list(Variant::Type(i), &constructors);
for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) {
-
if (E->get().arguments.size() > 0) {
String name = "functions/constructors/" + Variant::get_type_name(Variant::Type(i)) + "(";
for (int j = 0; j < E->get().arguments.size(); j++) {
@@ -4229,6 +3938,5 @@ void register_visual_script_nodes() {
}
void unregister_visual_script_nodes() {
-
constructor_map.clear();
}
diff --git a/modules/visual_script/visual_script_nodes.h b/modules/visual_script/visual_script_nodes.h
index 0df5071491..ae5e04d096 100644
--- a/modules/visual_script/visual_script_nodes.h
+++ b/modules/visual_script/visual_script_nodes.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "visual_script.h"
class VisualScriptFunction : public VisualScriptNode {
-
GDCLASS(VisualScriptFunction, VisualScriptNode);
struct Argument {
@@ -57,20 +56,20 @@ protected:
void _get_property_list(List<PropertyInfo> *p_list) const;
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "flow_control"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "flow_control"; }
void add_argument(Variant::Type p_type, const String &p_name, int p_index = -1, const PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = String(""));
void set_argument_type(int p_argidx, Variant::Type p_type);
@@ -98,13 +97,12 @@ public:
void set_rpc_mode(MultiplayerAPI::RPCMode p_mode);
MultiplayerAPI::RPCMode get_rpc_mode() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptFunction();
};
class VisualScriptLists : public VisualScriptNode {
-
GDCLASS(VisualScriptLists, VisualScriptNode)
struct Port {
@@ -144,20 +142,16 @@ public:
virtual bool is_input_port_name_editable() const;
virtual bool is_input_port_type_editable() const;
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
-
- virtual String get_caption() const = 0;
- virtual String get_text() const = 0;
- virtual String get_category() const = 0;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
void add_input_data_port(Variant::Type p_type, const String &p_name, int p_index = -1);
void set_input_data_port_type(int p_idx, Variant::Type p_type);
@@ -176,32 +170,30 @@ public:
};
class VisualScriptComposeArray : public VisualScriptLists {
-
GDCLASS(VisualScriptComposeArray, VisualScriptLists)
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptComposeArray();
};
class VisualScriptOperator : public VisualScriptNode {
-
GDCLASS(VisualScriptOperator, VisualScriptNode);
Variant::Type typed;
@@ -211,19 +203,19 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "operators"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "operators"; }
void set_operator(Variant::Operator p_op);
Variant::Operator get_operator() const;
@@ -231,13 +223,12 @@ public:
void set_typed(Variant::Type p_op);
Variant::Type get_typed() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptOperator();
};
class VisualScriptSelect : public VisualScriptNode {
-
GDCLASS(VisualScriptSelect, VisualScriptNode);
Variant::Type typed;
@@ -246,120 +237,117 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "operators"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "operators"; }
void set_typed(Variant::Type p_op);
Variant::Type get_typed() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptSelect();
};
class VisualScriptVariableGet : public VisualScriptNode {
-
GDCLASS(VisualScriptVariableGet, VisualScriptNode);
StringName variable;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_variable(StringName p_variable);
StringName get_variable() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptVariableGet();
};
class VisualScriptVariableSet : public VisualScriptNode {
-
GDCLASS(VisualScriptVariableSet, VisualScriptNode);
StringName variable;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_variable(StringName p_variable);
StringName get_variable() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptVariableSet();
};
class VisualScriptConstant : public VisualScriptNode {
-
GDCLASS(VisualScriptConstant, VisualScriptNode);
Variant::Type type;
Variant value;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "constants"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "constants"; }
void set_constant_type(Variant::Type p_type);
Variant::Type get_constant_type() const;
@@ -367,13 +355,12 @@ public:
void set_constant_value(Variant p_value);
Variant get_constant_value() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptConstant();
};
class VisualScriptPreload : public VisualScriptNode {
-
GDCLASS(VisualScriptPreload, VisualScriptNode);
Ref<Resource> preload;
@@ -382,78 +369,75 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_preload(const Ref<Resource> &p_preload);
Ref<Resource> get_preload() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptPreload();
};
class VisualScriptIndexGet : public VisualScriptNode {
-
GDCLASS(VisualScriptIndexGet, VisualScriptNode);
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "operators"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "operators"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptIndexGet();
};
class VisualScriptIndexSet : public VisualScriptNode {
-
GDCLASS(VisualScriptIndexSet, VisualScriptNode);
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "operators"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "operators"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptIndexSet();
};
class VisualScriptGlobalConstant : public VisualScriptNode {
-
GDCLASS(VisualScriptGlobalConstant, VisualScriptNode);
int index;
@@ -461,30 +445,29 @@ class VisualScriptGlobalConstant : public VisualScriptNode {
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "constants"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "constants"; }
void set_global_constant(int p_which);
int get_global_constant();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptGlobalConstant();
};
class VisualScriptClassConstant : public VisualScriptNode {
-
GDCLASS(VisualScriptClassConstant, VisualScriptNode);
StringName base_type;
@@ -492,22 +475,22 @@ class VisualScriptClassConstant : public VisualScriptNode {
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "constants"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "constants"; }
void set_class_constant(const StringName &p_which);
StringName get_class_constant();
@@ -515,13 +498,12 @@ public:
void set_base_type(const StringName &p_which);
StringName get_base_type();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptClassConstant();
};
class VisualScriptBasicTypeConstant : public VisualScriptNode {
-
GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode);
Variant::Type type;
@@ -529,23 +511,23 @@ class VisualScriptBasicTypeConstant : public VisualScriptNode {
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "constants"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "constants"; }
void set_basic_type_constant(const StringName &p_which);
StringName get_basic_type_constant() const;
@@ -553,13 +535,12 @@ public:
void set_basic_type(Variant::Type p_which);
Variant::Type get_basic_type() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptBasicTypeConstant();
};
class VisualScriptMathConstant : public VisualScriptNode {
-
GDCLASS(VisualScriptMathConstant, VisualScriptNode);
public:
@@ -584,24 +565,24 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "constants"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "constants"; }
void set_math_constant(MathConstant p_which);
MathConstant get_math_constant();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptMathConstant();
};
@@ -609,108 +590,104 @@ public:
VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant)
class VisualScriptEngineSingleton : public VisualScriptNode {
-
GDCLASS(VisualScriptEngineSingleton, VisualScriptNode);
String singleton;
protected:
- void _validate_property(PropertyInfo &property) const;
+ void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_singleton(const String &p_string);
String get_singleton();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptEngineSingleton();
};
class VisualScriptSceneNode : public VisualScriptNode {
-
GDCLASS(VisualScriptSceneNode, VisualScriptNode);
NodePath path;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_node_path(const NodePath &p_path);
NodePath get_node_path();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptSceneNode();
};
class VisualScriptSceneTree : public VisualScriptNode {
-
GDCLASS(VisualScriptSceneTree, VisualScriptNode);
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptSceneTree();
};
class VisualScriptResourcePath : public VisualScriptNode {
-
GDCLASS(VisualScriptResourcePath, VisualScriptNode);
String path;
@@ -719,59 +696,57 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
void set_resource_path(const String &p_path);
String get_resource_path();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptResourcePath();
};
class VisualScriptSelf : public VisualScriptNode {
-
GDCLASS(VisualScriptSelf, VisualScriptNode);
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const { return "data"; }
+ virtual String get_caption() const override;
+ virtual String get_category() const override { return "data"; }
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
- virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override;
VisualScriptSelf();
};
class VisualScriptCustomNode : public VisualScriptNode {
-
GDCLASS(VisualScriptCustomNode, VisualScriptNode);
protected:
@@ -794,22 +769,22 @@ public:
STEP_YIELD_BIT = STEP_SHIFT << 4, //yield (will find VisualScriptFunctionState state in first working memory)
};
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
void _script_changed();
@@ -819,35 +794,33 @@ public:
VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode);
class VisualScriptSubCall : public VisualScriptNode {
-
GDCLASS(VisualScriptSubCall, VisualScriptNode);
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptSubCall();
};
class VisualScriptComment : public VisualScriptNode {
-
GDCLASS(VisualScriptComment, VisualScriptNode);
String title;
@@ -858,20 +831,20 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override;
void set_title(const String &p_title);
String get_title() const;
@@ -882,13 +855,12 @@ public:
void set_size(const Size2 &p_size);
Size2 get_size() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptComment();
};
class VisualScriptConstructor : public VisualScriptNode {
-
GDCLASS(VisualScriptConstructor, VisualScriptNode);
Variant::Type type;
@@ -898,19 +870,19 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_category() const override;
void set_constructor_type(Variant::Type p_type);
Variant::Type get_constructor_type() const;
@@ -918,13 +890,12 @@ public:
void set_constructor(const Dictionary &p_info);
Dictionary get_constructor() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptConstructor();
};
class VisualScriptLocalVar : public VisualScriptNode {
-
GDCLASS(VisualScriptLocalVar, VisualScriptNode);
StringName name;
@@ -934,19 +905,19 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_category() const override;
void set_var_name(const StringName &p_name);
StringName get_var_name() const;
@@ -954,13 +925,12 @@ public:
void set_var_type(Variant::Type p_type);
Variant::Type get_var_type() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptLocalVar();
};
class VisualScriptLocalVarSet : public VisualScriptNode {
-
GDCLASS(VisualScriptLocalVarSet, VisualScriptNode);
StringName name;
@@ -970,20 +940,20 @@ protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override;
void set_var_name(const StringName &p_name);
StringName get_var_name() const;
@@ -991,13 +961,12 @@ public:
void set_var_type(Variant::Type p_type);
Variant::Type get_var_type() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptLocalVarSet();
};
class VisualScriptInputAction : public VisualScriptNode {
-
GDCLASS(VisualScriptInputAction, VisualScriptNode);
public:
@@ -1012,24 +981,24 @@ public:
Mode mode;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_category() const override;
void set_action_name(const StringName &p_name);
StringName get_action_name() const;
@@ -1037,7 +1006,7 @@ public:
void set_action_mode(Mode p_mode);
Mode get_action_mode() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptInputAction();
};
@@ -1045,7 +1014,6 @@ public:
VARIANT_ENUM_CAST(VisualScriptInputAction::Mode)
class VisualScriptDeconstruct : public VisualScriptNode {
-
GDCLASS(VisualScriptDeconstruct, VisualScriptNode);
struct Element {
@@ -1061,30 +1029,30 @@ class VisualScriptDeconstruct : public VisualScriptNode {
void _set_elem_cache(const Array &p_elements);
Array _get_elem_cache() const;
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
protected:
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_category() const;
+ virtual String get_caption() const override;
+ virtual String get_category() const override;
void set_deconstruct_type(Variant::Type p_type);
Variant::Type get_deconstruct_type() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptDeconstruct();
};
diff --git a/modules/visual_script/visual_script_property_selector.cpp b/modules/visual_script/visual_script_property_selector.cpp
index f57853078d..862cac5c67 100644
--- a/modules/visual_script/visual_script_property_selector.cpp
+++ b/modules/visual_script/visual_script_property_selector.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,6 +31,7 @@
#include "visual_script_property_selector.h"
#include "core/os/keyboard.h"
+#include "editor/doc_tools.h"
#include "editor/editor_node.h"
#include "editor/editor_scale.h"
#include "modules/visual_script/visual_script.h"
@@ -46,23 +47,21 @@ void VisualScriptPropertySelector::_text_changed(const String &p_newtext) {
}
void VisualScriptPropertySelector::_sbox_input(const Ref<InputEvent> &p_ie) {
-
Ref<InputEventKey> k = p_ie;
if (k.is_valid()) {
-
switch (k->get_keycode()) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN: {
-
search_options->call("_gui_input", k);
search_box->accept_event();
TreeItem *root = search_options->get_root();
- if (!root->get_children())
+ if (!root->get_children()) {
break;
+ }
TreeItem *current = search_options->get_selected();
@@ -153,11 +152,13 @@ void VisualScriptPropertySelector::_update_search() {
}
}
for (List<PropertyInfo>::Element *F = props.front(); F; F = F->next()) {
- if (!(F->get().usage & PROPERTY_USAGE_EDITOR) && !(F->get().usage & PROPERTY_USAGE_SCRIPT_VARIABLE))
+ if (!(F->get().usage & PROPERTY_USAGE_EDITOR) && !(F->get().usage & PROPERTY_USAGE_SCRIPT_VARIABLE)) {
continue;
+ }
- if (type_filter.size() && type_filter.find(F->get().type) == -1)
+ if (type_filter.size() && type_filter.find(F->get().type) == -1) {
continue;
+ }
// capitalize() also converts underscore to space, we'll match again both possible styles
String get_text_raw = String(vformat(TTR("Get %s"), F->get().name));
@@ -172,7 +173,7 @@ void VisualScriptPropertySelector::_update_search() {
item->set_metadata(0, F->get().name);
item->set_icon(0, type_icons[F->get().type]);
item->set_metadata(1, "get");
- item->set_collapsed(1);
+ item->set_collapsed(true);
item->set_selectable(0, true);
item->set_selectable(1, false);
item->set_selectable(2, false);
@@ -196,10 +197,9 @@ void VisualScriptPropertySelector::_update_search() {
if (type != Variant::NIL) {
Variant v;
Callable::CallError ce;
- v = Variant::construct(type, nullptr, 0, ce);
+ Variant::construct(type, v, nullptr, 0, ce);
v.get_method_list(&methods);
} else {
-
Object *obj = ObjectDB::get_instance(script);
if (Object::cast_to<Script>(obj)) {
Object::cast_to<Script>(obj)->get_script_method_list(&methods);
@@ -209,23 +209,24 @@ void VisualScriptPropertySelector::_update_search() {
}
}
for (List<MethodInfo>::Element *M = methods.front(); M; M = M->next()) {
-
String name = M->get().name.get_slice(":", 0);
- if (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))
+ if (virtuals_only && !(M->get().flags & METHOD_FLAG_VIRTUAL)) {
continue;
+ }
- if (!virtuals_only && (M->get().flags & METHOD_FLAG_VIRTUAL))
+ if (!virtuals_only && (M->get().flags & METHOD_FLAG_VIRTUAL)) {
continue;
+ }
MethodInfo mi = M->get();
String desc_arguments;
if (mi.arguments.size() > 0) {
desc_arguments = "(";
for (int i = 0; i < mi.arguments.size(); i++) {
-
if (i > 0) {
desc_arguments += ", ";
}
@@ -257,7 +258,7 @@ void VisualScriptPropertySelector::_update_search() {
item->set_selectable(0, true);
item->set_metadata(1, "method");
- item->set_collapsed(1);
+ item->set_collapsed(true);
item->set_selectable(1, false);
item->set_selectable(2, false);
@@ -309,7 +310,7 @@ void VisualScriptPropertySelector::_update_search() {
found = true;
}
- get_ok()->set_disabled(root->get_children() == nullptr);
+ get_ok_button()->set_disabled(root->get_children() == nullptr);
}
void VisualScriptPropertySelector::create_visualscript_item(const String &name, TreeItem *const root, const String &search_input, const String &text) {
@@ -320,7 +321,7 @@ void VisualScriptPropertySelector::create_visualscript_item(const String &name,
item->set_metadata(0, name);
item->set_metadata(1, "action");
item->set_selectable(0, true);
- item->set_collapsed(1);
+ item->set_collapsed(true);
item->set_selectable(1, false);
item->set_selectable(2, false);
item->set_metadata(2, connecting);
@@ -357,10 +358,11 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt
continue;
}
- bool in_modifier = p_modifiers.empty();
+ bool in_modifier = p_modifiers.is_empty();
for (Set<String>::Element *F = p_modifiers.front(); F && in_modifier; F = F->next()) {
- if (E->get().findn(F->get()) != -1)
+ if (E->get().findn(F->get()) != -1) {
in_modifier = true;
+ }
}
if (!in_modifier) {
continue;
@@ -411,21 +413,21 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt
}
void VisualScriptPropertySelector::_confirmed() {
-
TreeItem *ti = search_options->get_selected();
- if (!ti)
+ if (!ti) {
return;
+ }
emit_signal("selected", ti->get_metadata(0), ti->get_metadata(1), ti->get_metadata(2));
set_visible(false);
}
void VisualScriptPropertySelector::_item_selected() {
-
help_bit->set_text("");
TreeItem *item = search_options->get_selected();
- if (!item)
+ if (!item) {
return;
+ }
String name = item->get_metadata(0);
String class_type;
@@ -436,18 +438,17 @@ void VisualScriptPropertySelector::_item_selected() {
class_type = base_type;
}
- DocData *dd = EditorHelp::get_doc_data();
+ DocTools *dd = EditorHelp::get_doc_data();
String text;
String at_class = class_type;
while (at_class != String()) {
-
Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(at_class);
if (E) {
for (int i = 0; i < E->get().properties.size(); i++) {
if (E->get().properties[i].name == name) {
- text = E->get().properties[i].description;
+ text = DTR(E->get().properties[i].description);
}
}
}
@@ -457,12 +458,11 @@ void VisualScriptPropertySelector::_item_selected() {
at_class = class_type;
while (at_class != String()) {
-
Map<String, DocData::ClassDoc>::Element *C = dd->class_list.find(at_class);
if (C) {
for (int i = 0; i < C->get().methods.size(); i++) {
if (C->get().methods[i].name == name) {
- text = C->get().methods[i].description;
+ text = DTR(C->get().methods[i].description);
}
}
}
@@ -474,7 +474,7 @@ void VisualScriptPropertySelector::_item_selected() {
for (int i = 0; i < T->get().methods.size(); i++) {
Vector<String> functions = name.rsplit("/", false, 1);
if (T->get().methods[i].name == functions[functions.size() - 1]) {
- text = T->get().methods[i].description;
+ text = DTR(T->get().methods[i].description);
}
}
}
@@ -493,7 +493,7 @@ void VisualScriptPropertySelector::_item_selected() {
if (typecast_node.is_valid()) {
Map<String, DocData::ClassDoc>::Element *F = dd->class_list.find(typecast_node->get_class_name());
if (F) {
- text = F->get().description;
+ text = DTR(F->get().description);
}
}
@@ -503,7 +503,7 @@ void VisualScriptPropertySelector::_item_selected() {
if (F) {
for (int i = 0; i < F->get().constants.size(); i++) {
if (F->get().constants[i].value.to_int() == int(builtin_node->get_func())) {
- text = F->get().constants[i].description;
+ text = DTR(F->get().constants[i].description);
}
}
}
@@ -512,8 +512,9 @@ void VisualScriptPropertySelector::_item_selected() {
memdelete(names);
- if (text == String())
+ if (text == String()) {
return;
+ }
help_bit->set_text(text);
}
@@ -523,15 +524,12 @@ void VisualScriptPropertySelector::_hide_requested() {
}
void VisualScriptPropertySelector::_notification(int p_what) {
-
if (p_what == NOTIFICATION_ENTER_TREE) {
-
connect("confirmed", callable_mp(this, &VisualScriptPropertySelector::_confirmed));
}
}
void VisualScriptPropertySelector::select_method_from_base_type(const String &p_base, const String &p_current, const bool p_virtuals_only, const bool p_connecting, bool clear_text) {
-
base_type = p_base;
selected = p_current;
type = Variant::NIL;
@@ -540,10 +538,11 @@ void VisualScriptPropertySelector::select_method_from_base_type(const String &p_
virtuals_only = p_virtuals_only;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
connecting = p_connecting;
@@ -555,7 +554,6 @@ void VisualScriptPropertySelector::set_type_filter(const Vector<Variant::Type> &
}
void VisualScriptPropertySelector::select_from_base_type(const String &p_base, const String &p_current, bool p_virtuals_only, bool p_seq_connect, const bool p_connecting, bool clear_text) {
-
base_type = p_base;
selected = p_current;
type = Variant::NIL;
@@ -565,10 +563,11 @@ void VisualScriptPropertySelector::select_from_base_type(const String &p_base, c
virtuals_only = p_virtuals_only;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
seq_connect = p_seq_connect;
connecting = p_connecting;
@@ -589,10 +588,11 @@ void VisualScriptPropertySelector::select_from_script(const Ref<Script> &p_scrip
virtuals_only = false;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
seq_connect = false;
connecting = p_connecting;
@@ -611,10 +611,11 @@ void VisualScriptPropertySelector::select_from_basic_type(Variant::Type p_type,
virtuals_only = false;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
seq_connect = false;
connecting = p_connecting;
@@ -632,10 +633,11 @@ void VisualScriptPropertySelector::select_from_action(const String &p_type, cons
virtuals_only = false;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
seq_connect = true;
connecting = p_connecting;
@@ -653,10 +655,11 @@ void VisualScriptPropertySelector::select_from_instance(Object *p_instance, cons
virtuals_only = false;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
seq_connect = false;
connecting = p_connecting;
@@ -673,10 +676,11 @@ void VisualScriptPropertySelector::select_from_visual_script(const String &p_bas
instance = nullptr;
virtuals_only = false;
show_window(.5f);
- if (clear_text)
+ if (clear_text) {
search_box->set_text("");
- else
+ } else {
search_box->select_all();
+ }
search_box->grab_focus();
connecting = p_connecting;
@@ -684,17 +688,14 @@ void VisualScriptPropertySelector::select_from_visual_script(const String &p_bas
}
void VisualScriptPropertySelector::show_window(float p_screen_ratio) {
-
popup_centered_ratio(p_screen_ratio);
}
void VisualScriptPropertySelector::_bind_methods() {
-
ADD_SIGNAL(MethodInfo("selected", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "category"), PropertyInfo(Variant::BOOL, "connecting")));
}
VisualScriptPropertySelector::VisualScriptPropertySelector() {
-
vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
@@ -704,8 +705,8 @@ VisualScriptPropertySelector::VisualScriptPropertySelector() {
search_box->connect("gui_input", callable_mp(this, &VisualScriptPropertySelector::_sbox_input));
search_options = memnew(Tree);
vbc->add_margin_child(TTR("Matches:"), search_options, true);
- get_ok()->set_text(TTR("Open"));
- get_ok()->set_disabled(true);
+ get_ok_button()->set_text(TTR("Open"));
+ get_ok_button()->set_disabled(true);
register_text_enter(search_box);
set_hide_on_ok(false);
search_options->connect("item_activated", callable_mp(this, &VisualScriptPropertySelector::_confirmed));
diff --git a/modules/visual_script/visual_script_property_selector.h b/modules/visual_script/visual_script_property_selector.h
index cc49b2863d..7a87f3d3ee 100644
--- a/modules/visual_script/visual_script_property_selector.h
+++ b/modules/visual_script/visual_script_property_selector.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp
index b300aec385..6c9af4e600 100644
--- a/modules/visual_script/visual_script_yield_nodes.cpp
+++ b/modules/visual_script/visual_script_yield_nodes.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,51 +40,51 @@
//////////////////////////////////////////
int VisualScriptYield::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptYield::has_input_sequence_port() const {
-
return true;
}
int VisualScriptYield::get_input_value_port_count() const {
-
return 0;
}
-int VisualScriptYield::get_output_value_port_count() const {
+int VisualScriptYield::get_output_value_port_count() const {
return 0;
}
String VisualScriptYield::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptYield::get_input_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
PropertyInfo VisualScriptYield::get_output_value_port_info(int p_idx) const {
-
return PropertyInfo();
}
String VisualScriptYield::get_caption() const {
-
return yield_mode == YIELD_RETURN ? "Yield" : "Wait";
}
String VisualScriptYield::get_text() const {
-
switch (yield_mode) {
- case YIELD_RETURN: return ""; break;
- case YIELD_FRAME: return "Next Frame"; break;
- case YIELD_PHYSICS_FRAME: return "Next Physics Frame"; break;
- case YIELD_WAIT: return rtos(wait_time) + " sec(s)"; break;
+ case YIELD_RETURN:
+ return "";
+ break;
+ case YIELD_FRAME:
+ return "Next Frame";
+ break;
+ case YIELD_PHYSICS_FRAME:
+ return "Next Physics Frame";
+ break;
+ case YIELD_WAIT:
+ return rtos(wait_time) + " sec(s)";
+ break;
}
return String();
@@ -100,7 +100,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (p_start_mode == START_MODE_RESUME_YIELD) {
return 0; //resuming yield
} else {
@@ -118,13 +117,18 @@ public:
int ret = STEP_YIELD_BIT;
switch (mode) {
-
case VisualScriptYield::YIELD_RETURN:
ret = STEP_EXIT_FUNCTION_BIT;
break; //return the yield
- case VisualScriptYield::YIELD_FRAME: state->connect_to_signal(tree, "idle_frame", Array()); break;
- case VisualScriptYield::YIELD_PHYSICS_FRAME: state->connect_to_signal(tree, "physics_frame", Array()); break;
- case VisualScriptYield::YIELD_WAIT: state->connect_to_signal(tree->create_timer(wait_time).ptr(), "timeout", Array()); break;
+ case VisualScriptYield::YIELD_FRAME:
+ state->connect_to_signal(tree, "idle_frame", Array());
+ break;
+ case VisualScriptYield::YIELD_PHYSICS_FRAME:
+ state->connect_to_signal(tree, "physics_frame", Array());
+ break;
+ case VisualScriptYield::YIELD_WAIT:
+ state->connect_to_signal(tree->create_timer(wait_time).ptr(), "timeout", Array());
+ break;
}
*p_working_mem = state;
@@ -135,7 +139,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptYield::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceYield *instance = memnew(VisualScriptNodeInstanceYield);
//instance->instance=p_instance;
instance->mode = yield_mode;
@@ -144,34 +147,31 @@ VisualScriptNodeInstance *VisualScriptYield::instance(VisualScriptInstance *p_in
}
void VisualScriptYield::set_yield_mode(YieldMode p_mode) {
-
- if (yield_mode == p_mode)
+ if (yield_mode == p_mode) {
return;
+ }
yield_mode = p_mode;
ports_changed_notify();
_change_notify();
}
VisualScriptYield::YieldMode VisualScriptYield::get_yield_mode() {
-
return yield_mode;
}
void VisualScriptYield::set_wait_time(float p_time) {
-
- if (wait_time == p_time)
+ if (wait_time == p_time) {
return;
+ }
wait_time = p_time;
ports_changed_notify();
}
float VisualScriptYield::get_wait_time() {
-
return wait_time;
}
void VisualScriptYield::_validate_property(PropertyInfo &property) const {
-
if (property.name == "wait_time") {
if (yield_mode != YIELD_WAIT) {
property.usage = 0;
@@ -180,7 +180,6 @@ void VisualScriptYield::_validate_property(PropertyInfo &property) const {
}
void VisualScriptYield::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_yield_mode", "mode"), &VisualScriptYield::set_yield_mode);
ClassDB::bind_method(D_METHOD("get_yield_mode"), &VisualScriptYield::get_yield_mode);
@@ -196,14 +195,12 @@ void VisualScriptYield::_bind_methods() {
}
VisualScriptYield::VisualScriptYield() {
-
yield_mode = YIELD_FRAME;
wait_time = 1;
}
template <VisualScriptYield::YieldMode MODE>
static Ref<VisualScriptNode> create_yield_node(const String &p_name) {
-
Ref<VisualScriptYield> node;
node.instance();
node->set_yield_mode(MODE);
@@ -215,30 +212,30 @@ static Ref<VisualScriptNode> create_yield_node(const String &p_name) {
//////////////////////////////////////////////////
int VisualScriptYieldSignal::get_output_sequence_port_count() const {
-
return 1;
}
bool VisualScriptYieldSignal::has_input_sequence_port() const {
-
return true;
}
#ifdef TOOLS_ENABLED
static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
-
- if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene)
+ if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) {
return nullptr;
+ }
Ref<Script> scr = p_current_node->get_script();
- if (scr.is_valid() && scr == script)
+ if (scr.is_valid() && scr == script) {
return p_current_node;
+ }
for (int i = 0; i < p_current_node->get_child_count(); i++) {
Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script);
- if (n)
+ if (n) {
return n;
+ }
}
return nullptr;
@@ -246,30 +243,34 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const
#endif
Node *VisualScriptYieldSignal::_get_base_node() const {
-
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
- if (!script.is_valid())
+ if (!script.is_valid()) {
return nullptr;
+ }
MainLoop *main_loop = OS::get_singleton()->get_main_loop();
SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop);
- if (!scene_tree)
+ if (!scene_tree) {
return nullptr;
+ }
Node *edited_scene = scene_tree->get_edited_scene_root();
- if (!edited_scene)
+ if (!edited_scene) {
return nullptr;
+ }
Node *script_node = _find_script_node(edited_scene, edited_scene, script);
- if (!script_node)
+ if (!script_node) {
return nullptr;
+ }
- if (!script_node->has_node(base_path))
+ if (!script_node->has_node(base_path)) {
return nullptr;
+ }
Node *path_to = script_node->get_node(base_path);
@@ -281,60 +282,59 @@ Node *VisualScriptYieldSignal::_get_base_node() const {
}
StringName VisualScriptYieldSignal::_get_base_type() const {
-
- if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid())
+ if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
return get_visual_script()->get_instance_base_type();
- else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
+ } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) {
Node *path = _get_base_node();
- if (path)
+ if (path) {
return path->get_class();
+ }
}
return base_type;
}
int VisualScriptYieldSignal::get_input_value_port_count() const {
-
- if (call_mode == CALL_MODE_INSTANCE)
+ if (call_mode == CALL_MODE_INSTANCE) {
return 1;
- else
+ } else {
return 0;
+ }
}
-int VisualScriptYieldSignal::get_output_value_port_count() const {
+int VisualScriptYieldSignal::get_output_value_port_count() const {
MethodInfo sr;
- if (!ClassDB::get_signal(_get_base_type(), signal, &sr))
+ if (!ClassDB::get_signal(_get_base_type(), signal, &sr)) {
return 0;
+ }
return sr.arguments.size();
}
String VisualScriptYieldSignal::get_output_sequence_port_text(int p_port) const {
-
return String();
}
PropertyInfo VisualScriptYieldSignal::get_input_value_port_info(int p_idx) const {
-
- if (call_mode == CALL_MODE_INSTANCE)
+ if (call_mode == CALL_MODE_INSTANCE) {
return PropertyInfo(Variant::OBJECT, "instance");
- else
+ } else {
return PropertyInfo();
+ }
}
PropertyInfo VisualScriptYieldSignal::get_output_value_port_info(int p_idx) const {
-
MethodInfo sr;
- if (!ClassDB::get_signal(_get_base_type(), signal, &sr))
+ if (!ClassDB::get_signal(_get_base_type(), signal, &sr)) {
return PropertyInfo(); //no signal
+ }
ERR_FAIL_INDEX_V(p_idx, sr.arguments.size(), PropertyInfo());
return sr.arguments[p_idx];
}
String VisualScriptYieldSignal::get_caption() const {
-
static const char *cname[3] = {
"WaitSignal",
"WaitNodeSignal",
@@ -345,17 +345,17 @@ String VisualScriptYieldSignal::get_caption() const {
}
String VisualScriptYieldSignal::get_text() const {
-
- if (call_mode == CALL_MODE_SELF)
+ if (call_mode == CALL_MODE_SELF) {
return " " + String(signal) + "()";
- else
+ } else {
return " " + _get_base_type() + "." + String(signal) + "()";
+ }
}
void VisualScriptYieldSignal::set_base_type(const StringName &p_type) {
-
- if (base_type == p_type)
+ if (base_type == p_type) {
return;
+ }
base_type = p_type;
@@ -364,29 +364,28 @@ void VisualScriptYieldSignal::set_base_type(const StringName &p_type) {
}
StringName VisualScriptYieldSignal::get_base_type() const {
-
return base_type;
}
void VisualScriptYieldSignal::set_signal(const StringName &p_type) {
-
- if (signal == p_type)
+ if (signal == p_type) {
return;
+ }
signal = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptYieldSignal::get_signal() const {
+StringName VisualScriptYieldSignal::get_signal() const {
return signal;
}
void VisualScriptYieldSignal::set_base_path(const NodePath &p_type) {
-
- if (base_path == p_type)
+ if (base_path == p_type) {
return;
+ }
base_path = p_type;
@@ -395,14 +394,13 @@ void VisualScriptYieldSignal::set_base_path(const NodePath &p_type) {
}
NodePath VisualScriptYieldSignal::get_base_path() const {
-
return base_path;
}
void VisualScriptYieldSignal::set_call_mode(CallMode p_mode) {
-
- if (call_mode == p_mode)
+ if (call_mode == p_mode) {
return;
+ }
call_mode = p_mode;
@@ -411,12 +409,10 @@ void VisualScriptYieldSignal::set_call_mode(CallMode p_mode) {
}
VisualScriptYieldSignal::CallMode VisualScriptYieldSignal::get_call_mode() const {
-
return call_mode;
}
void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
-
if (property.name == "base_type") {
if (call_mode != CALL_MODE_INSTANCE) {
property.usage = PROPERTY_USAGE_NOEDITOR;
@@ -427,7 +423,6 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
if (call_mode != CALL_MODE_NODE_PATH) {
property.usage = 0;
} else {
-
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
@@ -444,8 +439,9 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
List<String> mstring;
for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().name.begins_with("_"))
+ if (E->get().name.begins_with("_")) {
continue;
+ }
mstring.push_back(E->get().name.get_slice(":", 0));
}
@@ -453,9 +449,9 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
String ml;
for (List<String>::Element *E = mstring.front(); E; E = E->next()) {
-
- if (ml != String())
+ if (ml != String()) {
ml += ",";
+ }
ml += E->get();
}
@@ -464,7 +460,6 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
}
void VisualScriptYieldSignal::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptYieldSignal::set_base_type);
ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptYieldSignal::get_base_type);
@@ -479,8 +474,9 @@ void VisualScriptYieldSignal::_bind_methods() {
String bt;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i > 0)
+ if (i > 0) {
bt += ",";
+ }
bt += Variant::get_type_name(Variant::Type(i));
}
@@ -510,7 +506,6 @@ public:
//virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; }
virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) {
-
if (p_start_mode == START_MODE_RESUME_YIELD) {
return 0; //resuming yield
} else {
@@ -519,14 +514,11 @@ public:
Object *object = nullptr;
switch (call_mode) {
-
case VisualScriptYieldSignal::CALL_MODE_SELF: {
-
object = instance->get_owner_ptr();
} break;
case VisualScriptYieldSignal::CALL_MODE_NODE_PATH: {
-
Node *node = Object::cast_to<Node>(instance->get_owner_ptr());
if (!node) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -545,7 +537,6 @@ public:
} break;
case VisualScriptYieldSignal::CALL_MODE_INSTANCE: {
-
object = *p_inputs[0];
if (!object) {
r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
@@ -569,7 +560,6 @@ public:
};
VisualScriptNodeInstance *VisualScriptYieldSignal::instance(VisualScriptInstance *p_instance) {
-
VisualScriptNodeInstanceYieldSignal *instance = memnew(VisualScriptNodeInstanceYieldSignal);
instance->node = this;
instance->instance = p_instance;
@@ -579,15 +569,14 @@ VisualScriptNodeInstance *VisualScriptYieldSignal::instance(VisualScriptInstance
instance->output_args = get_output_value_port_count();
return instance;
}
-VisualScriptYieldSignal::VisualScriptYieldSignal() {
+VisualScriptYieldSignal::VisualScriptYieldSignal() {
call_mode = CALL_MODE_SELF;
base_type = "Object";
}
template <VisualScriptYieldSignal::CallMode cmode>
static Ref<VisualScriptNode> create_yield_signal_node(const String &p_name) {
-
Ref<VisualScriptYieldSignal> node;
node.instance();
node->set_call_mode(cmode);
@@ -595,7 +584,6 @@ static Ref<VisualScriptNode> create_yield_signal_node(const String &p_name) {
}
void register_visual_script_yield_nodes() {
-
VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_frame", create_yield_node<VisualScriptYield::YIELD_FRAME>);
VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_physics_frame", create_yield_node<VisualScriptYield::YIELD_PHYSICS_FRAME>);
VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_time", create_yield_node<VisualScriptYield::YIELD_WAIT>);
diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h
index 4b976bd6c6..cc7ce0a1c6 100644
--- a/modules/visual_script/visual_script_yield_nodes.h
+++ b/modules/visual_script/visual_script_yield_nodes.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "visual_script.h"
class VisualScriptYield : public VisualScriptNode {
-
GDCLASS(VisualScriptYield, VisualScriptNode);
public:
@@ -51,25 +50,25 @@ private:
float wait_time;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
void set_yield_mode(YieldMode p_mode);
YieldMode get_yield_mode();
@@ -77,14 +76,13 @@ public:
void set_wait_time(float p_time);
float get_wait_time();
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptYield();
};
VARIANT_ENUM_CAST(VisualScriptYield::YieldMode)
class VisualScriptYieldSignal : public VisualScriptNode {
-
GDCLASS(VisualScriptYieldSignal, VisualScriptNode);
public:
@@ -105,25 +103,25 @@ private:
StringName _get_base_type() const;
protected:
- virtual void _validate_property(PropertyInfo &property) const;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
public:
- virtual int get_output_sequence_port_count() const;
- virtual bool has_input_sequence_port() const;
+ virtual int get_output_sequence_port_count() const override;
+ virtual bool has_input_sequence_port() const override;
- virtual String get_output_sequence_port_text(int p_port) const;
+ virtual String get_output_sequence_port_text(int p_port) const override;
- virtual int get_input_value_port_count() const;
- virtual int get_output_value_port_count() const;
+ virtual int get_input_value_port_count() const override;
+ virtual int get_output_value_port_count() const override;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const override;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const override;
- virtual String get_caption() const;
- virtual String get_text() const;
- virtual String get_category() const { return "functions"; }
+ virtual String get_caption() const override;
+ virtual String get_text() const override;
+ virtual String get_category() const override { return "functions"; }
void set_base_type(const StringName &p_type);
StringName get_base_type() const;
@@ -137,7 +135,7 @@ public:
void set_call_mode(CallMode p_mode);
CallMode get_call_mode() const;
- virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override;
VisualScriptYieldSignal();
};
diff --git a/modules/vorbis/SCsub b/modules/vorbis/SCsub
index 05d46757d3..bc31fff066 100644
--- a/modules/vorbis/SCsub
+++ b/modules/vorbis/SCsub
@@ -8,9 +8,10 @@ Import("env_modules")
env_vorbis = env_modules.Clone()
-stub = True
-
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_libvorbis"]:
thirdparty_dir = "#thirdparty/libvorbis/"
thirdparty_sources = [
@@ -51,7 +52,16 @@ if env["builtin_libvorbis"]:
env_thirdparty = env_vorbis.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_vorbis.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
-# Module files
-env_vorbis.add_source_files(env.modules_sources, "register_types.cpp")
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/vorbis/config.py b/modules/vorbis/config.py
index d22f9454ed..8a384e3066 100644
--- a/modules/vorbis/config.py
+++ b/modules/vorbis/config.py
@@ -1,5 +1,5 @@
def can_build(env, platform):
- return True
+ return env.module_check_dependencies("vorbis", ["ogg"])
def configure(env):
diff --git a/modules/vorbis/register_types.cpp b/modules/vorbis/register_types.cpp
index 8874b3887b..d3e77ea629 100644
--- a/modules/vorbis/register_types.cpp
+++ b/modules/vorbis/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/vorbis/register_types.h b/modules/vorbis/register_types.h
index 7fa0dfdeef..1497e6f5e4 100644
--- a/modules/vorbis/register_types.h
+++ b/modules/vorbis/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webm/SCsub b/modules/webm/SCsub
index 247b4ead37..44e80e2870 100644
--- a/modules/webm/SCsub
+++ b/modules/webm/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_webm = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
thirdparty_dir = "#thirdparty/libsimplewebm/"
thirdparty_sources = [
"libwebm/mkvparser/mkvparser.cc",
@@ -31,7 +34,15 @@ if env["builtin_libvpx"]:
env_thirdparty = env_webm.Clone()
env_thirdparty.disable_warnings()
-env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+env.modules_sources += thirdparty_obj
# Godot source files
-env_webm.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_webm.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/webm/config.py b/modules/webm/config.py
index 93b49d177a..99f8ace114 100644
--- a/modules/webm/config.py
+++ b/modules/webm/config.py
@@ -1,5 +1,8 @@
def can_build(env, platform):
- return platform not in ["iphone"]
+ if platform in ["iphone"]:
+ return False
+
+ return env.module_check_dependencies("webm", ["ogg", "opus", "vorbis"])
def configure(env):
diff --git a/modules/webm/doc_classes/VideoStreamWebm.xml b/modules/webm/doc_classes/VideoStreamWebm.xml
index dfa04720cf..f3e13ba31a 100644
--- a/modules/webm/doc_classes/VideoStreamWebm.xml
+++ b/modules/webm/doc_classes/VideoStreamWebm.xml
@@ -4,7 +4,9 @@
[VideoStream] resource for WebM videos.
</brief_description>
<description>
- [VideoStream] resource handling the [url=https://www.webmproject.org/]WebM[/url] video format with [code].webm[/code] extension.
+ [VideoStream] resource handling the [url=https://www.webmproject.org/]WebM[/url] video format with [code].webm[/code] extension. Both the VP8 and VP9 codecs are supported. The VP8 and VP9 codecs are more efficient than [VideoStreamTheora], but they require more CPU resources to decode (especially VP9). Both the VP8 and VP9 codecs are decoded on the CPU.
+ [b]Note:[/b] Alpha channel (also known as transparency) is not supported. The video will always appear to have a black background, even if it originally contains an alpha channel.
+ [b]Note:[/b] There are known bugs and performance issues with WebM video playback in Godot. If you run into problems, try using the Ogg Theora format instead: [VideoStreamTheora]
</description>
<tutorials>
</tutorials>
diff --git a/modules/webm/libvpx/SCsub b/modules/webm/libvpx/SCsub
index dd6866ad0e..67d3f1bebd 100644
--- a/modules/webm/libvpx/SCsub
+++ b/modules/webm/libvpx/SCsub
@@ -238,6 +238,7 @@ else:
is_x11_or_server_arm = (env["platform"] == "linuxbsd" or env["platform"] == "server") and (
platform.machine().startswith("arm") or platform.machine().startswith("aarch")
)
+ is_macos_x86 = env["platform"] == "osx" and ("arch" in env and (env["arch"] != "arm64"))
is_ios_x86 = env["platform"] == "iphone" and ("arch" in env and env["arch"].startswith("x86"))
is_android_x86 = env["platform"] == "android" and env["android_arch"].startswith("x86")
if is_android_x86:
@@ -248,14 +249,15 @@ else:
and (
env["platform"] == "windows"
or env["platform"] == "linuxbsd"
- or env["platform"] == "osx"
or env["platform"] == "haiku"
+ or is_macos_x86
or is_android_x86
or is_ios_x86
)
)
webm_cpu_arm = (
is_x11_or_server_arm
+ or (not is_macos_x86 and env["platform"] == "osx")
or (not is_ios_x86 and env["platform"] == "iphone")
or (not is_android_x86 and env["platform"] == "android")
)
@@ -276,7 +278,7 @@ if webm_cpu_x86:
try:
yasm_found = True
subprocess.Popen([yasm_path, "--version"], stdout=devnull, stderr=devnull).communicate()
- except:
+ except Exception:
yasm_found = False
if yasm_found:
break
diff --git a/modules/webm/register_types.cpp b/modules/webm/register_types.cpp
index 5449dd458c..82157a71c9 100644
--- a/modules/webm/register_types.cpp
+++ b/modules/webm/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
static Ref<ResourceFormatLoaderWebm> resource_loader_webm;
void register_webm_types() {
-
resource_loader_webm.instance();
ResourceLoader::add_resource_format_loader(resource_loader_webm, true);
@@ -43,7 +42,6 @@ void register_webm_types() {
}
void unregister_webm_types() {
-
ResourceLoader::remove_resource_format_loader(resource_loader_webm);
resource_loader_webm.unref();
}
diff --git a/modules/webm/register_types.h b/modules/webm/register_types.h
index 6a02e3a87a..d090fe745b 100644
--- a/modules/webm/register_types.h
+++ b/modules/webm/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp
index a2d0f78f5f..5d8245c64c 100644
--- a/modules/webm/video_stream_webm.cpp
+++ b/modules/webm/video_stream_webm.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,9 +30,9 @@
#include "video_stream_webm.h"
+#include "core/config/project_settings.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
#include "servers/audio_server.h"
#include "thirdparty/misc/yuv2rgb.h"
@@ -48,41 +48,39 @@
#include <mkvparser/mkvparser.h>
class MkvReader : public mkvparser::IMkvReader {
-
public:
MkvReader(const String &p_file) {
-
file = FileAccess::open(p_file, FileAccess::READ);
ERR_FAIL_COND_MSG(!file, "Failed loading resource: '" + p_file + "'.");
}
~MkvReader() {
-
- if (file)
+ if (file) {
memdelete(file);
+ }
}
virtual int Read(long long pos, long len, unsigned char *buf) {
-
if (file) {
-
- if (file->get_position() != (size_t)pos)
+ if (file->get_position() != (size_t)pos) {
file->seek(pos);
- if (file->get_buffer(buf, len) == len)
+ }
+ if (file->get_buffer(buf, len) == len) {
return 0;
+ }
}
return -1;
}
virtual int Length(long long *total, long long *available) {
-
if (file) {
-
const size_t len = file->get_len();
- if (total)
+ if (total) {
*total = len;
- if (available)
+ }
+ if (available) {
*available = len;
+ }
return 0;
}
return -1;
@@ -95,47 +93,23 @@ private:
/**/
VideoStreamPlaybackWebm::VideoStreamPlaybackWebm() :
- audio_track(0),
- webm(nullptr),
- video(nullptr),
- audio(nullptr),
- video_frames(nullptr),
- audio_frame(nullptr),
- video_frames_pos(0),
- video_frames_capacity(0),
- num_decoded_samples(0),
- samples_offset(-1),
- mix_callback(nullptr),
- mix_udata(nullptr),
- playing(false),
- paused(false),
- delay_compensation(0.0),
- time(0.0),
- video_frame_delay(0.0),
- video_pos(0.0),
- texture(memnew(ImageTexture)),
- pcm(nullptr) {}
-VideoStreamPlaybackWebm::~VideoStreamPlaybackWebm() {
+ texture(memnew(ImageTexture)) {}
+VideoStreamPlaybackWebm::~VideoStreamPlaybackWebm() {
delete_pointers();
}
bool VideoStreamPlaybackWebm::open_file(const String &p_file) {
-
file_name = p_file;
webm = memnew(WebMDemuxer(new MkvReader(file_name), 0, audio_track));
if (webm->isOpen()) {
-
video = memnew(VPXDecoder(*webm, OS::get_singleton()->get_processor_count()));
if (video->isOpen()) {
-
audio = memnew(OpusVorbisDecoder(*webm));
if (audio->isOpen()) {
-
audio_frame = memnew(WebMFrame);
pcm = (float *)memalloc(sizeof(float) * audio->getBufferSamples() * webm->getChannels());
} else {
-
memdelete(audio);
audio = nullptr;
}
@@ -157,9 +131,7 @@ bool VideoStreamPlaybackWebm::open_file(const String &p_file) {
}
void VideoStreamPlaybackWebm::stop() {
-
if (playing) {
-
delete_pointers();
pcm = nullptr;
@@ -180,8 +152,8 @@ void VideoStreamPlaybackWebm::stop() {
time = 0.0;
playing = false;
}
-void VideoStreamPlaybackWebm::play() {
+void VideoStreamPlaybackWebm::play() {
stop();
delay_compensation = ProjectSettings::get_singleton()->get("audio/video_delay_compensation_ms");
@@ -191,58 +163,52 @@ void VideoStreamPlaybackWebm::play() {
}
bool VideoStreamPlaybackWebm::is_playing() const {
-
return playing;
}
void VideoStreamPlaybackWebm::set_paused(bool p_paused) {
-
paused = p_paused;
}
-bool VideoStreamPlaybackWebm::is_paused() const {
+bool VideoStreamPlaybackWebm::is_paused() const {
return paused;
}
void VideoStreamPlaybackWebm::set_loop(bool p_enable) {
-
//Empty
}
-bool VideoStreamPlaybackWebm::has_loop() const {
+bool VideoStreamPlaybackWebm::has_loop() const {
return false;
}
float VideoStreamPlaybackWebm::get_length() const {
-
- if (webm)
+ if (webm) {
return webm->getLength();
+ }
return 0.0f;
}
float VideoStreamPlaybackWebm::get_playback_position() const {
-
return video_pos;
}
-void VideoStreamPlaybackWebm::seek(float p_time) {
+void VideoStreamPlaybackWebm::seek(float p_time) {
//Not implemented
}
void VideoStreamPlaybackWebm::set_audio_track(int p_idx) {
-
audio_track = p_idx;
}
Ref<Texture2D> VideoStreamPlaybackWebm::get_texture() const {
-
return texture;
}
void VideoStreamPlaybackWebm::update(float p_delta) {
-
- if ((!playing || paused) || !video)
+ if ((!playing || paused) || !video) {
return;
+ }
time += p_delta;
@@ -253,16 +219,13 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
bool audio_buffer_full = false;
if (samples_offset > -1) {
-
//Mix remaining samples
const int to_read = num_decoded_samples - samples_offset;
const int mixed = mix_callback(mix_udata, pcm + samples_offset * webm->getChannels(), to_read);
if (mixed != to_read) {
-
samples_offset += mixed;
audio_buffer_full = true;
} else {
-
samples_offset = -1;
}
}
@@ -270,10 +233,8 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
const bool hasAudio = (audio && mix_callback);
while ((hasAudio && !audio_buffer_full && !has_enough_video_frames()) ||
(!hasAudio && video_frames_pos == 0)) {
-
if (hasAudio && !audio_buffer_full && audio_frame->isValid() &&
audio->getPCMF(*audio_frame, pcm, num_decoded_samples) && num_decoded_samples > 0) {
-
const int mixed = mix_callback(mix_udata, pcm, num_decoded_samples);
if (mixed != num_decoded_samples) {
@@ -284,42 +245,37 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
WebMFrame *video_frame;
if (video_frames_pos >= video_frames_capacity) {
-
WebMFrame **video_frames_new = (WebMFrame **)memrealloc(video_frames, ++video_frames_capacity * sizeof(void *));
ERR_FAIL_COND(!video_frames_new); //Out of memory
(video_frames = video_frames_new)[video_frames_capacity - 1] = memnew(WebMFrame);
}
video_frame = video_frames[video_frames_pos];
- if (!webm->readFrame(video_frame, audio_frame)) //This will invalidate frames
+ if (!webm->readFrame(video_frame, audio_frame)) { //This will invalidate frames
break; //Can't demux, EOS?
+ }
- if (video_frame->isValid())
+ if (video_frame->isValid()) {
++video_frames_pos;
+ }
};
bool video_frame_done = false;
while (video_frames_pos > 0 && !video_frame_done) {
-
WebMFrame *video_frame = video_frames[0];
// It seems VPXDecoder::decode has to be executed even though we might skip this frame
if (video->decode(*video_frame)) {
-
VPXDecoder::IMAGE_ERROR err;
VPXDecoder::Image image;
if (should_process(*video_frame)) {
-
if ((err = video->getImage(image)) != VPXDecoder::NO_FRAME) {
-
if (err == VPXDecoder::NO_ERROR && image.w == webm->getWidth() && image.h == webm->getHeight()) {
-
uint8_t *w = frame_data.ptrw();
bool converted = false;
if (image.chromaShiftW == 0 && image.chromaShiftH == 0 && image.cs == VPX_CS_SRGB) {
-
uint8_t *wp = w;
unsigned char *rRow = image.planes[2];
unsigned char *gRow = image.planes[0];
@@ -337,22 +293,18 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
}
converted = true;
} else if (image.chromaShiftW == 1 && image.chromaShiftH == 1) {
-
yuv420_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
//libyuv::I420ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
converted = true;
} else if (image.chromaShiftW == 1 && image.chromaShiftH == 0) {
-
yuv422_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
//libyuv::I422ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
converted = true;
} else if (image.chromaShiftW == 0 && image.chromaShiftH == 0) {
-
yuv444_2_rgb8888(w, image.planes[0], image.planes[1], image.planes[2], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2);
//libyuv::I444ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2], image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
converted = true;
} else if (image.chromaShiftW == 2 && image.chromaShiftH == 0) {
-
//libyuv::I411ToARGB(image.planes[0], image.linesize[0], image.planes[2], image.linesize[2] image.planes[1], image.linesize[1], w.ptr(), image.w << 2, image.w, image.h);
//converted = true;
}
@@ -372,25 +324,27 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
video_frames[video_frames_pos] = video_frame;
}
- if (video_frames_pos == 0 && webm->isEOS())
+ if (video_frames_pos == 0 && webm->isEOS()) {
stop();
+ }
}
void VideoStreamPlaybackWebm::set_mix_callback(VideoStreamPlayback::AudioMixCallback p_callback, void *p_userdata) {
-
mix_callback = p_callback;
mix_udata = p_userdata;
}
-int VideoStreamPlaybackWebm::get_channels() const {
- if (audio)
+int VideoStreamPlaybackWebm::get_channels() const {
+ if (audio) {
return webm->getChannels();
+ }
return 0;
}
-int VideoStreamPlaybackWebm::get_mix_rate() const {
- if (audio)
+int VideoStreamPlaybackWebm::get_mix_rate() const {
+ if (audio) {
return webm->getSampleRate();
+ }
return 0;
}
@@ -415,52 +369,54 @@ bool VideoStreamPlaybackWebm::should_process(WebMFrame &video_frame) {
}
void VideoStreamPlaybackWebm::delete_pointers() {
-
- if (pcm)
+ if (pcm) {
memfree(pcm);
+ }
- if (audio_frame)
+ if (audio_frame) {
memdelete(audio_frame);
+ }
if (video_frames) {
- for (int i = 0; i < video_frames_capacity; ++i)
+ for (int i = 0; i < video_frames_capacity; ++i) {
memdelete(video_frames[i]);
+ }
memfree(video_frames);
}
- if (video)
+ if (video) {
memdelete(video);
- if (audio)
+ }
+ if (audio) {
memdelete(audio);
+ }
- if (webm)
+ if (webm) {
memdelete(webm);
+ }
}
/**/
-VideoStreamWebm::VideoStreamWebm() :
- audio_track(0) {}
+VideoStreamWebm::VideoStreamWebm() {}
Ref<VideoStreamPlayback> VideoStreamWebm::instance_playback() {
-
Ref<VideoStreamPlaybackWebm> pb = memnew(VideoStreamPlaybackWebm);
pb->set_audio_track(audio_track);
- if (pb->open_file(file))
+ if (pb->open_file(file)) {
return pb;
+ }
return nullptr;
}
void VideoStreamWebm::set_file(const String &p_file) {
-
file = p_file;
}
-String VideoStreamWebm::get_file() {
+String VideoStreamWebm::get_file() {
return file;
}
void VideoStreamWebm::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStreamWebm::set_file);
ClassDB::bind_method(D_METHOD("get_file"), &VideoStreamWebm::get_file);
@@ -468,14 +424,12 @@ void VideoStreamWebm::_bind_methods() {
}
void VideoStreamWebm::set_audio_track(int p_track) {
-
audio_track = p_track;
}
////////////
RES ResourceFormatLoaderWebm::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
-
FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
if (r_error) {
@@ -499,19 +453,17 @@ RES ResourceFormatLoaderWebm::load(const String &p_path, const String &p_origina
}
void ResourceFormatLoaderWebm::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("webm");
}
bool ResourceFormatLoaderWebm::handles_type(const String &p_type) const {
-
return ClassDB::is_parent_class(p_type, "VideoStream");
}
String ResourceFormatLoaderWebm::get_resource_type(const String &p_path) const {
-
String el = p_path.get_extension().to_lower();
- if (el == "webm")
+ if (el == "webm") {
return "VideoStreamWebm";
+ }
return "";
}
diff --git a/modules/webm/video_stream_webm.h b/modules/webm/video_stream_webm.h
index 6677fb85aa..cb3cf58850 100644
--- a/modules/webm/video_stream_webm.h
+++ b/modules/webm/video_stream_webm.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -40,31 +40,30 @@ class VPXDecoder;
class OpusVorbisDecoder;
class VideoStreamPlaybackWebm : public VideoStreamPlayback {
-
GDCLASS(VideoStreamPlaybackWebm, VideoStreamPlayback);
String file_name;
- int audio_track;
+ int audio_track = 0;
- WebMDemuxer *webm;
- VPXDecoder *video;
- OpusVorbisDecoder *audio;
+ WebMDemuxer *webm = nullptr;
+ VPXDecoder *video = nullptr;
+ OpusVorbisDecoder *audio = nullptr;
- WebMFrame **video_frames, *audio_frame;
- int video_frames_pos, video_frames_capacity;
+ WebMFrame **video_frames = nullptr, *audio_frame = nullptr;
+ int video_frames_pos = 0, video_frames_capacity = 0;
- int num_decoded_samples, samples_offset;
- AudioMixCallback mix_callback;
- void *mix_udata;
+ int num_decoded_samples = 0, samples_offset = -1;
+ AudioMixCallback mix_callback = nullptr;
+ void *mix_udata = nullptr;
- bool playing, paused;
- double delay_compensation;
- double time, video_frame_delay, video_pos;
+ bool playing = false, paused = false;
+ double delay_compensation = 0.0;
+ double time = 0.0, video_frame_delay = 0.0, video_pos = 0.0;
Vector<uint8_t> frame_data;
Ref<ImageTexture> texture;
- float *pcm;
+ float *pcm = nullptr;
public:
VideoStreamPlaybackWebm();
@@ -72,30 +71,30 @@ public:
bool open_file(const String &p_file);
- virtual void stop();
- virtual void play();
+ virtual void stop() override;
+ virtual void play() override;
- virtual bool is_playing() const;
+ virtual bool is_playing() const override;
- virtual void set_paused(bool p_paused);
- virtual bool is_paused() const;
+ virtual void set_paused(bool p_paused) override;
+ virtual bool is_paused() const override;
- virtual void set_loop(bool p_enable);
- virtual bool has_loop() const;
+ virtual void set_loop(bool p_enable) override;
+ virtual bool has_loop() const override;
- virtual float get_length() const;
+ virtual float get_length() const override;
- virtual float get_playback_position() const;
- virtual void seek(float p_time);
+ virtual float get_playback_position() const override;
+ virtual void seek(float p_time) override;
- virtual void set_audio_track(int p_idx);
+ virtual void set_audio_track(int p_idx) override;
- virtual Ref<Texture2D> get_texture() const;
- virtual void update(float p_delta);
+ virtual Ref<Texture2D> get_texture() const override;
+ virtual void update(float p_delta) override;
- virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata);
- virtual int get_channels() const;
- virtual int get_mix_rate() const;
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) override;
+ virtual int get_channels() const override;
+ virtual int get_mix_rate() const override;
private:
inline bool has_enough_video_frames() const;
@@ -107,11 +106,10 @@ private:
/**/
class VideoStreamWebm : public VideoStream {
-
GDCLASS(VideoStreamWebm, VideoStream);
String file;
- int audio_track;
+ int audio_track = 0;
protected:
static void _bind_methods();
@@ -119,11 +117,11 @@ protected:
public:
VideoStreamWebm();
- virtual Ref<VideoStreamPlayback> instance_playback();
+ virtual Ref<VideoStreamPlayback> instance_playback() override;
virtual void set_file(const String &p_file);
String get_file();
- virtual void set_audio_track(int p_track);
+ virtual void set_audio_track(int p_track) override;
};
class ResourceFormatLoaderWebm : public ResourceFormatLoader {
diff --git a/modules/webp/SCsub b/modules/webp/SCsub
index 58f2bb35e6..4c0c2f7893 100644
--- a/modules/webp/SCsub
+++ b/modules/webp/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_webp = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_libwebp"]:
thirdparty_dir = "#thirdparty/libwebp/"
thirdparty_sources = [
@@ -130,7 +133,16 @@ if env["builtin_libwebp"]:
env_thirdparty = env_webp.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_webp.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_webp.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp
index 0998977bb4..b304c4824f 100644
--- a/modules/webp/image_loader_webp.cpp
+++ b/modules/webp/image_loader_webp.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,21 +32,21 @@
#include "core/io/marshalls.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include <stdlib.h>
#include <webp/decode.h>
#include <webp/encode.h>
static Vector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_quality) {
-
- ERR_FAIL_COND_V(p_image.is_null() || p_image->empty(), Vector<uint8_t>());
+ ERR_FAIL_COND_V(p_image.is_null() || p_image->is_empty(), Vector<uint8_t>());
Ref<Image> img = p_image->duplicate();
- if (img->detect_alpha())
+ if (img->detect_alpha()) {
img->convert(Image::FORMAT_RGBA8);
- else
+ } else {
img->convert(Image::FORMAT_RGB8);
+ }
Size2 s(img->get_width(), img->get_height());
Vector<uint8_t> data = img->get_data();
@@ -55,7 +55,6 @@ static Vector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_quali
uint8_t *dst_buff = nullptr;
size_t dst_size = 0;
if (img->get_format() == Image::FORMAT_RGB8) {
-
dst_size = WebPEncodeRGB(r, s.width, s.height, 3 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff);
} else {
dst_size = WebPEncodeRGBA(r, s.width, s.height, 4 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff);
@@ -76,7 +75,6 @@ static Vector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_quali
}
static Ref<Image> _webp_lossy_unpack(const Vector<uint8_t> &p_buffer) {
-
int size = p_buffer.size() - 4;
ERR_FAIL_COND_V(size <= 0, Ref<Image>());
const uint8_t *r = p_buffer.ptr();
@@ -113,7 +111,6 @@ static Ref<Image> _webp_lossy_unpack(const Vector<uint8_t> &p_buffer) {
}
Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p_buffer_len) {
-
ERR_FAIL_NULL_V(p_image, ERR_INVALID_PARAMETER);
WebPBitstreamFeatures features;
@@ -135,13 +132,12 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
ERR_FAIL_COND_V_MSG(errdec, ERR_FILE_CORRUPT, "Failed decoding WebP image.");
- p_image->create(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
+ p_image->create(features.width, features.height, false, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
return OK;
}
static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) {
-
Ref<Image> img;
img.instance();
Error err = webp_load_image_from_buffer(img.ptr(), p_png, p_size);
@@ -150,7 +146,6 @@ static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) {
}
Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) {
-
Vector<uint8_t> src_image;
int src_image_len = f->get_len();
ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT);
@@ -168,7 +163,6 @@ Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_forc
}
void ImageLoaderWEBP::get_recognized_extensions(List<String> *p_extensions) const {
-
p_extensions->push_back("webp");
}
diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h
index 9206ca2525..9ea3056a19 100644
--- a/modules/webp/image_loader_webp.h
+++ b/modules/webp/image_loader_webp.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/io/image_loader.h"
class ImageLoaderWEBP : public ImageFormatLoader {
-
public:
virtual Error load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/webp/register_types.cpp b/modules/webp/register_types.cpp
index fe945b01d4..ea9af72418 100644
--- a/modules/webp/register_types.cpp
+++ b/modules/webp/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,12 +35,10 @@
static ImageLoaderWEBP *image_loader_webp = nullptr;
void register_webp_types() {
-
image_loader_webp = memnew(ImageLoaderWEBP);
ImageLoader::add_image_format_loader(image_loader_webp);
}
void unregister_webp_types() {
-
memdelete(image_loader_webp);
}
diff --git a/modules/webp/register_types.h b/modules/webp/register_types.h
index d574d7be1d..59d6894bf6 100644
--- a/modules/webp/register_types.h
+++ b/modules/webp/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webrtc/SCsub b/modules/webrtc/SCsub
index 20b4c8f8d2..31b8a73bf2 100644
--- a/modules/webrtc/SCsub
+++ b/modules/webrtc/SCsub
@@ -3,8 +3,6 @@
Import("env")
Import("env_modules")
-# Thirdparty source files
-
env_webrtc = env_modules.Clone()
use_gdnative = env_webrtc["module_gdnative_enabled"]
@@ -12,4 +10,8 @@ if use_gdnative: # GDNative is retained in Javascript for export compatibility
env_webrtc.Append(CPPDEFINES=["WEBRTC_GDNATIVE_ENABLED"])
env_webrtc.Prepend(CPPPATH=["#modules/gdnative/include/"])
+if env["platform"] == "javascript":
+ # Our JavaScript/C++ interface.
+ env.AddJSLibraries(["library_godot_webrtc.js"])
+
env_webrtc.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
index 504b4705d8..e21dee8eff 100644
--- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
+++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
@@ -40,7 +40,6 @@
<argument index="0" name="label" type="String">
</argument>
<argument index="1" name="options" type="Dictionary" default="{
-
}">
</argument>
<description>
@@ -82,7 +81,6 @@
<return type="int" enum="Error">
</return>
<argument index="0" name="configuration" type="Dictionary" default="{
-
}">
</argument>
<description>
@@ -97,7 +95,7 @@
{
"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.
+ "credential": "a_password", # Optional password for the TURN server.
}
]
}
@@ -120,7 +118,7 @@
</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].
+ After calling this function the peer will start emitting [signal ice_candidate_created] (unless an [enum Error] different from [constant OK] is returned).
</description>
</method>
<method name="set_remote_description">
diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js
new file mode 100644
index 0000000000..404a116716
--- /dev/null
+++ b/modules/webrtc/library_godot_webrtc.js
@@ -0,0 +1,433 @@
+/*************************************************************************/
+/* library_godot_webrtc.js */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+const GodotRTCDataChannel = {
+ // Our socket implementation that forwards events to C++.
+ $GodotRTCDataChannel__deps: ['$IDHandler', '$GodotRuntime'],
+ $GodotRTCDataChannel: {
+ connect: function (p_id, p_on_open, p_on_message, p_on_error, p_on_close) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+
+ ref.binaryType = 'arraybuffer';
+ ref.onopen = function (event) {
+ p_on_open();
+ };
+ ref.onclose = function (event) {
+ p_on_close();
+ };
+ ref.onerror = function (event) {
+ p_on_error();
+ };
+ ref.onmessage = function (event) {
+ let buffer;
+ let is_string = 0;
+ if (event.data instanceof ArrayBuffer) {
+ buffer = new Uint8Array(event.data);
+ } else if (event.data instanceof Blob) {
+ GodotRuntime.error('Blob type not supported');
+ return;
+ } else if (typeof event.data === 'string') {
+ is_string = 1;
+ const enc = new TextEncoder('utf-8');
+ buffer = new Uint8Array(enc.encode(event.data));
+ } else {
+ GodotRuntime.error('Unknown message type');
+ return;
+ }
+ const len = buffer.length * buffer.BYTES_PER_ELEMENT;
+ const out = GodotRuntime.malloc(len);
+ HEAPU8.set(buffer, out);
+ p_on_message(out, len, is_string);
+ GodotRuntime.free(out);
+ };
+ },
+
+ close: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ ref.onopen = null;
+ ref.onmessage = null;
+ ref.onerror = null;
+ ref.onclose = null;
+ ref.close();
+ },
+
+ get_prop: function (p_id, p_prop, p_def) {
+ const ref = IDHandler.get(p_id);
+ return (ref && ref[p_prop] !== undefined) ? ref[p_prop] : p_def;
+ },
+ },
+
+ godot_js_rtc_datachannel_ready_state_get__sig: 'ii',
+ godot_js_rtc_datachannel_ready_state_get: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return 3; // CLOSED
+ }
+
+ switch (ref.readyState) {
+ case 'connecting':
+ return 0;
+ case 'open':
+ return 1;
+ case 'closing':
+ return 2;
+ case 'closed':
+ default:
+ return 3;
+ }
+ },
+
+ godot_js_rtc_datachannel_send__sig: 'iiiii',
+ godot_js_rtc_datachannel_send: function (p_id, p_buffer, p_length, p_raw) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return 1;
+ }
+
+ const bytes_array = new Uint8Array(p_length);
+ for (let i = 0; i < p_length; i++) {
+ bytes_array[i] = GodotRuntime.getHeapValue(p_buffer + i, 'i8');
+ }
+
+ if (p_raw) {
+ ref.send(bytes_array.buffer);
+ } else {
+ const string = new TextDecoder('utf-8').decode(bytes_array);
+ ref.send(string);
+ }
+ return 0;
+ },
+
+ godot_js_rtc_datachannel_is_ordered__sig: 'ii',
+ godot_js_rtc_datachannel_is_ordered: function (p_id) {
+ return IDHandler.get_prop(p_id, 'ordered', true);
+ },
+
+ godot_js_rtc_datachannel_id_get__sig: 'ii',
+ godot_js_rtc_datachannel_id_get: function (p_id) {
+ return IDHandler.get_prop(p_id, 'id', 65535);
+ },
+
+ godot_js_rtc_datachannel_max_packet_lifetime_get__sig: 'ii',
+ godot_js_rtc_datachannel_max_packet_lifetime_get: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return 65535;
+ }
+ if (ref['maxPacketLifeTime'] !== undefined) {
+ return ref['maxPacketLifeTime'];
+ } else if (ref['maxRetransmitTime'] !== undefined) {
+ // Guess someone didn't appreciate the standardization process.
+ return ref['maxRetransmitTime'];
+ }
+ return 65535;
+ },
+
+ godot_js_rtc_datachannel_max_retransmits_get__sig: 'ii',
+ godot_js_rtc_datachannel_max_retransmits_get: function (p_id) {
+ return IDHandler.get_prop(p_id, 'maxRetransmits', 65535);
+ },
+
+ godot_js_rtc_datachannel_is_negotiated__sig: 'ii',
+ godot_js_rtc_datachannel_is_negotiated: function (p_id) {
+ return IDHandler.get_prop(p_id, 'negotiated', 65535);
+ },
+
+ godot_js_rtc_datachannel_label_get__sig: 'ii',
+ godot_js_rtc_datachannel_label_get: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref || !ref.label) {
+ return 0;
+ }
+ return GodotRuntime.allocString(ref.label);
+ },
+
+ godot_js_rtc_datachannel_protocol_get__sig: 'ii',
+ godot_js_rtc_datachannel_protocol_get: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref || !ref.protocol) {
+ return 0;
+ }
+ return GodotRuntime.allocString(ref.protocol);
+ },
+
+ godot_js_rtc_datachannel_destroy__sig: 'vi',
+ godot_js_rtc_datachannel_destroy: function (p_id) {
+ GodotRTCDataChannel.close(p_id);
+ IDHandler.remove(p_id);
+ },
+
+ godot_js_rtc_datachannel_connect__sig: 'viiiiii',
+ godot_js_rtc_datachannel_connect: function (p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) {
+ const onopen = GodotRuntime.get_func(p_on_open).bind(null, p_ref);
+ const onmessage = GodotRuntime.get_func(p_on_message).bind(null, p_ref);
+ const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_ref);
+ const onclose = GodotRuntime.get_func(p_on_close).bind(null, p_ref);
+ GodotRTCDataChannel.connect(p_id, onopen, onmessage, onerror, onclose);
+ },
+
+ godot_js_rtc_datachannel_close__sig: 'vi',
+ godot_js_rtc_datachannel_close: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ GodotRTCDataChannel.close(p_id);
+ },
+};
+
+autoAddDeps(GodotRTCDataChannel, '$GodotRTCDataChannel');
+mergeInto(LibraryManager.library, GodotRTCDataChannel);
+
+const GodotRTCPeerConnection = {
+ $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'],
+ $GodotRTCPeerConnection: {
+ onstatechange: function (p_id, p_conn, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ let state;
+ switch (p_conn.iceConnectionState) {
+ case 'new':
+ state = 0;
+ break;
+ case 'checking':
+ state = 1;
+ break;
+ case 'connected':
+ case 'completed':
+ state = 2;
+ break;
+ case 'disconnected':
+ state = 3;
+ break;
+ case 'failed':
+ state = 4;
+ break;
+ case 'closed':
+ default:
+ state = 5;
+ break;
+ }
+ callback(state);
+ },
+
+ onicecandidate: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref || !event.candidate) {
+ return;
+ }
+
+ const c = event.candidate;
+ const candidate_str = GodotRuntime.allocString(c.candidate);
+ const mid_str = GodotRuntime.allocString(c.sdpMid);
+ callback(mid_str, c.sdpMLineIndex, candidate_str);
+ GodotRuntime.free(candidate_str);
+ GodotRuntime.free(mid_str);
+ },
+
+ ondatachannel: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+
+ const cid = IDHandler.add(event.channel);
+ callback(cid);
+ },
+
+ onsession: function (p_id, callback, session) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ const type_str = GodotRuntime.allocString(session.type);
+ const sdp_str = GodotRuntime.allocString(session.sdp);
+ callback(type_str, sdp_str);
+ GodotRuntime.free(type_str);
+ GodotRuntime.free(sdp_str);
+ },
+
+ onerror: function (p_id, callback, error) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ GodotRuntime.error(error);
+ callback();
+ },
+ },
+
+ godot_js_rtc_pc_create__sig: 'iiiiii',
+ godot_js_rtc_pc_create: function (p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) {
+ const onstatechange = GodotRuntime.get_func(p_on_state_change).bind(null, p_ref);
+ const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref);
+ const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref);
+
+ const config = JSON.parse(GodotRuntime.parseString(p_config));
+ let conn = null;
+ try {
+ conn = new RTCPeerConnection(config);
+ } catch (e) {
+ GodotRuntime.error(e);
+ return 0;
+ }
+
+ const base = GodotRTCPeerConnection;
+ const id = IDHandler.add(conn);
+ conn.oniceconnectionstatechange = base.onstatechange.bind(null, id, conn, onstatechange);
+ conn.onicecandidate = base.onicecandidate.bind(null, id, oncandidate);
+ conn.ondatachannel = base.ondatachannel.bind(null, id, ondatachannel);
+ return id;
+ },
+
+ godot_js_rtc_pc_close__sig: 'vi',
+ godot_js_rtc_pc_close: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ ref.close();
+ },
+
+ godot_js_rtc_pc_destroy__sig: 'vi',
+ godot_js_rtc_pc_destroy: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ ref.oniceconnectionstatechange = null;
+ ref.onicecandidate = null;
+ ref.ondatachannel = null;
+ IDHandler.remove(p_id);
+ },
+
+ godot_js_rtc_pc_offer_create__sig: 'viiii',
+ godot_js_rtc_pc_offer_create: function (p_id, p_obj, p_on_session, p_on_error) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ const onsession = GodotRuntime.get_func(p_on_session).bind(null, p_obj);
+ const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
+ ref.createOffer().then(function (session) {
+ GodotRTCPeerConnection.onsession(p_id, onsession, session);
+ }).catch(function (error) {
+ GodotRTCPeerConnection.onerror(p_id, onerror, error);
+ });
+ },
+
+ godot_js_rtc_pc_local_description_set__sig: 'viiiii',
+ godot_js_rtc_pc_local_description_set: function (p_id, p_type, p_sdp, p_obj, p_on_error) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ const type = GodotRuntime.parseString(p_type);
+ const sdp = GodotRuntime.parseString(p_sdp);
+ const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
+ ref.setLocalDescription({
+ 'sdp': sdp,
+ 'type': type,
+ }).catch(function (error) {
+ GodotRTCPeerConnection.onerror(p_id, onerror, error);
+ });
+ },
+
+ godot_js_rtc_pc_remote_description_set__sig: 'viiiiii',
+ godot_js_rtc_pc_remote_description_set: function (p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ const type = GodotRuntime.parseString(p_type);
+ const sdp = GodotRuntime.parseString(p_sdp);
+ const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
+ const onsession = GodotRuntime.get_func(p_session_created).bind(null, p_obj);
+ ref.setRemoteDescription({
+ 'sdp': sdp,
+ 'type': type,
+ }).then(function () {
+ if (type !== 'offer') {
+ return Promise.resolve();
+ }
+ return ref.createAnswer().then(function (session) {
+ GodotRTCPeerConnection.onsession(p_id, onsession, session);
+ });
+ }).catch(function (error) {
+ GodotRTCPeerConnection.onerror(p_id, onerror, error);
+ });
+ },
+
+ godot_js_rtc_pc_ice_candidate_add__sig: 'viiii',
+ godot_js_rtc_pc_ice_candidate_add: function (p_id, p_mid_name, p_mline_idx, p_sdp) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ const sdpMidName = GodotRuntime.parseString(p_mid_name);
+ const sdpName = GodotRuntime.parseString(p_sdp);
+ ref.addIceCandidate(new RTCIceCandidate({
+ 'candidate': sdpName,
+ 'sdpMid': sdpMidName,
+ 'sdpMlineIndex': p_mline_idx,
+ }));
+ },
+
+ godot_js_rtc_pc_datachannel_create__deps: ['$GodotRTCDataChannel'],
+ godot_js_rtc_pc_datachannel_create__sig: 'iiii',
+ godot_js_rtc_pc_datachannel_create: function (p_id, p_label, p_config) {
+ try {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return 0;
+ }
+
+ const label = GodotRuntime.parseString(p_label);
+ const config = JSON.parse(GodotRuntime.parseString(p_config));
+
+ const channel = ref.createDataChannel(label, config);
+ return IDHandler.add(channel);
+ } catch (e) {
+ GodotRuntime.error(e);
+ return 0;
+ }
+ },
+};
+
+autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection');
+mergeInto(LibraryManager.library, GodotRTCPeerConnection);
diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp
index 5b296b1ac6..ecfaed9089 100644
--- a/modules/webrtc/register_types.cpp
+++ b/modules/webrtc/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,7 +29,7 @@
/*************************************************************************/
#include "register_types.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
#include "webrtc_data_channel.h"
#include "webrtc_peer_connection.h"
diff --git a/modules/webrtc/register_types.h b/modules/webrtc/register_types.h
index 8f5b9e8452..710ee88a28 100644
--- a/modules/webrtc/register_types.h
+++ b/modules/webrtc/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webrtc/webrtc_data_channel.cpp b/modules/webrtc/webrtc_data_channel.cpp
index 7566532982..004112f992 100644
--- a/modules/webrtc/webrtc_data_channel.cpp
+++ b/modules/webrtc/webrtc_data_channel.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,7 +29,7 @@
/*************************************************************************/
#include "webrtc_data_channel.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
void WebRTCDataChannel::_bind_methods() {
ClassDB::bind_method(D_METHOD("poll"), &WebRTCDataChannel::poll);
diff --git a/modules/webrtc/webrtc_data_channel.h b/modules/webrtc/webrtc_data_channel.h
index e61f786ca1..20affc513f 100644
--- a/modules/webrtc/webrtc_data_channel.h
+++ b/modules/webrtc/webrtc_data_channel.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -73,13 +73,6 @@ public:
virtual Error poll() = 0;
virtual void close() = 0;
- /** Inherited from PacketPeer: **/
- virtual int get_available_packet_count() const = 0;
- virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) = 0; ///< buffer is GONE after next get_packet
- virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0;
-
- virtual int get_max_packet_size() const = 0;
-
WebRTCDataChannel();
~WebRTCDataChannel();
};
diff --git a/modules/webrtc/webrtc_data_channel_gdnative.cpp b/modules/webrtc/webrtc_data_channel_gdnative.cpp
index 67ad2c07ce..d4cf464c7c 100644
--- a/modules/webrtc/webrtc_data_channel_gdnative.cpp
+++ b/modules/webrtc/webrtc_data_channel_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webrtc/webrtc_data_channel_gdnative.h b/modules/webrtc/webrtc_data_channel_gdnative.h
index be3ea13028..7e02a32046 100644
--- a/modules/webrtc/webrtc_data_channel_gdnative.h
+++ b/modules/webrtc/webrtc_data_channel_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,11 +28,11 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifdef WEBRTC_GDNATIVE_ENABLED
-
#ifndef WEBRTC_DATA_CHANNEL_GDNATIVE_H
#define WEBRTC_DATA_CHANNEL_GDNATIVE_H
+#ifdef WEBRTC_GDNATIVE_ENABLED
+
#include "modules/gdnative/include/net/godot_net.h"
#include "webrtc_data_channel.h"
@@ -48,33 +48,33 @@ private:
public:
void set_native_webrtc_data_channel(const godot_net_webrtc_data_channel *p_impl);
- virtual void set_write_mode(WriteMode mode);
- virtual WriteMode get_write_mode() const;
- virtual bool was_string_packet() const;
+ virtual void set_write_mode(WriteMode mode) override;
+ virtual WriteMode get_write_mode() const override;
+ virtual bool was_string_packet() const override;
- virtual ChannelState get_ready_state() const;
- virtual String get_label() const;
- virtual bool is_ordered() const;
- virtual int get_id() const;
- virtual int get_max_packet_life_time() const;
- virtual int get_max_retransmits() const;
- virtual String get_protocol() const;
- virtual bool is_negotiated() const;
+ virtual ChannelState get_ready_state() const override;
+ virtual String get_label() const override;
+ virtual bool is_ordered() const override;
+ virtual int get_id() const override;
+ virtual int get_max_packet_life_time() const override;
+ virtual int get_max_retransmits() const override;
+ virtual String get_protocol() const override;
+ virtual bool is_negotiated() const override;
- virtual Error poll();
- virtual void close();
+ virtual Error poll() override;
+ virtual void close() override;
/** Inherited from PacketPeer: **/
- virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
- virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+ virtual int get_available_packet_count() const override;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- virtual int get_max_packet_size() const;
+ virtual int get_max_packet_size() const override;
WebRTCDataChannelGDNative();
~WebRTCDataChannelGDNative();
};
-#endif // WEBRTC_DATA_CHANNEL_GDNATIVE_H
-
#endif // WEBRTC_GDNATIVE_ENABLED
+
+#endif // WEBRTC_DATA_CHANNEL_GDNATIVE_H
diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp
index 1b360720a2..9f2b084cb1 100644
--- a/modules/webrtc/webrtc_data_channel_js.cpp
+++ b/modules/webrtc/webrtc_data_channel_js.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,40 +34,43 @@
#include "emscripten.h"
extern "C" {
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_error(void *obj) {
- WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
- peer->_on_error();
-}
-
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_open(void *obj) {
- WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
- peer->_on_open();
-}
+typedef void (*RTCChOnOpen)(void *p_obj);
+typedef void (*RTCChOnMessage)(void *p_obj, const uint8_t *p_buffer, int p_size, int p_is_string);
+typedef void (*RTCChOnClose)(void *p_obj);
+typedef void (*RTCChOnError)(void *p_obj);
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_close(void *obj) {
- WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
- peer->_on_close();
-}
-
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_ch_message(void *obj, uint8_t *p_data, uint32_t p_size, bool p_is_string) {
- WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(obj);
- peer->_on_message(p_data, p_size, p_is_string);
-}
+extern int godot_js_rtc_datachannel_ready_state_get(int p_id);
+extern int godot_js_rtc_datachannel_send(int p_id, const uint8_t *p_buffer, int p_length, int p_raw);
+extern int godot_js_rtc_datachannel_is_ordered(int p_id);
+extern int godot_js_rtc_datachannel_id_get(int p_id);
+extern int godot_js_rtc_datachannel_max_packet_lifetime_get(int p_id);
+extern int godot_js_rtc_datachannel_max_retransmits_get(int p_id);
+extern int godot_js_rtc_datachannel_is_negotiated(int p_id);
+extern char *godot_js_rtc_datachannel_label_get(int p_id); // Must free the returned string.
+extern char *godot_js_rtc_datachannel_protocol_get(int p_id); // Must free the returned string.
+extern void godot_js_rtc_datachannel_destroy(int p_id);
+extern void godot_js_rtc_datachannel_connect(int p_id, void *p_obj, RTCChOnOpen p_on_open, RTCChOnMessage p_on_message, RTCChOnError p_on_error, RTCChOnClose p_on_close);
+extern void godot_js_rtc_datachannel_close(int p_id);
}
-void WebRTCDataChannelJS::_on_open() {
- in_buffer.resize(_in_buffer_shift);
+void WebRTCDataChannelJS::_on_open(void *p_obj) {
+ WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj);
+ peer->in_buffer.resize(peer->_in_buffer_shift);
}
-void WebRTCDataChannelJS::_on_close() {
- close();
+void WebRTCDataChannelJS::_on_close(void *p_obj) {
+ WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj);
+ peer->close();
}
-void WebRTCDataChannelJS::_on_error() {
- close();
+void WebRTCDataChannelJS::_on_error(void *p_obj) {
+ WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj);
+ peer->close();
}
-void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
+void WebRTCDataChannelJS::_on_message(void *p_obj, const uint8_t *p_data, int p_size, int p_is_string) {
+ WebRTCDataChannelJS *peer = static_cast<WebRTCDataChannelJS *>(p_obj);
+ RingBuffer<uint8_t> &in_buffer = peer->in_buffer;
ERR_FAIL_COND_MSG(in_buffer.space_left() < (int)(p_size + 5), "Buffer full! Dropping data.");
@@ -75,25 +78,14 @@ void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_i
in_buffer.write((uint8_t *)&p_size, 4);
in_buffer.write((uint8_t *)&is_string, 1);
in_buffer.write(p_data, p_size);
- queue_count++;
+ peer->queue_count++;
}
void WebRTCDataChannelJS::close() {
in_buffer.resize(0);
queue_count = 0;
_was_string = false;
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- if (!dict) return;
- var channel = dict["channel"];
- channel.onopen = null;
- channel.onclose = null;
- channel.onerror = null;
- channel.onmessage = null;
- channel.close();
- }, _js_id);
- /* clang-format on */
+ godot_js_rtc_datachannel_close(_js_id);
}
Error WebRTCDataChannelJS::poll() {
@@ -101,24 +93,7 @@ Error WebRTCDataChannelJS::poll() {
}
WebRTCDataChannelJS::ChannelState WebRTCDataChannelJS::get_ready_state() const {
- /* clang-format off */
- return (ChannelState) EM_ASM_INT({
- var dict = Module.IDHandler.get($0);
- if (!dict) return 3; // CLOSED
- var channel = dict["channel"];
- switch(channel.readyState) {
- case "connecting":
- return 0;
- case "open":
- return 1;
- case "closing":
- return 2;
- case "closed":
- return 3;
- }
- return 3; // CLOSED
- }, _js_id);
- /* clang-format on */
+ return (ChannelState)godot_js_rtc_datachannel_ready_state_get(_js_id);
}
int WebRTCDataChannelJS::get_available_packet_count() const {
@@ -158,27 +133,7 @@ Error WebRTCDataChannelJS::put_packet(const uint8_t *p_buffer, int p_buffer_size
ERR_FAIL_COND_V(get_ready_state() != STATE_OPEN, ERR_UNCONFIGURED);
int is_bin = _write_mode == WebRTCDataChannel::WRITE_MODE_BINARY ? 1 : 0;
-
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var channel = dict["channel"];
- var bytes_array = new Uint8Array($2);
- var i = 0;
-
- for(i=0; i<$2; i++) {
- bytes_array[i] = getValue($1+i, 'i8');
- }
-
- if ($3) {
- channel.send(bytes_array.buffer);
- } else {
- var string = new TextDecoder("utf-8").decode(bytes_array);
- channel.send(string);
- }
- }, _js_id, p_buffer, p_buffer_size, is_bin);
- /* clang-format on */
-
+ godot_js_rtc_datachannel_send(_js_id, p_buffer, p_buffer_size, is_bin);
return OK;
}
@@ -202,46 +157,20 @@ String WebRTCDataChannelJS::get_label() const {
return _label;
}
-/* clang-format off */
-#define _JS_GET(PROP, DEF) \
-EM_ASM_INT({ \
- var dict = Module.IDHandler.get($0); \
- if (!dict || !dict["channel"]) { \
- 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, true);
+ return godot_js_rtc_datachannel_is_ordered(_js_id);
}
int WebRTCDataChannelJS::get_id() const {
- return _JS_GET(id, 65535);
+ return godot_js_rtc_datachannel_id_get(_js_id);
}
int WebRTCDataChannelJS::get_max_packet_life_time() const {
- // 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 */
+ return godot_js_rtc_datachannel_max_packet_lifetime_get(_js_id);
}
int WebRTCDataChannelJS::get_max_retransmits() const {
- return _JS_GET(maxRetransmits, 65535);
+ return godot_js_rtc_datachannel_max_retransmits_get(_js_id);
}
String WebRTCDataChannelJS::get_protocol() const {
@@ -249,7 +178,7 @@ String WebRTCDataChannelJS::get_protocol() const {
}
bool WebRTCDataChannelJS::is_negotiated() const {
- return _JS_GET(negotiated, false);
+ return godot_js_rtc_datachannel_is_negotiated(_js_id);
}
WebRTCDataChannelJS::WebRTCDataChannelJS() {
@@ -265,101 +194,22 @@ WebRTCDataChannelJS::WebRTCDataChannelJS(int js_id) {
_write_mode = WRITE_MODE_BINARY;
_js_id = js_id;
- /* clang-format off */
- EM_ASM({
- var c_ptr = $0;
- var dict = Module.IDHandler.get($1);
- if (!dict) return;
- var channel = dict["channel"];
- dict["ptr"] = c_ptr;
-
- channel.binaryType = "arraybuffer";
- channel.onopen = function (evt) {
- ccall("_emrtc_on_ch_open",
- "void",
- ["number"],
- [c_ptr]
- );
- };
- channel.onclose = function (evt) {
- ccall("_emrtc_on_ch_close",
- "void",
- ["number"],
- [c_ptr]
- );
- };
- channel.onerror = function (evt) {
- ccall("_emrtc_on_ch_error",
- "void",
- ["number"],
- [c_ptr]
- );
- };
- channel.onmessage = function(event) {
- var buffer;
- var is_string = 0;
- if (event.data instanceof ArrayBuffer) {
- buffer = new Uint8Array(event.data);
- } else if (event.data instanceof Blob) {
- console.error("Blob type not supported");
- return;
- } else if (typeof event.data === "string") {
- is_string = 1;
- var enc = new TextEncoder("utf-8");
- buffer = new Uint8Array(enc.encode(event.data));
- } else {
- console.error("Unknown message type");
- return;
- }
- var len = buffer.length*buffer.BYTES_PER_ELEMENT;
- var out = Module._malloc(len);
- Module.HEAPU8.set(buffer, out);
- ccall("_emrtc_on_ch_message",
- "void",
- ["number", "number", "number", "number"],
- [c_ptr, out, len, is_string]
- );
- Module._free(out);
- }
-
- }, this, js_id);
+ godot_js_rtc_datachannel_connect(js_id, this, &_on_open, &_on_message, &_on_error, &_on_close);
// Parse label
- char *str;
- str = (char *)EM_ASM_INT({
- var dict = Module.IDHandler.get($0);
- if (!dict || !dict["channel"]) return 0;
- var str = dict["channel"].label;
- var len = lengthBytesUTF8(str)+1;
- var ptr = _malloc(str);
- stringToUTF8(str, ptr, len+1);
- return ptr;
- }, js_id);
- if(str != nullptr) {
- _label.parse_utf8(str);
- EM_ASM({ _free($0) }, str);
+ char *label = godot_js_rtc_datachannel_label_get(js_id);
+ if (label) {
+ _label.parse_utf8(label);
+ free(label);
}
- str = (char *)EM_ASM_INT({
- var dict = Module.IDHandler.get($0);
- if (!dict || !dict["channel"]) return 0;
- var str = dict["channel"].protocol;
- var len = lengthBytesUTF8(str)+1;
- var ptr = _malloc(str);
- stringToUTF8(str, ptr, len+1);
- return ptr;
- }, js_id);
- if(str != nullptr) {
- _protocol.parse_utf8(str);
- EM_ASM({ _free($0) }, str);
+ char *protocol = godot_js_rtc_datachannel_protocol_get(js_id);
+ if (protocol) {
+ _protocol.parse_utf8(protocol);
+ free(protocol);
}
- /* clang-format on */
}
WebRTCDataChannelJS::~WebRTCDataChannelJS() {
close();
- /* clang-format off */
- EM_ASM({
- Module.IDHandler.remove($0);
- }, _js_id);
- /* clang-format on */
-};
+ godot_js_rtc_datachannel_destroy(_js_id);
+}
#endif
diff --git a/modules/webrtc/webrtc_data_channel_js.h b/modules/webrtc/webrtc_data_channel_js.h
index 00b5963ea1..8c56b62303 100644
--- a/modules/webrtc/webrtc_data_channel_js.h
+++ b/modules/webrtc/webrtc_data_channel_js.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,11 +28,11 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifdef JAVASCRIPT_ENABLED
-
#ifndef WEBRTC_DATA_CHANNEL_JS_H
#define WEBRTC_DATA_CHANNEL_JS_H
+#ifdef JAVASCRIPT_ENABLED
+
#include "webrtc_data_channel.h"
class WebRTCDataChannelJS : public WebRTCDataChannel {
@@ -54,40 +54,40 @@ private:
int queue_count;
uint8_t packet_buffer[PACKET_BUFFER_SIZE];
+ static void _on_open(void *p_obj);
+ static void _on_close(void *p_obj);
+ static void _on_error(void *p_obj);
+ static void _on_message(void *p_obj, const uint8_t *p_data, int p_size, int p_is_string);
+
public:
- void _on_open();
- void _on_close();
- void _on_error();
- void _on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string);
-
- virtual void set_write_mode(WriteMode mode);
- virtual WriteMode get_write_mode() const;
- virtual bool was_string_packet() const;
-
- virtual ChannelState get_ready_state() const;
- virtual String get_label() const;
- virtual bool is_ordered() const;
- virtual int get_id() const;
- virtual int get_max_packet_life_time() const;
- virtual int get_max_retransmits() const;
- virtual String get_protocol() const;
- virtual bool is_negotiated() const;
-
- virtual Error poll();
- virtual void close();
+ virtual void set_write_mode(WriteMode mode) override;
+ virtual WriteMode get_write_mode() const override;
+ virtual bool was_string_packet() const override;
+
+ virtual ChannelState get_ready_state() const override;
+ virtual String get_label() const override;
+ virtual bool is_ordered() const override;
+ virtual int get_id() const override;
+ virtual int get_max_packet_life_time() const override;
+ virtual int get_max_retransmits() const override;
+ virtual String get_protocol() const override;
+ virtual bool is_negotiated() const override;
+
+ virtual Error poll() override;
+ virtual void close() override;
/** Inherited from PacketPeer: **/
- virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
- virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+ virtual int get_available_packet_count() const override;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- virtual int get_max_packet_size() const;
+ virtual int get_max_packet_size() const override;
WebRTCDataChannelJS();
WebRTCDataChannelJS(int js_id);
~WebRTCDataChannelJS();
};
-#endif // WEBRTC_DATA_CHANNEL_JS_H
-
#endif // JAVASCRIPT_ENABLED
+
+#endif // WEBRTC_DATA_CHANNEL_JS_H
diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp
index 78a4d1e61a..741cad5640 100644
--- a/modules/webrtc/webrtc_multiplayer.cpp
+++ b/modules/webrtc/webrtc_multiplayer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -65,8 +65,9 @@ bool WebRTCMultiplayer::is_server() const {
}
void WebRTCMultiplayer::poll() {
- if (peer_map.size() == 0)
+ if (peer_map.size() == 0) {
return;
+ }
List<int> remove;
List<int> add;
@@ -113,15 +114,17 @@ void WebRTCMultiplayer::poll() {
// Remove disconnected peers
for (List<int>::Element *E = remove.front(); E; E = E->next()) {
remove_peer(E->get());
- if (next_packet_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)
+ 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) {
@@ -131,20 +134,24 @@ void WebRTCMultiplayer::poll() {
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)
+ 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)
+ 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();
+ if (E) {
+ E = E->next();
+ }
// After last.
while (E) {
for (List<Ref<WebRTCDataChannel>>::Element *F = E->get()->channels.front(); F; F = F->next()) {
@@ -164,8 +171,9 @@ void WebRTCMultiplayer::_find_next_peer() {
return;
}
}
- if (E->key() == (int)next_packet_peer)
+ if (E->key() == (int)next_packet_peer) {
break;
+ }
E = E->next();
}
// No packet found
@@ -190,10 +198,11 @@ Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) {
server_compat = p_server_compat;
// Mesh and server are always connected
- if (!server_compat || p_self_id == 1)
+ if (!server_compat || p_self_id == 1) {
connection_status = CONNECTION_CONNECTED;
- else
+ } else {
connection_status = CONNECTION_CONNECTING;
+ }
return OK;
}
@@ -319,7 +328,6 @@ Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size)
Map<int, Ref<ConnectedPeer>>::Element *E = nullptr;
if (target_peer > 0) {
-
E = peer_map.find(target_peer);
ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
@@ -331,10 +339,10 @@ Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size)
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)
+ 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);
@@ -344,8 +352,9 @@ Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size)
}
int WebRTCMultiplayer::get_available_packet_count() const {
- if (next_packet_peer == 0)
+ 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()) {
diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer.h
index 0e1335b8a8..6b4ae6fcc8 100644
--- a/modules/webrtc/webrtc_multiplayer.h
+++ b/modules/webrtc/webrtc_multiplayer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,7 +35,6 @@
#include "webrtc_peer_connection.h"
class WebRTCMultiplayer : public NetworkedMultiplayerPeer {
-
GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer);
protected:
@@ -50,7 +49,6 @@ private:
};
class ConnectedPeer : public Reference {
-
public:
Ref<WebRTCPeerConnection> connection;
List<Ref<WebRTCDataChannel>> channels;
@@ -58,8 +56,9 @@ private:
ConnectedPeer() {
connected = false;
- for (int i = 0; i < CH_RESERVED_MAX; i++)
+ for (int i = 0; i < CH_RESERVED_MAX; i++) {
channels.push_front(Ref<WebRTCDataChannel>());
+ }
}
};
@@ -90,27 +89,27 @@ public:
void close();
// 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;
+ Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
+ Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
+ int get_available_packet_count() const override;
+ int get_max_packet_size() const override;
// NetworkedMultiplayerPeer
- void set_transfer_mode(TransferMode p_mode);
- TransferMode get_transfer_mode() const;
- void set_target_peer(int p_peer_id);
+ void set_transfer_mode(TransferMode p_mode) override;
+ TransferMode get_transfer_mode() const override;
+ void set_target_peer(int p_peer_id) override;
- int get_unique_id() const;
- int get_packet_peer() const;
+ int get_unique_id() const override;
+ int get_packet_peer() const override;
- bool is_server() const;
+ bool is_server() const override;
- void poll();
+ void poll() override;
- void set_refuse_new_connections(bool p_enable);
- bool is_refusing_new_connections() const;
+ void set_refuse_new_connections(bool p_enable) override;
+ bool is_refusing_new_connections() const override;
- ConnectionStatus get_connection_status() const;
+ ConnectionStatus get_connection_status() const override;
};
-#endif
+#endif // WEBRTC_MULTIPLAYER_H
diff --git a/modules/webrtc/webrtc_peer_connection.cpp b/modules/webrtc/webrtc_peer_connection.cpp
index 399e4f09ff..3e2938bf7d 100644
--- a/modules/webrtc/webrtc_peer_connection.cpp
+++ b/modules/webrtc/webrtc_peer_connection.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,14 +33,13 @@
WebRTCPeerConnection *(*WebRTCPeerConnection::_create)() = nullptr;
Ref<WebRTCPeerConnection> WebRTCPeerConnection::create_ref() {
-
return create();
}
WebRTCPeerConnection *WebRTCPeerConnection::create() {
-
- if (!_create)
+ if (!_create) {
return nullptr;
+ }
return _create();
}
diff --git a/modules/webrtc/webrtc_peer_connection.h b/modules/webrtc/webrtc_peer_connection.h
index 7366c3d0e8..ae75864489 100644
--- a/modules/webrtc/webrtc_peer_connection.h
+++ b/modules/webrtc/webrtc_peer_connection.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/webrtc/webrtc_peer_connection_gdnative.cpp b/modules/webrtc/webrtc_peer_connection_gdnative.cpp
index f082646629..dcf78dfb73 100644
--- a/modules/webrtc/webrtc_peer_connection_gdnative.cpp
+++ b/modules/webrtc/webrtc_peer_connection_gdnative.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -49,7 +49,6 @@ Error WebRTCPeerConnectionGDNative::set_default_library(const godot_net_webrtc_l
}
WebRTCPeerConnection *WebRTCPeerConnectionGDNative::_create() {
-
WebRTCPeerConnectionGDNative *obj = memnew(WebRTCPeerConnectionGDNative);
ERR_FAIL_COND_V_MSG(!default_library, obj, "Default GDNative WebRTC implementation not defined.");
diff --git a/modules/webrtc/webrtc_peer_connection_gdnative.h b/modules/webrtc/webrtc_peer_connection_gdnative.h
index 8e59ad62ba..578af0202f 100644
--- a/modules/webrtc/webrtc_peer_connection_gdnative.h
+++ b/modules/webrtc/webrtc_peer_connection_gdnative.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -28,11 +28,11 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifdef WEBRTC_GDNATIVE_ENABLED
-
#ifndef WEBRTC_PEER_CONNECTION_GDNATIVE_H
#define WEBRTC_PEER_CONNECTION_GDNATIVE_H
+#ifdef WEBRTC_GDNATIVE_ENABLED
+
#include "modules/gdnative/include/net/godot_net.h"
#include "webrtc_peer_connection.h"
@@ -53,21 +53,21 @@ public:
void set_native_webrtc_peer_connection(const godot_net_webrtc_peer_connection *p_impl);
- virtual ConnectionState get_connection_state() const;
+ virtual ConnectionState get_connection_state() const override;
- virtual Error initialize(Dictionary p_config = Dictionary());
- virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary());
- virtual Error create_offer();
- virtual Error set_remote_description(String type, String sdp);
- virtual Error set_local_description(String type, String sdp);
- virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName);
- virtual Error poll();
- virtual void close();
+ virtual Error initialize(Dictionary p_config = Dictionary()) override;
+ virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary()) override;
+ virtual Error create_offer() override;
+ virtual Error set_remote_description(String type, String sdp) override;
+ virtual Error set_local_description(String type, String sdp) override;
+ virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) override;
+ virtual Error poll() override;
+ virtual void close() override;
WebRTCPeerConnectionGDNative();
~WebRTCPeerConnectionGDNative();
};
-#endif // WEBRTC_PEER_CONNECTION_GDNATIVE_H
-
#endif // WEBRTC_GDNATIVE_ENABLED
+
+#endif // WEBRTC_PEER_CONNECTION_GDNATIVE_H
diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp
index 593c3a5162..8879f7d6ec 100644
--- a/modules/webrtc/webrtc_peer_connection_js.cpp
+++ b/modules/webrtc/webrtc_peer_connection_js.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -37,116 +37,32 @@
#include "core/io/json.h"
#include "emscripten.h"
-extern "C" {
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_ice_candidate(void *obj, char *p_MidName, int p_MlineIndexName, char *p_sdpName) {
- WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj);
- peer->emit_signal("ice_candidate_created", String(p_MidName), p_MlineIndexName, String(p_sdpName));
+void WebRTCPeerConnectionJS::_on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate) {
+ WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj);
+ peer->emit_signal("ice_candidate_created", String(p_mid_name), p_mline_idx, String(p_candidate));
}
-EMSCRIPTEN_KEEPALIVE void _emrtc_session_description_created(void *obj, char *p_type, char *p_offer) {
- WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj);
- peer->emit_signal("session_description_created", String(p_type), String(p_offer));
+void WebRTCPeerConnectionJS::_on_session_created(void *p_obj, const char *p_type, const char *p_session) {
+ WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj);
+ peer->emit_signal("session_description_created", String(p_type), String(p_session));
}
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_connection_state_changed(void *obj) {
- WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj);
- peer->_on_connection_state_changed();
+void WebRTCPeerConnectionJS::_on_connection_state_changed(void *p_obj, int p_state) {
+ WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj);
+ peer->_conn_state = (ConnectionState)p_state;
}
-EMSCRIPTEN_KEEPALIVE void _emrtc_on_error() {
+void WebRTCPeerConnectionJS::_on_error(void *p_obj) {
ERR_PRINT("RTCPeerConnection error!");
}
-EMSCRIPTEN_KEEPALIVE void _emrtc_emit_channel(void *obj, int p_id) {
- WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(obj);
+void WebRTCPeerConnectionJS::_on_data_channel(void *p_obj, int p_id) {
+ WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj);
peer->emit_signal("data_channel_received", Ref<WebRTCDataChannelJS>(new WebRTCDataChannelJS(p_id)));
}
-}
-
-void _emrtc_create_pc(int p_id, const Dictionary &p_config) {
- String config = JSON::print(p_config);
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var c_ptr = dict["ptr"];
- var config = JSON.parse(UTF8ToString($1));
- // Setup local connaction
- var conn = null;
- try {
- conn = new RTCPeerConnection(config);
- } catch (e) {
- console.log(e);
- return;
- }
- conn.oniceconnectionstatechange = function(event) {
- if (!Module.IDHandler.get($0)) return;
- ccall("_emrtc_on_connection_state_changed", "void", ["number"], [c_ptr]);
- };
- conn.onicecandidate = function(event) {
- if (!Module.IDHandler.get($0)) return;
- if (!event.candidate) return;
-
- var c = event.candidate;
- // should emit on ice candidate
- ccall("_emrtc_on_ice_candidate",
- "void",
- ["number", "string", "number", "string"],
- [c_ptr, c.sdpMid, c.sdpMLineIndex, c.candidate]
- );
- };
- conn.ondatachannel = function (evt) {
- var dict = Module.IDHandler.get($0);
- if (!dict) {
- return;
- }
- var id = Module.IDHandler.add({"channel": evt.channel, "ptr": null});
- ccall("_emrtc_emit_channel",
- "void",
- ["number", "number"],
- [c_ptr, id]
- );
- };
- dict["conn"] = conn;
- }, p_id, config.utf8().get_data());
- /* clang-format on */
-}
-
-void WebRTCPeerConnectionJS::_on_connection_state_changed() {
- /* clang-format off */
- _conn_state = (ConnectionState)EM_ASM_INT({
- var dict = Module.IDHandler.get($0);
- if (!dict) return 5; // CLOSED
- var conn = dict["conn"];
- switch(conn.iceConnectionState) {
- case "new":
- return 0;
- case "checking":
- return 1;
- case "connected":
- case "completed":
- return 2;
- case "disconnected":
- return 3;
- case "failed":
- return 4;
- case "closed":
- return 5;
- }
- return 5; // CLOSED
- }, _js_id);
- /* clang-format on */
-}
void WebRTCPeerConnectionJS::close() {
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- if (!dict) return;
- if (dict["conn"]) {
- dict["conn"].close();
- }
- }, _js_id);
- /* clang-format on */
+ godot_js_rtc_pc_close(_js_id);
_conn_state = STATE_CLOSED;
}
@@ -154,46 +70,12 @@ Error WebRTCPeerConnectionJS::create_offer() {
ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED);
_conn_state = STATE_CONNECTING;
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var conn = dict["conn"];
- var c_ptr = dict["ptr"];
- var onError = function(error) {
- console.error(error);
- ccall("_emrtc_on_error", "void", [], []);
- };
- var onCreated = function(offer) {
- ccall("_emrtc_session_description_created",
- "void",
- ["number", "string", "string"],
- [c_ptr, offer.type, offer.sdp]
- );
- };
- conn.createOffer().then(onCreated).catch(onError);
- }, _js_id);
- /* clang-format on */
+ godot_js_rtc_pc_offer_create(_js_id, this, &_on_session_created, &_on_error);
return OK;
}
Error WebRTCPeerConnectionJS::set_local_description(String type, String sdp) {
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var conn = dict["conn"];
- var c_ptr = dict["ptr"];
- var type = UTF8ToString($1);
- var sdp = UTF8ToString($2);
- var onError = function(error) {
- console.error(error);
- ccall("_emrtc_on_error", "void", [], []);
- };
- conn.setLocalDescription({
- "sdp": sdp,
- "type": type
- }).catch(onError);
- }, _js_id, type.utf8().get_data(), sdp.utf8().get_data());
- /* clang-format on */
+ godot_js_rtc_pc_local_description_set(_js_id, type.utf8().get_data(), sdp.utf8().get_data(), this, &_on_error);
return OK;
}
@@ -202,83 +84,32 @@ Error WebRTCPeerConnectionJS::set_remote_description(String type, String sdp) {
ERR_FAIL_COND_V(_conn_state != STATE_NEW, FAILED);
_conn_state = STATE_CONNECTING;
}
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var conn = dict["conn"];
- var c_ptr = dict["ptr"];
- var type = UTF8ToString($1);
- var sdp = UTF8ToString($2);
-
- var onError = function(error) {
- console.error(error);
- ccall("_emrtc_on_error", "void", [], []);
- };
- var onCreated = function(offer) {
- ccall("_emrtc_session_description_created",
- "void",
- ["number", "string", "string"],
- [c_ptr, offer.type, offer.sdp]
- );
- };
- var onSet = function() {
- if (type != "offer") {
- return;
- }
- conn.createAnswer().then(onCreated);
- };
- conn.setRemoteDescription({
- "sdp": sdp,
- "type": type
- }).then(onSet).catch(onError);
- }, _js_id, type.utf8().get_data(), sdp.utf8().get_data());
- /* clang-format on */
+ godot_js_rtc_pc_remote_description_set(_js_id, type.utf8().get_data(), sdp.utf8().get_data(), this, &_on_session_created, &_on_error);
return OK;
}
Error WebRTCPeerConnectionJS::add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) {
- /* clang-format off */
- EM_ASM({
- var dict = Module.IDHandler.get($0);
- var conn = dict["conn"];
- var c_ptr = dict["ptr"];
- var sdpMidName = UTF8ToString($1);
- var sdpMlineIndexName = UTF8ToString($2);
- var sdpName = UTF8ToString($3);
- conn.addIceCandidate(new RTCIceCandidate({
- "candidate": sdpName,
- "sdpMid": sdpMidName,
- "sdpMlineIndex": sdpMlineIndexName
- }));
- }, _js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data());
- /* clang-format on */
+ godot_js_rtc_pc_ice_candidate_add(_js_id, sdpMidName.utf8().get_data(), sdpMlineIndexName, sdpName.utf8().get_data());
return OK;
}
Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) {
- _emrtc_create_pc(_js_id, p_config);
- return OK;
+ if (_js_id) {
+ godot_js_rtc_pc_destroy(_js_id);
+ _js_id = 0;
+ }
+ _conn_state = STATE_NEW;
+
+ String config = JSON::print(p_config);
+ _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_ice_candidate, &_on_data_channel);
+ return _js_id ? OK : FAILED;
}
Ref<WebRTCDataChannel> WebRTCPeerConnectionJS::create_data_channel(String p_channel, Dictionary p_channel_config) {
+ ERR_FAIL_COND_V(_conn_state != STATE_NEW, nullptr);
+
String config = JSON::print(p_channel_config);
- /* clang-format off */
- int id = EM_ASM_INT({
- try {
- var dict = Module.IDHandler.get($0);
- if (!dict) return 0;
- var label = UTF8ToString($1);
- var config = JSON.parse(UTF8ToString($2));
- var conn = dict["conn"];
- return Module.IDHandler.add({
- "channel": conn.createDataChannel(label, config),
- "ptr": null
- })
- } catch (e) {
- return 0;
- }
- }, _js_id, p_channel.utf8().get_data(), config.utf8().get_data());
- /* clang-format on */
+ int id = godot_js_rtc_pc_datachannel_create(_js_id, p_channel.utf8().get_data(), config.utf8().get_data());
ERR_FAIL_COND_V(id == 0, nullptr);
return memnew(WebRTCDataChannelJS(id));
}
@@ -293,22 +124,17 @@ WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_sta
WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() {
_conn_state = STATE_NEW;
+ _js_id = 0;
- /* clang-format off */
- _js_id = EM_ASM_INT({
- return Module.IDHandler.add({"conn": null, "ptr": $0});
- }, this);
- /* clang-format on */
Dictionary config;
- _emrtc_create_pc(_js_id, config);
+ initialize(config);
}
WebRTCPeerConnectionJS::~WebRTCPeerConnectionJS() {
close();
- /* clang-format off */
- EM_ASM({
- Module.IDHandler.remove($0);
- }, _js_id);
- /* clang-format on */
+ if (_js_id) {
+ godot_js_rtc_pc_destroy(_js_id);
+ _js_id = 0;
+ }
};
#endif
diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h
index 6540077e84..0272e67f6f 100644
--- a/modules/webrtc/webrtc_peer_connection_js.h
+++ b/modules/webrtc/webrtc_peer_connection_js.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -35,17 +35,37 @@
#include "webrtc_peer_connection.h"
-class WebRTCPeerConnectionJS : public WebRTCPeerConnection {
+extern "C" {
+typedef void (*RTCOnIceConnectionStateChange)(void *p_obj, int p_state);
+typedef void (*RTCOnIceCandidate)(void *p_obj, const char *p_mid, int p_mline_idx, const char *p_candidate);
+typedef void (*RTCOnDataChannel)(void *p_obj, int p_id);
+typedef void (*RTCOnSession)(void *p_obj, const char *p_type, const char *p_sdp);
+typedef void (*RTCOnError)(void *p_obj);
+extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel);
+extern void godot_js_rtc_pc_close(int p_id);
+extern void godot_js_rtc_pc_destroy(int p_id);
+extern void godot_js_rtc_pc_offer_create(int p_id, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error);
+extern void godot_js_rtc_pc_local_description_set(int p_id, const char *p_type, const char *p_sdp, void *p_obj, RTCOnError p_on_error);
+extern void godot_js_rtc_pc_remote_description_set(int p_id, const char *p_type, const char *p_sdp, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error);
+extern void godot_js_rtc_pc_ice_candidate_add(int p_id, const char *p_mid_name, int p_mline_idx, const char *p_sdo);
+extern int godot_js_rtc_pc_datachannel_create(int p_id, const char *p_label, const char *p_config);
+}
+class WebRTCPeerConnectionJS : public WebRTCPeerConnection {
private:
int _js_id;
ConnectionState _conn_state;
+ static void _on_connection_state_changed(void *p_obj, int p_state);
+ static void _on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate);
+ static void _on_data_channel(void *p_obj, int p_channel);
+ static void _on_session_created(void *p_obj, const char *p_type, const char *p_session);
+ static void _on_error(void *p_obj);
+
public:
static WebRTCPeerConnection *_create() { return memnew(WebRTCPeerConnectionJS); }
static void make_default() { WebRTCPeerConnection::_create = WebRTCPeerConnectionJS::_create; }
- void _on_connection_state_changed();
virtual ConnectionState get_connection_state() const;
virtual Error initialize(Dictionary configuration = Dictionary());
diff --git a/modules/websocket/SCsub b/modules/websocket/SCsub
index af60055855..4c022c43cf 100644
--- a/modules/websocket/SCsub
+++ b/modules/websocket/SCsub
@@ -3,28 +3,46 @@
Import("env")
Import("env_modules")
-# Thirdparty source files
-
env_ws = env_modules.Clone()
-if env["builtin_wslay"] and not env["platform"] == "javascript": # already builtin for javascript
- wslay_dir = "#thirdparty/wslay/"
- wslay_sources = [
+thirdparty_obj = []
+
+if env["platform"] == "javascript":
+ # Our JavaScript/C++ interface.
+ env.AddJSLibraries(["library_godot_websocket.js"])
+
+elif env["builtin_wslay"]:
+ # Thirdparty source files
+ thirdparty_dir = "#thirdparty/wslay/"
+ thirdparty_sources = [
"wslay_net.c",
"wslay_event.c",
"wslay_queue.c",
"wslay_stack.c",
"wslay_frame.c",
]
- wslay_sources = [wslay_dir + s for s in wslay_sources]
- env_ws.Prepend(CPPPATH=[wslay_dir + "includes/"])
+ thirdparty_sources = [thirdparty_dir + s for s in thirdparty_sources]
+
+ env_ws.Prepend(CPPPATH=[thirdparty_dir + "includes/"])
env_ws.Append(CPPDEFINES=["HAVE_CONFIG_H"])
+
if env["platform"] == "windows" or env["platform"] == "uwp":
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")
+ env_thirdparty = env_ws.Clone()
+ env_thirdparty.disable_warnings()
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
+
+# Godot source files
+
+module_obj = []
+
+env_ws.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/websocket/editor_debugger_server_websocket.cpp b/modules/websocket/editor_debugger_server_websocket.cpp
new file mode 100644
index 0000000000..b02d212c42
--- /dev/null
+++ b/modules/websocket/editor_debugger_server_websocket.cpp
@@ -0,0 +1,93 @@
+/*************************************************************************/
+/* editor_debugger_server_websocket.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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_debugger_server_websocket.h"
+
+#include "core/config/project_settings.h"
+#include "editor/editor_settings.h"
+#include "modules/websocket/remote_debugger_peer_websocket.h"
+
+void EditorDebuggerServerWebSocket::_peer_connected(int p_id, String _protocol) {
+ pending_peers.push_back(p_id);
+}
+
+void EditorDebuggerServerWebSocket::_peer_disconnected(int p_id, bool p_was_clean) {
+ if (pending_peers.find(p_id)) {
+ pending_peers.erase(p_id);
+ }
+}
+
+void EditorDebuggerServerWebSocket::poll() {
+ server->poll();
+}
+
+Error EditorDebuggerServerWebSocket::start() {
+ int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port");
+ Vector<String> protocols;
+ protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer.
+ return server->listen(remote_port, protocols);
+}
+
+void EditorDebuggerServerWebSocket::stop() {
+ server->stop();
+ pending_peers.clear();
+}
+
+bool EditorDebuggerServerWebSocket::is_active() const {
+ return server->is_listening();
+}
+
+bool EditorDebuggerServerWebSocket::is_connection_available() const {
+ return pending_peers.size() > 0;
+}
+
+Ref<RemoteDebuggerPeer> EditorDebuggerServerWebSocket::take_connection() {
+ ERR_FAIL_COND_V(!is_connection_available(), Ref<RemoteDebuggerPeer>());
+ RemoteDebuggerPeer *peer = memnew(RemoteDebuggerPeerWebSocket(server->get_peer(pending_peers[0])));
+ pending_peers.pop_front();
+ return peer;
+}
+
+EditorDebuggerServerWebSocket::EditorDebuggerServerWebSocket() {
+ server = Ref<WebSocketServer>(WebSocketServer::create());
+ int max_pkts = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages");
+ server->set_buffers(8192, max_pkts, 8192, max_pkts);
+ server->connect("client_connected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_connected));
+ server->connect("client_disconnected", callable_mp(this, &EditorDebuggerServerWebSocket::_peer_disconnected));
+}
+
+EditorDebuggerServerWebSocket::~EditorDebuggerServerWebSocket() {
+ stop();
+}
+
+EditorDebuggerServer *EditorDebuggerServerWebSocket::create(const String &p_protocol) {
+ ERR_FAIL_COND_V(p_protocol != "ws://", nullptr);
+ return memnew(EditorDebuggerServerWebSocket);
+}
diff --git a/modules/websocket/editor_debugger_server_websocket.h b/modules/websocket/editor_debugger_server_websocket.h
new file mode 100644
index 0000000000..2f73b98c3d
--- /dev/null
+++ b/modules/websocket/editor_debugger_server_websocket.h
@@ -0,0 +1,62 @@
+/*************************************************************************/
+/* editor_debugger_server_websocket.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H
+#define SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H
+
+#include "modules/websocket/websocket_server.h"
+
+#include "editor/debugger/editor_debugger_server.h"
+
+class EditorDebuggerServerWebSocket : public EditorDebuggerServer {
+ GDCLASS(EditorDebuggerServerWebSocket, EditorDebuggerServer);
+
+private:
+ Ref<WebSocketServer> server;
+ List<int> pending_peers;
+
+public:
+ static EditorDebuggerServer *create(const String &p_protocol);
+
+ void _peer_connected(int p_peer, String p_protocol);
+ void _peer_disconnected(int p_peer, bool p_was_clean);
+
+ void poll() override;
+ Error start() override;
+ void stop() override;
+ bool is_active() const override;
+ bool is_connection_available() const override;
+ Ref<RemoteDebuggerPeer> take_connection() override;
+
+ EditorDebuggerServerWebSocket();
+ ~EditorDebuggerServerWebSocket();
+};
+
+#endif // SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H
diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp
index bbe4d6dc5b..aec01a1eea 100644
--- a/modules/websocket/emws_client.cpp
+++ b/modules/websocket/emws_client.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,18 +31,17 @@
#ifdef JAVASCRIPT_ENABLED
#include "emws_client.h"
+#include "core/config/project_settings.h"
#include "core/io/ip.h"
-#include "core/project_settings.h"
#include "emscripten.h"
-extern "C" {
-EMSCRIPTEN_KEEPALIVE void _esws_on_connect(void *obj, char *proto) {
+void EMWSClient::_esws_on_connect(void *obj, char *proto) {
EMWSClient *client = static_cast<EMWSClient *>(obj);
client->_is_connecting = false;
client->_on_connect(String(proto));
}
-EMSCRIPTEN_KEEPALIVE void _esws_on_message(void *obj, uint8_t *p_data, int p_data_size, int p_is_string) {
+void EMWSClient::_esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string) {
EMWSClient *client = static_cast<EMWSClient *>(obj);
Error err = static_cast<EMWSPeer *>(*client->get_peer(1))->read_msg(p_data, p_data_size, p_is_string == 1);
@@ -50,21 +49,25 @@ EMSCRIPTEN_KEEPALIVE void _esws_on_message(void *obj, uint8_t *p_data, int p_dat
client->_on_peer_packet();
}
-EMSCRIPTEN_KEEPALIVE void _esws_on_error(void *obj) {
+void EMWSClient::_esws_on_error(void *obj) {
EMWSClient *client = static_cast<EMWSClient *>(obj);
client->_is_connecting = false;
client->_on_error();
}
-EMSCRIPTEN_KEEPALIVE void _esws_on_close(void *obj, int code, char *reason, int was_clean) {
+void EMWSClient::_esws_on_close(void *obj, int code, const char *reason, int was_clean) {
EMWSClient *client = static_cast<EMWSClient *>(obj);
client->_on_close_request(code, String(reason));
client->_is_connecting = false;
+ client->disconnect_from_host();
client->_on_disconnect(was_clean != 0);
}
-}
Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
+ if (_js_id) {
+ godot_js_websocket_destroy(_js_id);
+ _js_id = 0;
+ }
String proto_string;
for (int i = 0; i < p_protocols.size(); i++) {
@@ -85,117 +88,26 @@ Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port,
}
}
str += p_host + ":" + itos(p_port) + p_path;
-
_is_connecting = true;
- /* clang-format off */
- int peer_sock = EM_ASM_INT({
- var proto_str = UTF8ToString($2);
- var socket = null;
- try {
- if (proto_str) {
- socket = new WebSocket(UTF8ToString($1), proto_str.split(","));
- } else {
- socket = new WebSocket(UTF8ToString($1));
- }
- } catch (e) {
- return -1;
- }
- var c_ptr = Module.IDHandler.get($0);
- socket.binaryType = "arraybuffer";
-
- // Connection opened
- socket.addEventListener("open", function (event) {
- if (!Module.IDHandler.has($0))
- return; // Godot Object is gone!
- ccall("_esws_on_connect",
- "void",
- ["number", "string"],
- [c_ptr, socket.protocol]
- );
- });
-
- // Listen for messages
- socket.addEventListener("message", function (event) {
- if (!Module.IDHandler.has($0))
- return; // Godot Object is gone!
- var buffer;
- var is_string = 0;
- if (event.data instanceof ArrayBuffer) {
-
- buffer = new Uint8Array(event.data);
-
- } else if (event.data instanceof Blob) {
-
- alert("Blob type not supported");
- return;
-
- } else if (typeof event.data === "string") {
-
- is_string = 1;
- var enc = new TextEncoder("utf-8");
- buffer = new Uint8Array(enc.encode(event.data));
-
- } else {
-
- alert("Unknown message type");
- return;
-
- }
- var len = buffer.length*buffer.BYTES_PER_ELEMENT;
- var out = Module._malloc(len);
- Module.HEAPU8.set(buffer, out);
- ccall("_esws_on_message",
- "void",
- ["number", "number", "number", "number"],
- [c_ptr, out, len, is_string]
- );
- Module._free(out);
- });
-
- socket.addEventListener("error", function (event) {
- if (!Module.IDHandler.has($0))
- return; // Godot Object is gone!
- ccall("_esws_on_error",
- "void",
- ["number"],
- [c_ptr]
- );
- });
-
- socket.addEventListener("close", function (event) {
- if (!Module.IDHandler.has($0))
- return; // Godot Object is gone!
- var was_clean = 0;
- if (event.wasClean)
- was_clean = 1;
- ccall("_esws_on_close",
- "void",
- ["number", "number", "string", "number"],
- [c_ptr, event.code, event.reason, was_clean]
- );
- });
- return Module.IDHandler.add(socket);
- }, _js_id, str.utf8().get_data(), proto_string.utf8().get_data());
- /* clang-format on */
- if (peer_sock == -1)
+ _js_id = godot_js_websocket_create(this, str.utf8().get_data(), proto_string.utf8().get_data(), &_esws_on_connect, &_esws_on_message, &_esws_on_error, &_esws_on_close);
+ if (!_js_id) {
return FAILED;
+ }
- static_cast<Ref<EMWSPeer>>(_peer)->set_sock(peer_sock, _in_buf_size, _in_pkt_size);
+ static_cast<Ref<EMWSPeer>>(_peer)->set_sock(_js_id, _in_buf_size, _in_pkt_size);
return OK;
-};
+}
void EMWSClient::poll() {
}
Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const {
-
return _peer;
}
NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const {
-
if (_peer->is_connected_to_host()) {
if (_is_connecting)
return CONNECTION_CONNECTING;
@@ -203,22 +115,19 @@ NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() c
}
return CONNECTION_DISCONNECTED;
-};
+}
void EMWSClient::disconnect_from_host(int p_code, String p_reason) {
-
_peer->close(p_code, p_reason);
-};
+}
IP_Address EMWSClient::get_connected_host() const {
-
ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export.");
-};
+}
uint16_t EMWSClient::get_connected_port() const {
-
ERR_FAIL_V_MSG(0, "Not supported in HTML5 export.");
-};
+}
int EMWSClient::get_max_packet_size() const {
return (1 << _in_buf_size) - PROTO_SIZE;
@@ -231,26 +140,19 @@ Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffe
}
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);
+ _in_buf_size = DEF_BUF_SHIFT;
+ _in_pkt_size = DEF_PKT_SHIFT;
_is_connecting = false;
_peer = Ref<EMWSPeer>(memnew(EMWSPeer));
- /* clang-format off */
- _js_id = EM_ASM_INT({
- return Module.IDHandler.add($0);
- }, this);
- /* clang-format on */
-};
+ _js_id = 0;
+}
EMWSClient::~EMWSClient() {
-
disconnect_from_host();
_peer = Ref<EMWSPeer>();
- /* clang-format off */
- EM_ASM({
- Module.IDHandler.remove($0);
- }, _js_id);
- /* clang-format on */
-};
+ if (_js_id) {
+ godot_js_websocket_destroy(_js_id);
+ }
+}
#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h
index 9f1c220ed4..fdf7a231d2 100644
--- a/modules/websocket/emws_client.h
+++ b/modules/websocket/emws_client.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,22 +33,25 @@
#ifdef JAVASCRIPT_ENABLED
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "emws_peer.h"
#include "websocket_client.h"
class EMWSClient : public WebSocketClient {
-
GDCIIMPL(EMWSClient, WebSocketClient);
private:
+ int _js_id;
+ bool _is_connecting;
int _in_buf_size;
int _in_pkt_size;
- int _js_id;
-public:
- bool _is_connecting;
+ static void _esws_on_connect(void *obj, char *proto);
+ static void _esws_on_message(void *obj, const uint8_t *p_data, int p_data_size, int p_is_string);
+ static void _esws_on_error(void *obj);
+ static void _esws_on_close(void *obj, int code, const char *reason, int was_clean);
+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, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>());
Ref<WebSocketPeer> get_peer(int p_peer_id) const;
diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp
index 9472daa620..496c1edc04 100644
--- a/modules/websocket/emws_peer.cpp
+++ b/modules/websocket/emws_peer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/io/ip.h"
void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size) {
-
peer_sock = p_sock;
_in_buffer.resize(p_in_pkt_size, p_in_buf_size);
_packet_buffer.resize((1 << p_in_buf_size));
@@ -48,45 +47,18 @@ EMWSPeer::WriteMode EMWSPeer::get_write_mode() const {
return write_mode;
}
-Error EMWSPeer::read_msg(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
-
+Error EMWSPeer::read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string) {
uint8_t is_string = p_is_string ? 1 : 0;
return _in_buffer.write_packet(p_data, p_size, &is_string);
}
Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
-
int is_bin = write_mode == WebSocketPeer::WRITE_MODE_BINARY ? 1 : 0;
-
- /* clang-format off */
- EM_ASM({
- var sock = Module.IDHandler.get($0);
- var bytes_array = new Uint8Array($2);
- var i = 0;
-
- for(i=0; i<$2; i++) {
- bytes_array[i] = getValue($1+i, 'i8');
- }
-
- try {
- if ($3) {
- sock.send(bytes_array.buffer);
- } else {
- var string = new TextDecoder("utf-8").decode(bytes_array);
- sock.send(string);
- }
- } catch (e) {
- return 1;
- }
- return 0;
- }, peer_sock, p_buffer, p_buffer_size, is_bin);
- /* clang-format on */
-
+ godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, is_bin);
return OK;
};
Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
-
if (_in_buffer.packets_left() == 0)
return ERR_UNAVAILABLE;
@@ -101,32 +73,20 @@ Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
};
int EMWSPeer::get_available_packet_count() const {
-
return _in_buffer.packets_left();
};
bool EMWSPeer::was_string_packet() const {
-
return _is_string;
};
bool EMWSPeer::is_connected_to_host() const {
-
return peer_sock != -1;
};
void EMWSPeer::close(int p_code, String p_reason) {
-
if (peer_sock != -1) {
- /* clang-format off */
- EM_ASM({
- var sock = Module.IDHandler.get($0);
- var code = $1;
- var reason = UTF8ToString($2);
- sock.close(code, reason);
- Module.IDHandler.remove($0);
- }, peer_sock, p_code, p_reason.utf8().get_data());
- /* clang-format on */
+ godot_js_websocket_close(peer_sock, p_code, p_reason.utf8().get_data());
}
_is_string = 0;
_in_buffer.clear();
@@ -134,17 +94,14 @@ void EMWSPeer::close(int p_code, String p_reason) {
};
IP_Address EMWSPeer::get_connected_host() const {
-
ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export.");
};
uint16_t EMWSPeer::get_connected_port() const {
-
ERR_FAIL_V_MSG(0, "Not supported in HTML5 export.");
};
void EMWSPeer::set_no_delay(bool p_enabled) {
-
ERR_FAIL_MSG("'set_no_delay' is not supported in HTML5 export.");
}
@@ -155,7 +112,6 @@ EMWSPeer::EMWSPeer() {
};
EMWSPeer::~EMWSPeer() {
-
close();
};
diff --git a/modules/websocket/emws_peer.h b/modules/websocket/emws_peer.h
index 6308ebe490..07f61b62a0 100644
--- a/modules/websocket/emws_peer.h
+++ b/modules/websocket/emws_peer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,15 +33,26 @@
#ifdef JAVASCRIPT_ENABLED
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "core/io/packet_peer.h"
-#include "core/ring_buffer.h"
+#include "core/templates/ring_buffer.h"
#include "emscripten.h"
#include "packet_buffer.h"
#include "websocket_peer.h"
-class EMWSPeer : public WebSocketPeer {
+extern "C" {
+typedef void (*WSOnOpen)(void *p_ref, char *p_protocol);
+typedef void (*WSOnMessage)(void *p_ref, const uint8_t *p_buf, int p_buf_len, int p_is_string);
+typedef void (*WSOnClose)(void *p_ref, int p_code, const char *p_reason, int p_is_clean);
+typedef void (*WSOnError)(void *p_ref);
+
+extern int godot_js_websocket_create(void *p_ref, const char *p_url, const char *p_proto, WSOnOpen p_on_open, WSOnMessage p_on_message, WSOnError p_on_error, WSOnClose p_on_close);
+extern int godot_js_websocket_send(int p_id, const uint8_t *p_buf, int p_buf_len, int p_raw);
+extern void godot_js_websocket_close(int p_id, int p_code, const char *p_reason);
+extern void godot_js_websocket_destroy(int p_id);
+}
+class EMWSPeer : public WebSocketPeer {
GDCIIMPL(EMWSPeer, WebSocketPeer);
private:
@@ -53,7 +64,7 @@ private:
uint8_t _is_string;
public:
- Error read_msg(uint8_t *p_data, uint32_t p_size, bool p_is_string);
+ Error read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string);
void set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size);
virtual int get_available_packet_count() const;
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size);
diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp
index 95cffb4775..a35d84f372 100644
--- a/modules/websocket/emws_server.cpp
+++ b/modules/websocket/emws_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -34,7 +34,6 @@
#include "core/os/os.h"
Error EMWSServer::listen(int p_port, Vector<String> p_protocols, bool gd_mp_api) {
-
return FAILED;
}
@@ -60,12 +59,10 @@ Vector<String> EMWSServer::get_protocols() const {
}
IP_Address EMWSServer::get_peer_address(int p_peer_id) const {
-
return IP_Address();
}
int EMWSServer::get_peer_port(int p_peer_id) const {
-
return 0;
}
diff --git a/modules/websocket/emws_server.h b/modules/websocket/emws_server.h
index f273fd078f..4179b20ffe 100644
--- a/modules/websocket/emws_server.h
+++ b/modules/websocket/emws_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,12 +33,11 @@
#ifdef JAVASCRIPT_ENABLED
-#include "core/reference.h"
+#include "core/object/reference.h"
#include "emws_peer.h"
#include "websocket_server.h"
class EMWSServer : public WebSocketServer {
-
GDCIIMPL(EMWSServer, WebSocketServer);
public:
diff --git a/modules/websocket/library_godot_websocket.js b/modules/websocket/library_godot_websocket.js
new file mode 100644
index 0000000000..b182d1ecde
--- /dev/null
+++ b/modules/websocket/library_godot_websocket.js
@@ -0,0 +1,188 @@
+/*************************************************************************/
+/* library_godot_websocket.js */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+const GodotWebSocket = {
+ // Our socket implementation that forwards events to C++.
+ $GodotWebSocket__deps: ['$IDHandler', '$GodotRuntime'],
+ $GodotWebSocket: {
+ // Connection opened, report selected protocol
+ _onopen: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return; // Godot object is gone.
+ }
+ const c_str = GodotRuntime.allocString(ref.protocol);
+ callback(c_str);
+ GodotRuntime.free(c_str);
+ },
+
+ // Message received, report content and type (UTF8 vs binary)
+ _onmessage: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return; // Godot object is gone.
+ }
+ let buffer;
+ let is_string = 0;
+ if (event.data instanceof ArrayBuffer) {
+ buffer = new Uint8Array(event.data);
+ } else if (event.data instanceof Blob) {
+ GodotRuntime.error('Blob type not supported');
+ return;
+ } else if (typeof event.data === 'string') {
+ is_string = 1;
+ const enc = new TextEncoder('utf-8');
+ buffer = new Uint8Array(enc.encode(event.data));
+ } else {
+ GodotRuntime.error('Unknown message type');
+ return;
+ }
+ const len = buffer.length * buffer.BYTES_PER_ELEMENT;
+ const out = GodotRuntime.malloc(len);
+ HEAPU8.set(buffer, out);
+ callback(out, len, is_string);
+ GodotRuntime.free(out);
+ },
+
+ // An error happened, 'onclose' will be called after this.
+ _onerror: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return; // Godot object is gone.
+ }
+ callback();
+ },
+
+ // Connection is closed, this is always fired. Report close code, reason, and clean status.
+ _onclose: function (p_id, callback, event) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return; // Godot object is gone.
+ }
+ const c_str = GodotRuntime.allocString(event.reason);
+ callback(event.code, c_str, event.wasClean ? 1 : 0);
+ GodotRuntime.free(c_str);
+ },
+
+ // Send a message
+ send: function (p_id, p_data) {
+ const ref = IDHandler.get(p_id);
+ if (!ref || ref.readyState !== ref.OPEN) {
+ return 1; // Godot object is gone or socket is not in a ready state.
+ }
+ ref.send(p_data);
+ return 0;
+ },
+
+ create: function (socket, p_on_open, p_on_message, p_on_error, p_on_close) {
+ const id = IDHandler.add(socket);
+ socket.onopen = GodotWebSocket._onopen.bind(null, id, p_on_open);
+ socket.onmessage = GodotWebSocket._onmessage.bind(null, id, p_on_message);
+ socket.onerror = GodotWebSocket._onerror.bind(null, id, p_on_error);
+ socket.onclose = GodotWebSocket._onclose.bind(null, id, p_on_close);
+ return id;
+ },
+
+ // Closes the JavaScript WebSocket (if not already closing) associated to a given C++ object.
+ close: function (p_id, p_code, p_reason) {
+ const ref = IDHandler.get(p_id);
+ if (ref && ref.readyState < ref.CLOSING) {
+ const code = p_code;
+ const reason = GodotRuntime.parseString(p_reason);
+ ref.close(code, reason);
+ }
+ },
+
+ // Deletes the reference to a C++ object (closing any connected socket if necessary).
+ destroy: function (p_id) {
+ const ref = IDHandler.get(p_id);
+ if (!ref) {
+ return;
+ }
+ GodotWebSocket.close(p_id, 1001, '');
+ IDHandler.remove(p_id);
+ ref.onopen = null;
+ ref.onmessage = null;
+ ref.onerror = null;
+ ref.onclose = null;
+ },
+ },
+
+ godot_js_websocket_create__sig: 'iiiiiiii',
+ godot_js_websocket_create: function (p_ref, p_url, p_proto, p_on_open, p_on_message, p_on_error, p_on_close) {
+ const on_open = GodotRuntime.get_func(p_on_open).bind(null, p_ref);
+ const on_message = GodotRuntime.get_func(p_on_message).bind(null, p_ref);
+ const on_error = GodotRuntime.get_func(p_on_error).bind(null, p_ref);
+ const on_close = GodotRuntime.get_func(p_on_close).bind(null, p_ref);
+ const url = GodotRuntime.parseString(p_url);
+ const protos = GodotRuntime.parseString(p_proto);
+ let socket = null;
+ try {
+ if (protos) {
+ socket = new WebSocket(url, protos.split(','));
+ } else {
+ socket = new WebSocket(url);
+ }
+ } catch (e) {
+ return 0;
+ }
+ socket.binaryType = 'arraybuffer';
+ return GodotWebSocket.create(socket, on_open, on_message, on_error, on_close);
+ },
+
+ godot_js_websocket_send__sig: 'iiiii',
+ godot_js_websocket_send: function (p_id, p_buf, p_buf_len, p_raw) {
+ const bytes_array = new Uint8Array(p_buf_len);
+ let i = 0;
+ for (i = 0; i < p_buf_len; i++) {
+ bytes_array[i] = GodotRuntime.getHeapValue(p_buf + i, 'i8');
+ }
+ let out = bytes_array.buffer;
+ if (!p_raw) {
+ out = new TextDecoder('utf-8').decode(bytes_array);
+ }
+ return GodotWebSocket.send(p_id, out);
+ },
+
+ godot_js_websocket_close__sig: 'viii',
+ godot_js_websocket_close: function (p_id, p_code, p_reason) {
+ const code = p_code;
+ const reason = GodotRuntime.parseString(p_reason);
+ GodotWebSocket.close(p_id, code, reason);
+ },
+
+ godot_js_websocket_destroy__sig: 'vi',
+ godot_js_websocket_destroy: function (p_id) {
+ GodotWebSocket.destroy(p_id);
+ },
+};
+
+autoAddDeps(GodotWebSocket, '$GodotWebSocket');
+mergeInto(LibraryManager.library, GodotWebSocket);
diff --git a/modules/websocket/packet_buffer.h b/modules/websocket/packet_buffer.h
index 5f5f0e20cd..ed756363cf 100644
--- a/modules/websocket/packet_buffer.h
+++ b/modules/websocket/packet_buffer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,11 +32,10 @@
#define PACKET_BUFFER_H
#include "core/os/copymem.h"
-#include "core/ring_buffer.h"
+#include "core/templates/ring_buffer.h"
template <class T>
class PacketBuffer {
-
private:
typedef struct {
uint32_t size;
diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp
index e389d75ffd..5a02509c4a 100644
--- a/modules/websocket/register_types.cpp
+++ b/modules/websocket/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -29,8 +29,8 @@
/*************************************************************************/
#include "register_types.h"
-#include "core/error_macros.h"
-#include "core/project_settings.h"
+#include "core/config/project_settings.h"
+#include "core/error/error_macros.h"
#ifdef JAVASCRIPT_ENABLED
#include "emscripten.h"
#include "emws_client.h"
@@ -40,24 +40,19 @@
#include "wsl_client.h"
#include "wsl_server.h"
#endif
+#ifdef TOOLS_ENABLED
+#include "editor/debugger/editor_debugger_server.h"
+#include "editor/editor_node.h"
+#include "editor_debugger_server_websocket.h"
+#endif
-void register_websocket_types() {
-#define _SET_HINT(NAME, _VAL_, _MAX_) \
- GLOBAL_DEF(NAME, _VAL_); \
- ProjectSettings::get_singleton()->set_custom_property_info(NAME, PropertyInfo(Variant::INT, NAME, PROPERTY_HINT_RANGE, "2," #_MAX_ ",1,or_greater"));
-
- // Client buffers project settings
- _SET_HINT(WSC_IN_BUF, 64, 4096);
- _SET_HINT(WSC_IN_PKT, 1024, 16384);
- _SET_HINT(WSC_OUT_BUF, 64, 4096);
- _SET_HINT(WSC_OUT_PKT, 1024, 16384);
-
- // Server buffers project settings
- _SET_HINT(WSS_IN_BUF, 64, 4096);
- _SET_HINT(WSS_IN_PKT, 1024, 16384);
- _SET_HINT(WSS_OUT_BUF, 64, 4096);
- _SET_HINT(WSS_OUT_PKT, 1024, 16384);
+#ifdef TOOLS_ENABLED
+static void _editor_init_callback() {
+ EditorDebuggerServer::register_protocol_handler("ws://", EditorDebuggerServerWebSocket::create);
+}
+#endif
+void register_websocket_types() {
#ifdef JAVASCRIPT_ENABLED
EMWSPeer::make_default();
EMWSClient::make_default();
@@ -72,6 +67,10 @@ void register_websocket_types() {
ClassDB::register_custom_instance_class<WebSocketServer>();
ClassDB::register_custom_instance_class<WebSocketClient>();
ClassDB::register_custom_instance_class<WebSocketPeer>();
+
+#ifdef TOOLS_ENABLED
+ EditorNode::add_init_callback(&_editor_init_callback);
+#endif
}
void unregister_websocket_types() {}
diff --git a/modules/websocket/register_types.h b/modules/websocket/register_types.h
index bb7be57ab3..3884db67b7 100644
--- a/modules/websocket/register_types.h
+++ b/modules/websocket/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/websocket/remote_debugger_peer_websocket.cpp b/modules/websocket/remote_debugger_peer_websocket.cpp
new file mode 100644
index 0000000000..c9591cc564
--- /dev/null
+++ b/modules/websocket/remote_debugger_peer_websocket.cpp
@@ -0,0 +1,133 @@
+/*************************************************************************/
+/* remote_debugger_peer_websocket.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "remote_debugger_peer_websocket.h"
+
+#include "core/config/project_settings.h"
+
+Error RemoteDebuggerPeerWebSocket::connect_to_host(const String &p_uri) {
+ Vector<String> protocols;
+ protocols.push_back("binary"); // Compatibility for emscripten TCP-to-WebSocket.
+
+ ws_client->connect_to_url(p_uri, protocols);
+ ws_client->poll();
+
+ if (ws_client->get_connection_status() == WebSocketClient::CONNECTION_DISCONNECTED) {
+ ERR_PRINT("Remote Debugger: Unable to connect. Status: " + String::num(ws_client->get_connection_status()) + ".");
+ return FAILED;
+ }
+
+ ws_peer = ws_client->get_peer(1);
+
+ return OK;
+}
+
+bool RemoteDebuggerPeerWebSocket::is_peer_connected() {
+ return ws_peer.is_valid() && ws_peer->is_connected_to_host();
+}
+
+void RemoteDebuggerPeerWebSocket::poll() {
+ ws_client->poll();
+
+ while (ws_peer->is_connected_to_host() && ws_peer->get_available_packet_count() > 0 && in_queue.size() < max_queued_messages) {
+ Variant var;
+ Error err = ws_peer->get_var(var);
+ ERR_CONTINUE(err != OK);
+ ERR_CONTINUE(var.get_type() != Variant::ARRAY);
+ in_queue.push_back(var);
+ }
+
+ while (ws_peer->is_connected_to_host() && out_queue.size() > 0) {
+ Array var = out_queue[0];
+ Error err = ws_peer->put_var(var);
+ ERR_BREAK(err != OK); // Peer buffer full?
+ out_queue.pop_front();
+ }
+}
+
+int RemoteDebuggerPeerWebSocket::get_max_message_size() const {
+ return 8 << 20; // 8 Mib
+}
+
+bool RemoteDebuggerPeerWebSocket::has_message() {
+ return in_queue.size() > 0;
+}
+
+Array RemoteDebuggerPeerWebSocket::get_message() {
+ ERR_FAIL_COND_V(in_queue.size() < 1, Array());
+ Array msg = in_queue[0];
+ in_queue.pop_front();
+ return msg;
+}
+
+Error RemoteDebuggerPeerWebSocket::put_message(const Array &p_arr) {
+ if (out_queue.size() >= max_queued_messages) {
+ return ERR_OUT_OF_MEMORY;
+ }
+ out_queue.push_back(p_arr);
+ return OK;
+}
+
+void RemoteDebuggerPeerWebSocket::close() {
+ if (ws_peer.is_valid()) {
+ ws_peer.unref();
+ }
+ ws_client->disconnect_from_host();
+}
+
+bool RemoteDebuggerPeerWebSocket::can_block() const {
+#ifdef JAVASCRIPT_ENABLED
+ return false;
+#else
+ return true;
+#endif
+}
+
+RemoteDebuggerPeerWebSocket::RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer) {
+#ifdef JAVASCRIPT_ENABLED
+ ws_client = Ref<WebSocketClient>(memnew(EMWSClient));
+#else
+ ws_client = Ref<WebSocketClient>(memnew(WSLClient));
+#endif
+ max_queued_messages = (int)GLOBAL_GET("network/limits/debugger/max_queued_messages");
+ ws_client->set_buffers(8192, max_queued_messages, 8192, max_queued_messages);
+ ws_peer = p_peer;
+}
+
+RemoteDebuggerPeer *RemoteDebuggerPeerWebSocket::create(const String &p_uri) {
+ ERR_FAIL_COND_V(!p_uri.begins_with("ws://") && !p_uri.begins_with("wss://"), nullptr);
+ RemoteDebuggerPeerWebSocket *peer = memnew(RemoteDebuggerPeerWebSocket);
+ Error err = peer->connect_to_host(p_uri);
+ if (err != OK) {
+ memdelete(peer);
+ return nullptr;
+ }
+ return peer;
+}
diff --git a/modules/websocket/remote_debugger_peer_websocket.h b/modules/websocket/remote_debugger_peer_websocket.h
new file mode 100644
index 0000000000..03c60fb480
--- /dev/null
+++ b/modules/websocket/remote_debugger_peer_websocket.h
@@ -0,0 +1,65 @@
+/*************************************************************************/
+/* remote_debugger_peer_websocket.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 SCRIPT_DEBUGGER_WEBSOCKET_H
+#define SCRIPT_DEBUGGER_WEBSOCKET_H
+
+#ifdef JAVASCRIPT_ENABLED
+#include "modules/websocket/emws_client.h"
+#else
+#include "modules/websocket/wsl_client.h"
+#endif
+#include "core/debugger/remote_debugger_peer.h"
+
+class RemoteDebuggerPeerWebSocket : public RemoteDebuggerPeer {
+ Ref<WebSocketClient> ws_client;
+ Ref<WebSocketPeer> ws_peer;
+ List<Array> in_queue;
+ List<Array> out_queue;
+
+ int max_queued_messages;
+
+public:
+ static RemoteDebuggerPeer *create(const String &p_uri);
+
+ Error connect_to_host(const String &p_uri);
+ bool is_peer_connected();
+ int get_max_message_size() const;
+ bool has_message();
+ Error put_message(const Array &p_arr);
+ Array get_message();
+ void close();
+ void poll();
+ bool can_block() const;
+
+ RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer = Ref<WebSocketPeer>());
+};
+
+#endif // SCRIPT_DEBUGGER_WEBSOCKET_H
diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp
index 7ee4b990b5..eb0252e6d1 100644
--- a/modules/websocket/websocket_client.cpp
+++ b/modules/websocket/websocket_client.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
GDCINULL(WebSocketClient);
WebSocketClient::WebSocketClient() {
-
verify_ssl = true;
}
@@ -54,8 +53,9 @@ Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_proto
port = 443;
} else {
ssl = false;
- if (host.begins_with("ws://"))
+ if (host.begins_with("ws://")) {
host = host.substr(5, host.length() - 5);
+ }
}
// Path
@@ -66,7 +66,7 @@ Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_proto
}
// Port
- p_len = host.find_last(":");
+ p_len = host.rfind(":");
if (p_len != -1 && p_len == host.find(":")) {
port = host.substr(p_len, host.length() - p_len).to_int();
host = host.substr(0, p_len);
@@ -76,33 +76,27 @@ Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_proto
}
void WebSocketClient::set_verify_ssl_enabled(bool p_verify_ssl) {
-
verify_ssl = p_verify_ssl;
}
bool WebSocketClient::is_verify_ssl_enabled() const {
-
return verify_ssl;
}
Ref<X509Certificate> WebSocketClient::get_trusted_ssl_certificate() const {
-
return ssl_cert;
}
void WebSocketClient::set_trusted_ssl_certificate(Ref<X509Certificate> p_cert) {
-
ERR_FAIL_COND(get_connection_status() != CONNECTION_DISCONNECTED);
ssl_cert = p_cert;
}
bool WebSocketClient::is_server() const {
-
return false;
}
void WebSocketClient::_on_peer_packet() {
-
if (_is_multiplayer) {
_process_multiplayer(get_peer(1), 1);
} else {
@@ -111,7 +105,6 @@ void WebSocketClient::_on_peer_packet() {
}
void WebSocketClient::_on_connect(String p_protocol) {
-
if (_is_multiplayer) {
// need to wait for ID confirmation...
} else {
@@ -120,12 +113,10 @@ void WebSocketClient::_on_connect(String p_protocol) {
}
void WebSocketClient::_on_close_request(int p_code, String p_reason) {
-
emit_signal("server_close_request", p_code, p_reason);
}
void WebSocketClient::_on_disconnect(bool p_was_clean) {
-
if (_is_multiplayer) {
emit_signal("connection_failed");
} else {
@@ -134,7 +125,6 @@ void WebSocketClient::_on_disconnect(bool p_was_clean) {
}
void WebSocketClient::_on_error() {
-
if (_is_multiplayer) {
emit_signal("connection_failed");
} else {
diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h
index 4dc1224066..78b77b89cd 100644
--- a/modules/websocket/websocket_client.h
+++ b/modules/websocket/websocket_client.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,12 +32,11 @@
#define WEBSOCKET_CLIENT_H
#include "core/crypto/crypto.h"
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "websocket_multiplayer_peer.h"
#include "websocket_peer.h"
class WebSocketClient : public WebSocketMultiplayerPeer {
-
GDCLASS(WebSocketClient, WebSocketMultiplayerPeer);
GDCICLASS(WebSocketClient);
@@ -56,14 +55,12 @@ public:
Ref<X509Certificate> get_trusted_ssl_certificate() const;
void set_trusted_ssl_certificate(Ref<X509Certificate> p_cert);
- virtual void poll() = 0;
virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0;
virtual void disconnect_from_host(int p_code = 1000, String p_reason = "") = 0;
virtual IP_Address get_connected_host() const = 0;
virtual uint16_t get_connected_port() const = 0;
- virtual bool is_server() const;
- virtual ConnectionStatus get_connection_status() const = 0;
+ virtual bool is_server() const override;
void _on_peer_packet();
void _on_connect(String p_protocol);
@@ -71,8 +68,6 @@ 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_macros.h b/modules/websocket/websocket_macros.h
index f7eafcff1f..d04909c97d 100644
--- a/modules/websocket/websocket_macros.h
+++ b/modules/websocket/websocket_macros.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,15 +31,9 @@
#ifndef WEBSOCKETMACTOS_H
#define WEBSOCKETMACTOS_H
-#define WSC_IN_BUF "network/limits/websocket_client/max_in_buffer_kb"
-#define WSC_IN_PKT "network/limits/websocket_client/max_in_packets"
-#define WSC_OUT_BUF "network/limits/websocket_client/max_out_buffer_kb"
-#define WSC_OUT_PKT "network/limits/websocket_client/max_out_packets"
-
-#define WSS_IN_BUF "network/limits/websocket_server/max_in_buffer_kb"
-#define WSS_IN_PKT "network/limits/websocket_server/max_in_packets"
-#define WSS_OUT_BUF "network/limits/websocket_server/max_out_buffer_kb"
-#define WSS_OUT_PKT "network/limits/websocket_server/max_out_packets"
+// Defaults per peer buffers, 1024 packets with a shared 65536 bytes payload.
+#define DEF_PKT_SHIFT 10
+#define DEF_BUF_SHIFT 16
/* clang-format off */
#define GDCICLASS(CNAME) \
diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp
index 9b71b32e33..f94642475c 100644
--- a/modules/websocket/websocket_multiplayer_peer.cpp
+++ b/modules/websocket/websocket_multiplayer_peer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,6 @@
#include "core/os/os.h"
WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() {
-
_is_multiplayer = false;
_peer_id = 0;
_target_peer = 0;
@@ -46,16 +45,13 @@ WebSocketMultiplayerPeer::WebSocketMultiplayerPeer() {
}
WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() {
-
_clear();
}
int WebSocketMultiplayerPeer::_gen_unique_id() const {
-
uint32_t hash = 0;
while (hash == 0 || hash == 1) {
-
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_ticks_usec());
hash = hash_djb2_one_32(
@@ -71,11 +67,12 @@ int WebSocketMultiplayerPeer::_gen_unique_id() const {
return hash;
}
-void WebSocketMultiplayerPeer::_clear() {
+void WebSocketMultiplayerPeer::_clear() {
_peer_map.clear();
- if (_current_packet.data != nullptr)
+ if (_current_packet.data != nullptr) {
memfree(_current_packet.data);
+ }
for (List<Packet>::Element *E = _incoming_packets.front(); E; E = E->next()) {
memfree(E->get().data);
@@ -86,7 +83,6 @@ 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);
@@ -97,14 +93,12 @@ void WebSocketMultiplayerPeer::_bind_methods() {
// PacketPeer
//
int WebSocketMultiplayerPeer::get_available_packet_count() const {
-
ERR_FAIL_COND_V_MSG(!_is_multiplayer, 0, "Please use get_peer(ID).get_available_packet_count to get available packet count from peers when not using the MultiplayerAPI.");
return _incoming_packets.size();
}
Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
-
ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).get_packet/var to communicate with peers when not using the MultiplayerAPI.");
r_buffer_size = 0;
@@ -124,7 +118,6 @@ Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buff
}
Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
-
ERR_FAIL_COND_V_MSG(!_is_multiplayer, ERR_UNCONFIGURED, "Please use get_peer(ID).put_packet/var to communicate with peers when not using the MultiplayerAPI.");
Vector<uint8_t> buffer = _make_pkt(SYS_NONE, get_unique_id(), _target_peer, p_buffer, p_buffer_size);
@@ -140,23 +133,19 @@ Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer
// NetworkedMultiplayerPeer
//
void WebSocketMultiplayerPeer::set_transfer_mode(TransferMode p_mode) {
-
// Websocket uses TCP, reliable
}
NetworkedMultiplayerPeer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const {
-
// Websocket uses TCP, reliable
return TRANSFER_MODE_RELIABLE;
}
void WebSocketMultiplayerPeer::set_target_peer(int p_target_peer) {
-
_target_peer = p_target_peer;
}
int WebSocketMultiplayerPeer::get_packet_peer() const {
-
ERR_FAIL_COND_V_MSG(!_is_multiplayer, 1, "This function is not available when not using the MultiplayerAPI.");
ERR_FAIL_COND_V(_incoming_packets.size() == 0, 1);
@@ -164,22 +153,18 @@ int WebSocketMultiplayerPeer::get_packet_peer() const {
}
int WebSocketMultiplayerPeer::get_unique_id() const {
-
return _peer_id;
}
void WebSocketMultiplayerPeer::set_refuse_new_connections(bool p_enable) {
-
_refusing = p_enable;
}
bool WebSocketMultiplayerPeer::is_refusing_new_connections() const {
-
return _refusing;
}
void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_type, int32_t p_peer_id) {
-
ERR_FAIL_COND(!p_peer.is_valid());
ERR_FAIL_COND(!p_peer->is_connected_to_host());
@@ -188,7 +173,6 @@ void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_ty
}
Vector<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) {
-
Vector<uint8_t> out;
out.resize(PROTO_SIZE + p_data_size);
@@ -202,7 +186,6 @@ Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_fr
}
void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) {
-
// First of all, confirm the ID!
_send_sys(get_peer(p_peer_id), SYS_ID, p_peer_id);
@@ -211,8 +194,9 @@ void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) {
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
int32_t id = E->key();
- if (p_peer_id == id)
+ if (p_peer_id == id) {
continue; // Skip the newwly added peer (already confirmed)
+ }
// Send new peer to others
_send_sys(get_peer(id), SYS_ADD, p_peer_id);
@@ -224,8 +208,9 @@ void WebSocketMultiplayerPeer::_send_add(int32_t p_peer_id) {
void WebSocketMultiplayerPeer::_send_del(int32_t p_peer_id) {
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
int32_t id = E->key();
- if (p_peer_id != id)
+ if (p_peer_id != id) {
_send_sys(get_peer(id), SYS_DEL, p_peer_id);
+ }
}
}
@@ -242,27 +227,25 @@ void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, cons
Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) {
if (p_to == 1) {
-
return OK; // Will not send to self
} else if (p_to == 0) {
-
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
- if (E->key() != p_from)
+ if (E->key() != p_from) {
E->get()->put_packet(p_buffer, p_buffer_size);
+ }
}
return OK; // Sent to all but sender
} else if (p_to < 0) {
-
for (Map<int, Ref<WebSocketPeer>>::Element *E = _peer_map.front(); E; E = E->next()) {
- if (E->key() != p_from && E->key() != -p_to)
+ if (E->key() != p_from && E->key() != -p_to) {
E->get()->put_packet(p_buffer, p_buffer_size);
+ }
}
return OK; // Sent to all but sender and excluded
} else {
-
ERR_FAIL_COND_V(p_to == p_from, FAILED);
Ref<WebSocketPeer> peer_to = get_peer(p_to);
@@ -273,7 +256,6 @@ Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, cons
}
void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id) {
-
ERR_FAIL_COND(!p_peer.is_valid());
const uint8_t *in_buffer;
@@ -304,21 +286,19 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u
_store_pkt(from, to, in_buffer, data_size);
} else if (to == 0) {
-
// Broadcast, for us too
_store_pkt(from, to, in_buffer, data_size);
} else if (to < 0) {
-
// All but one, for us if not excluded
- if (_peer_id != -(int32_t)p_peer_id)
+ if (_peer_id != -(int32_t)p_peer_id) {
_store_pkt(from, to, in_buffer, data_size);
+ }
}
// Relay if needed (i.e. "to" includes a peer that is not the server)
_server_relay(from, to, in_buffer, size);
} else {
-
if (type == SYS_NONE) { // Payload message
_store_pkt(from, to, in_buffer, data_size);
@@ -331,12 +311,12 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u
copymem(&id, &in_buffer[PROTO_SIZE], 4);
switch (type) {
-
case SYS_ADD: // Add peer
_peer_map[id] = Ref<WebSocketPeer>();
emit_signal("peer_connected", id);
- if (id == 1) // We just connected to the server
+ if (id == 1) { // We just connected to the server
emit_signal("connection_succeeded");
+ }
break;
case SYS_DEL: // Remove peer
diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h
index c6669c730c..e593163b7c 100644
--- a/modules/websocket/websocket_multiplayer_peer.h
+++ b/modules/websocket/websocket_multiplayer_peer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,13 +31,12 @@
#ifndef WEBSOCKET_MULTIPLAYER_PEER_H
#define WEBSOCKET_MULTIPLAYER_PEER_H
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "core/io/networked_multiplayer_peer.h"
-#include "core/list.h"
+#include "core/templates/list.h"
#include "websocket_peer.h"
class WebSocketMultiplayerPeer : public NetworkedMultiplayerPeer {
-
GDCLASS(WebSocketMultiplayerPeer, NetworkedMultiplayerPeer);
private:
@@ -80,21 +79,18 @@ protected:
public:
/* NetworkedMultiplayerPeer */
- void set_transfer_mode(TransferMode p_mode);
- TransferMode get_transfer_mode() const;
- void set_target_peer(int p_target_peer);
- int get_packet_peer() const;
- int get_unique_id() const;
- virtual bool is_server() const = 0;
- void set_refuse_new_connections(bool p_enable);
- bool is_refusing_new_connections() const;
- virtual ConnectionStatus get_connection_status() const = 0;
+ void set_transfer_mode(TransferMode p_mode) override;
+ TransferMode get_transfer_mode() const override;
+ void set_target_peer(int p_target_peer) override;
+ int get_packet_peer() const override;
+ int get_unique_id() const override;
+ void set_refuse_new_connections(bool p_enable) override;
+ bool is_refusing_new_connections() const override;
/* PacketPeer */
- virtual int get_available_packet_count() const;
- virtual int get_max_packet_size() const = 0;
- 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_available_packet_count() const override;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
/* WebSocketPeer */
virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0;
diff --git a/modules/websocket/websocket_peer.cpp b/modules/websocket/websocket_peer.cpp
index 30a5972330..e77fdcfed2 100644
--- a/modules/websocket/websocket_peer.cpp
+++ b/modules/websocket/websocket_peer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
diff --git a/modules/websocket/websocket_peer.h b/modules/websocket/websocket_peer.h
index d4173600ec..2ba83637f9 100644
--- a/modules/websocket/websocket_peer.h
+++ b/modules/websocket/websocket_peer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,12 +31,11 @@
#ifndef WEBSOCKETPEER_H
#define WEBSOCKETPEER_H
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "core/io/packet_peer.h"
#include "websocket_macros.h"
class WebSocketPeer : public PacketPeer {
-
GDCLASS(WebSocketPeer, PacketPeer);
GDCICLASS(WebSocketPeer);
@@ -50,11 +49,6 @@ protected:
static void _bind_methods();
public:
- virtual int get_available_packet_count() const = 0;
- virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) = 0;
- virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) = 0;
- virtual int get_max_packet_size() const = 0;
-
virtual WriteMode get_write_mode() const = 0;
virtual void set_write_mode(WriteMode p_mode) = 0;
diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp
index a7ced65543..f57e8d959c 100644
--- a/modules/websocket/websocket_server.cpp
+++ b/modules/websocket/websocket_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -41,7 +41,6 @@ WebSocketServer::~WebSocketServer() {
}
void WebSocketServer::_bind_methods() {
-
ClassDB::bind_method(D_METHOD("is_listening"), &WebSocketServer::is_listening);
ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(Vector<String>()), DEFVAL(false));
ClassDB::bind_method(D_METHOD("stop"), &WebSocketServer::stop);
@@ -110,19 +109,18 @@ void WebSocketServer::set_ca_chain(Ref<X509Certificate> p_ca_chain) {
}
NetworkedMultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const {
- if (is_listening())
+ if (is_listening()) {
return CONNECTION_CONNECTED;
+ }
return CONNECTION_DISCONNECTED;
}
bool WebSocketServer::is_server() const {
-
return true;
}
void WebSocketServer::_on_peer_packet(int32_t p_peer_id) {
-
if (_is_multiplayer) {
_process_multiplayer(get_peer(p_peer_id), p_peer_id);
} else {
@@ -131,7 +129,6 @@ void WebSocketServer::_on_peer_packet(int32_t p_peer_id) {
}
void WebSocketServer::_on_connect(int32_t p_peer_id, String p_protocol) {
-
if (_is_multiplayer) {
// Send add to clients
_send_add(p_peer_id);
@@ -142,7 +139,6 @@ void WebSocketServer::_on_connect(int32_t p_peer_id, String p_protocol) {
}
void WebSocketServer::_on_disconnect(int32_t p_peer_id, bool p_was_clean) {
-
if (_is_multiplayer) {
// Send delete to clients
_send_del(p_peer_id);
@@ -153,6 +149,5 @@ void WebSocketServer::_on_disconnect(int32_t p_peer_id, bool p_was_clean) {
}
void WebSocketServer::_on_close_request(int32_t p_peer_id, int p_code, String p_reason) {
-
emit_signal("client_close_request", p_peer_id, p_code, p_reason);
}
diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h
index 3ce4dbe711..3fbd5e3b95 100644
--- a/modules/websocket/websocket_server.h
+++ b/modules/websocket/websocket_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -32,12 +32,11 @@
#define WEBSOCKET_H
#include "core/crypto/crypto.h"
-#include "core/reference.h"
+#include "core/object/reference.h"
#include "websocket_multiplayer_peer.h"
#include "websocket_peer.h"
class WebSocketServer : public WebSocketMultiplayerPeer {
-
GDCLASS(WebSocketServer, WebSocketMultiplayerPeer);
GDCICLASS(WebSocketServer);
@@ -51,14 +50,12 @@ protected:
Ref<X509Certificate> ca_chain;
public:
- virtual void poll() = 0;
virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0;
virtual void stop() = 0;
virtual bool is_listening() const = 0;
virtual bool has_peer(int p_id) const = 0;
- virtual Ref<WebSocketPeer> get_peer(int p_id) const = 0;
- virtual bool is_server() const;
- ConnectionStatus get_connection_status() const;
+ virtual bool is_server() const override;
+ ConnectionStatus get_connection_status() const override;
virtual IP_Address get_peer_address(int p_peer_id) const = 0;
virtual int get_peer_port(int p_peer_id) const = 0;
@@ -81,8 +78,6 @@ public:
Ref<X509Certificate> get_ca_chain() const;
void set_ca_chain(Ref<X509Certificate> p_ca_chain);
- 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
index 9f05500eb9..3e2f48e9b3 100644
--- a/modules/websocket/wsl_client.cpp
+++ b/modules/websocket/wsl_client.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef JAVASCRIPT_ENABLED
#include "wsl_client.h"
+#include "core/config/project_settings.h"
#include "core/io/ip.h"
-#include "core/project_settings.h"
void WSLClient::_do_handshake() {
if (_requested < _request.size() - 1) {
@@ -117,10 +117,11 @@ bool WSLClient::_verify_headers(String &r_protocol) {
ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i] + ".");
String name = header[0].to_lower();
String value = header[1].strip_edges();
- if (headers.has(name))
+ if (headers.has(name)) {
headers[name] += "," + value;
- else
+ } else {
headers[name] = value;
+ }
}
#define _WSL_CHECK(NAME, VALUE) \
@@ -142,19 +143,20 @@ bool WSLClient::_verify_headers(String &r_protocol) {
r_protocol = headers["sec-websocket-protocol"];
bool valid = false;
for (int i = 0; i < _protocols.size(); i++) {
- if (_protocols[i] != r_protocol)
+ if (_protocols[i] != r_protocol) {
continue;
+ }
valid = true;
break;
}
- if (!valid)
+ if (!valid) {
return false;
+ }
}
return true;
}
Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
-
ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE);
_peer = Ref<WSLPeer>(memnew(WSLPeer));
@@ -200,8 +202,9 @@ Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port,
if (p_protocols.size() > 0) {
request += "Sec-WebSocket-Protocol: ";
for (int i = 0; i < p_protocols.size(); i++) {
- if (i != 0)
+ if (i != 0) {
request += ",";
+ }
request += p_protocols[i];
}
request += "\r\n";
@@ -229,8 +232,9 @@ void WSLClient::poll() {
return;
}
- if (_connection.is_null())
+ if (_connection.is_null()) {
return; // Not connected.
+ }
switch (_tcp->get_status()) {
case StreamPeerTCP::STATUS_NONE:
@@ -257,9 +261,9 @@ void WSLClient::poll() {
ERR_FAIL_COND(ssl.is_null()); // Bug?
ssl->poll();
}
- if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
+ if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
return; // Need more polling.
- else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
+ } else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
disconnect_from_host();
_on_error();
return; // Error.
@@ -278,25 +282,24 @@ void WSLClient::poll() {
}
Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const {
-
ERR_FAIL_COND_V(p_peer_id != 1, nullptr);
return _peer;
}
NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
-
- if (_peer->is_connected_to_host())
+ if (_peer->is_connected_to_host()) {
return CONNECTION_CONNECTED;
+ }
- if (_tcp->is_connected_to_host())
+ 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>(nullptr);
_tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP));
@@ -314,13 +317,11 @@ void WSLClient::disconnect_from_host(int p_code, String p_reason) {
}
IP_Address WSLClient::get_connected_host() const {
-
ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IP_Address());
return _peer->get_connected_host();
}
uint16_t WSLClient::get_connected_port() const {
-
ERR_FAIL_COND_V(!_peer->is_connected_to_host(), 0);
return _peer->get_connected_port();
}
@@ -336,10 +337,10 @@ Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer
}
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);
+ _in_buf_size = DEF_BUF_SHIFT;
+ _in_pkt_size = DEF_PKT_SHIFT;
+ _out_buf_size = DEF_BUF_SHIFT;
+ _out_pkt_size = DEF_PKT_SHIFT;
_peer.instance();
_tcp.instance();
@@ -347,7 +348,6 @@ WSLClient::WSLClient() {
}
WSLClient::~WSLClient() {
-
_peer->close_now();
_peer->invalidate();
disconnect_from_host();
diff --git a/modules/websocket/wsl_client.h b/modules/websocket/wsl_client.h
index 2cecfd97ee..8712b57f2c 100644
--- a/modules/websocket/wsl_client.h
+++ b/modules/websocket/wsl_client.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,7 +33,7 @@
#ifndef JAVASCRIPT_ENABLED
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "core/io/stream_peer_ssl.h"
#include "core/io/stream_peer_tcp.h"
#include "websocket_client.h"
@@ -41,7 +41,6 @@
#include "wslay/wslay.h"
class WSLClient : public WebSocketClient {
-
GDCIIMPL(WSLClient, WebSocketClient);
private:
diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp
index 44b71f70f4..9d016e1139 100644
--- a/modules/websocket/wsl_peer.cpp
+++ b/modules/websocket/wsl_peer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -60,8 +60,9 @@ String WSLPeer::compute_key_response(String p_key) {
}
void WSLPeer::_wsl_destroy(struct PeerData **p_data) {
- if (!p_data || !(*p_data))
+ if (!p_data || !(*p_data)) {
return;
+ }
struct PeerData *data = *p_data;
if (data->polling) {
data->destroy = true;
@@ -147,8 +148,9 @@ void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event
}
WSLPeer *peer = (WSLPeer *)peer_data->peer;
- if (peer->parse_message(arg) != OK)
+ if (peer->parse_message(arg) != OK) {
return;
+ }
if (peer_data->is_server) {
WSLServer *helper = (WSLServer *)peer_data->obj;
@@ -209,10 +211,11 @@ void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigne
_data->peer = this;
_data->valid = true;
- if (_data->is_server)
+ if (_data->is_server) {
wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data);
- else
+ } else {
wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data);
+ }
wslay_event_config_set_max_recv_msg_length(_data->ctx, (1ULL << p_in_buf_size));
}
@@ -225,8 +228,9 @@ WSLPeer::WriteMode WSLPeer::get_write_mode() const {
}
void WSLPeer::poll() {
- if (!_data)
+ if (!_data) {
return;
+ }
if (_wsl_poll(_data)) {
_data = nullptr;
@@ -234,7 +238,6 @@ void WSLPeer::poll() {
}
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?
@@ -251,13 +254,13 @@ Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
}
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)
+ if (_in_buffer.packets_left() == 0) {
return ERR_UNAVAILABLE;
+ }
int read = 0;
uint8_t *rw = _packet_buffer.ptrw();
@@ -270,20 +273,18 @@ Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
}
int WSLPeer::get_available_packet_count() const {
-
- if (!is_connected_to_host())
+ 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 != nullptr;
}
@@ -305,28 +306,26 @@ void WSLPeer::close(int p_code, String p_reason) {
}
IP_Address WSLPeer::get_connected_host() const {
-
ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IP_Address());
return _data->tcp->get_connected_host();
}
uint16_t WSLPeer::get_connected_port() const {
-
ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), 0);
return _data->tcp->get_connected_port();
}
void WSLPeer::set_no_delay(bool p_enabled) {
-
ERR_FAIL_COND(!is_connected_to_host() || _data->tcp.is_null());
_data->tcp->set_no_delay(p_enabled);
}
void WSLPeer::invalidate() {
- if (_data)
+ if (_data) {
_data->valid = false;
+ }
}
WSLPeer::WSLPeer() {
@@ -337,7 +336,6 @@ WSLPeer::WSLPeer() {
}
WSLPeer::~WSLPeer() {
-
close();
invalidate();
_wsl_destroy(&_data);
diff --git a/modules/websocket/wsl_peer.h b/modules/websocket/wsl_peer.h
index 3b0639831a..01efa4b21e 100644
--- a/modules/websocket/wsl_peer.h
+++ b/modules/websocket/wsl_peer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -33,10 +33,10 @@
#ifndef JAVASCRIPT_ENABLED
-#include "core/error_list.h"
+#include "core/error/error_list.h"
#include "core/io/packet_peer.h"
#include "core/io/stream_peer_tcp.h"
-#include "core/ring_buffer.h"
+#include "core/templates/ring_buffer.h"
#include "packet_buffer.h"
#include "websocket_peer.h"
#include "wslay/wslay.h"
@@ -44,7 +44,6 @@
#define WSL_MAX_HEADER_SIZE 4096
class WSLPeer : public WebSocketPeer {
-
GDCIIMPL(WSLPeer, WebSocketPeer);
public:
diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp
index 6f155a6ffa..9df076bf3f 100644
--- a/modules/websocket/wsl_server.cpp
+++ b/modules/websocket/wsl_server.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -31,8 +31,8 @@
#ifndef JAVASCRIPT_ENABLED
#include "wsl_server.h"
+#include "core/config/project_settings.h"
#include "core/os/os.h"
-#include "core/project_settings.h"
WSLServer::PendingPeer::PendingPeer() {
use_ssl = false;
@@ -60,10 +60,11 @@ bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
ERR_FAIL_COND_V_MSG(header.size() != 2, false, "Invalid header -> " + psa[i]);
String name = header[0].to_lower();
String value = header[1].strip_edges();
- if (headers.has(name))
+ if (headers.has(name)) {
headers[name] += "," + value;
- else
+ } else {
headers[name] = value;
+ }
}
#define _WSL_CHECK(NAME, VALUE) \
ERR_FAIL_COND_V_MSG(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false, \
@@ -83,44 +84,52 @@ bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) {
String proto = protos[i].strip_edges();
// Check if we have the given protocol
for (int j = 0; j < p_protocols.size(); j++) {
- if (proto != p_protocols[j])
+ if (proto != p_protocols[j]) {
continue;
+ }
protocol = proto;
break;
}
// Found a protocol
- if (protocol != "")
+ if (protocol != "") {
break;
+ }
}
- if (protocol == "") // Invalid protocol(s) requested
+ if (protocol == "") { // Invalid protocol(s) requested
return false;
- } else if (p_protocols.size() > 0) // No protocol requested, but we need one
+ }
+ } else if (p_protocols.size() > 0) { // No protocol requested, but we need one
return false;
+ }
return true;
}
Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) {
- if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT)
+ if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT) {
return ERR_TIMEOUT;
+ }
if (use_ssl) {
Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL>>(connection);
- if (ssl.is_null())
+ if (ssl.is_null()) {
return FAILED;
+ }
ssl->poll();
- if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
+ if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) {
return ERR_BUSY;
- else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED)
+ } else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
return FAILED;
+ }
}
if (!has_request) {
int read = 0;
while (true) {
ERR_FAIL_COND_V_MSG(req_pos >= WSL_MAX_HEADER_SIZE, ERR_OUT_OF_MEMORY, "Response headers too big.");
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
- if (err != OK) // Got an error
+ if (err != OK) { // Got an error
return FAILED;
- else if (read != 1) // Busy, wait next poll
+ } 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') {
@@ -132,8 +141,9 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) {
s += "Upgrade: websocket\r\n";
s += "Connection: Upgrade\r\n";
s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
- if (protocol != "")
+ if (protocol != "") {
s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
+ }
s += "\r\n";
response = s.utf8();
has_request = true;
@@ -150,8 +160,9 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) {
}
response_sent += sent;
}
- if (response_sent < response.size() - 1)
+ if (response_sent < response.size() - 1) {
return ERR_BUSY;
+ }
return OK;
}
@@ -169,7 +180,6 @@ Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp
}
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();
@@ -217,13 +227,15 @@ void WSLServer::poll() {
}
remove_peers.clear();
- if (!_server->is_listening())
+ if (!_server->is_listening()) {
return;
+ }
while (_server->is_connection_available()) {
Ref<StreamPeerTCP> conn = _server->take_connection();
- if (is_refusing_new_connections())
+ if (is_refusing_new_connections()) {
continue; // Conn will go out-of-scope and be closed.
+ }
Ref<PendingPeer> peer = memnew(PendingPeer);
if (private_key.is_valid() && ssl_cert.is_valid()) {
@@ -298,10 +310,10 @@ Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer
}
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);
+ _in_buf_size = DEF_BUF_SHIFT;
+ _in_pkt_size = DEF_PKT_SHIFT;
+ _out_buf_size = DEF_BUF_SHIFT;
+ _out_pkt_size = DEF_PKT_SHIFT;
_server.instance();
}
diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h
index 2e893d6727..8b2d4d3a04 100644
--- a/modules/websocket/wsl_server.h
+++ b/modules/websocket/wsl_server.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -43,12 +43,10 @@
#define WSL_SERVER_TIMEOUT 1000
class WSLServer : public WebSocketServer {
-
GDCIIMPL(WSLServer, WebSocketServer);
private:
class PendingPeer : public Reference {
-
private:
bool _parse_request(const Vector<String> p_protocols);
diff --git a/modules/webxr/SCsub b/modules/webxr/SCsub
new file mode 100644
index 0000000000..0a96af0811
--- /dev/null
+++ b/modules/webxr/SCsub
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+Import("env")
+Import("env_modules")
+
+if env["platform"] == "javascript":
+ env.AddJSLibraries(["native/library_godot_webxr.js"])
+ env.AddJSExterns(["native/webxr.externs.js"])
+
+env_webxr = env_modules.Clone()
+env_webxr.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/webxr/config.py b/modules/webxr/config.py
new file mode 100644
index 0000000000..9efebed4e6
--- /dev/null
+++ b/modules/webxr/config.py
@@ -0,0 +1,14 @@
+def can_build(env, platform):
+ return True
+
+
+def configure(env):
+ pass
+
+
+def get_doc_classes():
+ return ["WebXRInterface"]
+
+
+def get_doc_path():
+ return "doc_classes"
diff --git a/modules/webxr/doc_classes/WebXRInterface.xml b/modules/webxr/doc_classes/WebXRInterface.xml
new file mode 100644
index 0000000000..bddffd910e
--- /dev/null
+++ b/modules/webxr/doc_classes/WebXRInterface.xml
@@ -0,0 +1,253 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="WebXRInterface" inherits="XRInterface" version="4.0">
+ <brief_description>
+ AR/VR interface using WebXR.
+ </brief_description>
+ <description>
+ WebXR is an open standard that allows creating VR and AR applications that run in the web browser.
+ As such, this interface is only available when running in an HTML5 export.
+ WebXR supports a wide range of devices, from the very capable (like Valve Index, HTC Vive, Oculus Rift and Quest) down to the much less capable (like Google Cardboard, Oculus Go, GearVR, or plain smartphones).
+ Since WebXR is based on Javascript, it makes extensive use of callbacks, which means that [WebXRInterface] is forced to use signals, where other AR/VR interfaces would instead use functions that return a result immediately. This makes [WebXRInterface] quite a bit more complicated to intialize than other AR/VR interfaces.
+ Here's the minimum code required to start an immersive VR session:
+ [codeblock]
+ var webxr_interface
+ var vr_supported = false
+
+ func _ready():
+ # We assume this node has a canvas layer with a button on it as a child.
+ # This button is for the user to consent to entering immersive VR mode.
+ $CanvasLayer/Button.connect("pressed", self, "_on_Button_pressed")
+
+ webxr_interface = XRServer.find_interface("WebXR")
+ if webxr_interface:
+ # WebXR uses a lot of asynchronous callbacks, so we connect to various
+ # signals in order to receive them.
+ webxr_interface.connect("session_supported", self, "_webxr_session_supported")
+ webxr_interface.connect("session_started", self, "_webxr_session_started")
+ webxr_interface.connect("session_ended", self, "_webxr_session_ended")
+ webxr_interface.connect("session_failed", self, "_webxr_session_failed")
+
+ # This returns immediately - our _webxr_session_supported() method
+ # (which we connected to the "session_supported" signal above) will
+ # be called sometime later to let us know if it's supported or not.
+ webxr_interface.is_session_supported("immersive-vr")
+
+ func _webxr_session_supported(session_mode, supported):
+ if session_mode == 'immersive-vr':
+ vr_supported = supported
+
+ func _on_Button_pressed():
+ if not vr_supported:
+ OS.alert("Your browser doesn't support VR")
+ return
+
+ # We want an immersive VR session, as opposed to AR ('immersive-ar') or a
+ # simple 3DoF viewer ('viewer').
+ webxr_interface.session_mode = 'immersive-vr'
+ # 'bounded-floor' is room scale, 'local-floor' is a standing or sitting
+ # experience (it puts you 1.6m above the ground if you have 3DoF headset),
+ # whereas as 'local' puts you down at the XROrigin.
+ # This list means it'll first try to request 'bounded-floor', then
+ # fallback on 'local-floor' and ultimately 'local', if nothing else is
+ # supported.
+ webxr_interface.requested_reference_space_types = 'bounded-floor, local-floor, local'
+ # In order to use 'local-floor' or 'bounded-floor' we must also
+ # mark the features as required or optional.
+ webxr_interface.required_features = 'local-floor'
+ webxr_interface.optional_features = 'bounded-floor'
+
+ # This will return false if we're unable to even request the session,
+ # however, it can still fail asynchronously later in the process, so we
+ # only know if it's really succeeded or failed when our
+ # _webxr_session_started() or _webxr_session_failed() methods are called.
+ if not webxr_interface.initialize():
+ OS.alert("Failed to initialize")
+ return
+
+ func _webxr_session_started():
+ # This tells Godot to start rendering to the headset.
+ get_viewport().xr = true
+ # This will be the reference space type you ultimately got, out of the
+ # types that you requested above. This is useful if you want the game to
+ # work a little differently in 'bounded-floor' versus 'local-floor'.
+ print ("Reference space type: " + webxr_interface.reference_space_type)
+
+ func _webxr_session_ended():
+ # If the user exits immersive mode, then we tell Godot to render to the web
+ # page again.
+ get_viewport().xr = false
+
+ func _webxr_session_failed(message):
+ OS.alert("Failed to initialize: " + message)
+ [/codeblock]
+ There are several ways to handle "controller" input:
+ - Using [XRController3D] nodes and their [signal XRController3D.button_pressed] and [signal XRController3D.button_released] signals. This is how controllers are typically handled in AR/VR apps in Godot, however, this will only work with advanced VR controllers like the Oculus Touch or Index controllers, for example. The buttons codes are defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url].
+ - Using [method Node._unhandled_input] and [InputEventJoypadButton] or [InputEventJoypadMotion]. This works the same as normal joypads, except the [member InputEvent.device] starts at 100, so the left controller is 100 and the right controller is 101, and the button codes are also defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url].
+ - Using the [signal select], [signal squeeze] and related signals. This method will work for both advanced VR controllers, and non-traditional "controllers" like a tap on the screen, a spoken voice command or a button press on the device itself. The [code]controller_id[/code] passed to these signals is the same id as used in [member XRController3D.controller_id].
+ You can use one or all of these methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interations with more advanced devices.
+ </description>
+ <tutorials>
+ <link title="How to make a VR game for WebXR with Godot">https://www.snopekgames.com/blog/2020/how-make-vr-game-webxr-godot</link>
+ </tutorials>
+ <methods>
+ <method name="get_controller" qualifiers="const">
+ <return type="XRPositionalTracker">
+ </return>
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Gets an [XRPositionalTracker] for the given [code]controller_id[/code].
+ In the context of WebXR, a "controller" can be an advanced VR controller like the Oculus Touch or Index controllers, or even a tap on the screen, a spoken voice command or a button press on the device itself. When a non-traditional controller is used, interpret the position and orientation of the [XRPositionalTracker] as a ray pointing at the object the user wishes to interact with.
+ Use this method to get information about the controller that triggered one of these signals:
+ - [signal selectstart]
+ - [signal select]
+ - [signal selectend]
+ - [signal squeezestart]
+ - [signal squeeze]
+ - [signal squeezestart]
+ </description>
+ </method>
+ <method name="is_session_supported">
+ <return type="void">
+ </return>
+ <argument index="0" name="session_mode" type="String">
+ </argument>
+ <description>
+ Checks if the given [code]session_mode[/code] is supported by the user's browser.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRSessionMode]WebXR's XRSessionMode[/url], including: [code]"immersive-vr"[/code], [code]"immersive-ar"[/code], and [code]"inline"[/code].
+ This method returns nothing, instead it emits the [signal session_supported] signal with the result.
+ </description>
+ </method>
+ </methods>
+ <members>
+ <member name="bounds_geometry" type="PackedVector3Array" setter="" getter="get_bounds_geometry">
+ The vertices of a polygon which defines the boundaries of the user's play area.
+ This will only be available if [member reference_space_type] is [code]"bounded-floor"[/code] and only on certain browsers and devices that support it.
+ The [signal reference_space_reset] signal may indicate when this changes.
+ </member>
+ <member name="optional_features" type="String" setter="set_optional_features" getter="get_optional_features">
+ A comma-seperated list of optional features used by [method XRInterface.initialize] when setting up the WebXR session.
+ If a user's browser or device doesn't support one of the given features, initialization will continue, but you won't be able to use the requested feature.
+ This doesn't have any effect on the interface when already initialized.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features].
+ </member>
+ <member name="reference_space_type" type="String" setter="" getter="get_reference_space_type">
+ The reference space type (from the list of requested types set in the [member requested_reference_space_types] property), that was ultimately used by [method XRInterface.initialize] when setting up the WebXR session.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features].
+ </member>
+ <member name="requested_reference_space_types" type="String" setter="set_requested_reference_space_types" getter="get_requested_reference_space_types">
+ A comma-seperated list of reference space types used by [method XRInterface.initialize] when setting up the WebXR session.
+ The reference space types are requested in order, and the first on supported by the users device or browser will be used. The [member reference_space_type] property contains the reference space type that was ultimately used.
+ This doesn't have any effect on the interface when already initialized.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features].
+ </member>
+ <member name="required_features" type="String" setter="set_required_features" getter="get_required_features">
+ A comma-seperated list of required features used by [method XRInterface.initialize] when setting up the WebXR session.
+ If a user's browser or device doesn't support one of the given features, initialization will fail and [signal session_failed] will be emitted.
+ This doesn't have any effect on the interface when already initialized.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpaceType]WebXR's XRReferenceSpaceType[/url]. If you want to use a particular reference space type, it must be listed in either [member required_features] or [member optional_features].
+ </member>
+ <member name="session_mode" type="String" setter="set_session_mode" getter="get_session_mode">
+ The session mode used by [method XRInterface.initialize] when setting up the WebXR session.
+ This doesn't have any effect on the interface when already initialized.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRSessionMode]WebXR's XRSessionMode[/url], including: [code]"immersive-vr"[/code], [code]"immersive-ar"[/code], and [code]"inline"[/code].
+ </member>
+ <member name="visibility_state" type="String" setter="" getter="get_visibility_state">
+ Indicates if the WebXR session's imagery is visible to the user.
+ Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRVisibilityState]WebXR's XRVisibilityState[/url], including [code]"hidden"[/code], [code]"visible"[/code], and [code]"visible-blurred"[/code].
+ </member>
+ </members>
+ <signals>
+ <signal name="reference_space_reset">
+ <description>
+ Emitted to indicate that the reference space has been reset or reconfigured.
+ When (or whether) this is emitted depends on the user's browser or device, but may include when the user has changed the dimensions of their play space (which you may be able to access via [member bounds_geometry]) or pressed/held a button to recenter their position.
+ See [url=https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace/reset_event]WebXR's XRReferenceSpace reset event[/url] for more information.
+ </description>
+ </signal>
+ <signal name="select">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted after one of the "controllers" has finished its "primary action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="selectend">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted when one of the "controllers" has finished its "primary action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="selectstart">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted when one of the "controllers" has started its "primary action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="session_ended">
+ <description>
+ Emitted when the user ends the WebXR session (which can be done using UI from the browser or device).
+ At this point, you should do [code]get_viewport().xr = false[/code] to instruct Godot to resume rendering to the screen.
+ </description>
+ </signal>
+ <signal name="session_failed">
+ <argument index="0" name="message" type="String">
+ </argument>
+ <description>
+ Emitted by [method XRInterface.initialize] if the session fails to start.
+ [code]message[/code] may optionally contain an error message from WebXR, or an empty string if no message is available.
+ </description>
+ </signal>
+ <signal name="session_started">
+ <description>
+ Emitted by [method XRInterface.initialize] if the session is successfully started.
+ At this point, it's safe to do [code]get_viewport().xr = true[/code] to instruct Godot to start rendering to the AR/VR device.
+ </description>
+ </signal>
+ <signal name="session_supported">
+ <argument index="0" name="session_mode" type="String">
+ </argument>
+ <argument index="1" name="supported" type="bool">
+ </argument>
+ <description>
+ Emitted by [method is_session_supported] to indicate if the given [code]session_mode[/code] is supported or not.
+ </description>
+ </signal>
+ <signal name="squeeze">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted after one of the "controllers" has finished its "primary squeeze action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="squeezeend">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted when one of the "controllers" has finished its "primary squeeze action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="squeezestart">
+ <argument index="0" name="controller_id" type="int">
+ </argument>
+ <description>
+ Emitted when one of the "controllers" has started its "primary squeeze action".
+ Use [method get_controller] to get more information about the controller.
+ </description>
+ </signal>
+ <signal name="visibility_state_changed">
+ <description>
+ Emitted when [member visibility_state] has changed.
+ </description>
+ </signal>
+ </signals>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/webxr/godot_webxr.h b/modules/webxr/godot_webxr.h
new file mode 100644
index 0000000000..5e50ffde28
--- /dev/null
+++ b/modules/webxr/godot_webxr.h
@@ -0,0 +1,84 @@
+/*************************************************************************/
+/* godot_webxr.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 GODOT_WEBXR_H
+#define GODOT_WEBXR_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "stddef.h"
+
+typedef void (*GodotWebXRSupportedCallback)(char *p_session_mode, int p_supported);
+typedef void (*GodotWebXRStartedCallback)(char *p_reference_space_type);
+typedef void (*GodotWebXREndedCallback)();
+typedef void (*GodotWebXRFailedCallback)(char *p_message);
+typedef void (*GodotWebXRControllerCallback)();
+typedef void (*GodotWebXRInputEventCallback)(char *p_signal_name, int p_controller_id);
+typedef void (*GodotWebXRSimpleEventCallback)(char *p_signal_name);
+
+extern int godot_webxr_is_supported();
+extern void godot_webxr_is_session_supported(const char *p_session_mode, GodotWebXRSupportedCallback p_callback);
+
+extern void godot_webxr_initialize(
+ const char *p_session_mode,
+ const char *p_required_features,
+ const char *p_optional_features,
+ const char *p_requested_reference_space_types,
+ GodotWebXRStartedCallback p_on_session_started,
+ GodotWebXREndedCallback p_on_session_ended,
+ GodotWebXRFailedCallback p_on_session_failed,
+ GodotWebXRControllerCallback p_on_controller_changed,
+ GodotWebXRInputEventCallback p_on_input_event,
+ GodotWebXRSimpleEventCallback p_on_simple_event);
+extern void godot_webxr_uninitialize();
+
+extern int *godot_webxr_get_render_targetsize();
+extern float *godot_webxr_get_transform_for_eye(int p_eye);
+extern float *godot_webxr_get_projection_for_eye(int p_eye);
+extern int godot_webxr_get_external_texture_for_eye(int p_eye);
+extern void godot_webxr_commit_for_eye(int p_eye);
+
+extern void godot_webxr_sample_controller_data();
+extern int godot_webxr_get_controller_count();
+extern int godot_webxr_is_controller_connected(int p_controller);
+extern float *godot_webxr_get_controller_transform(int p_controller);
+extern int *godot_webxr_get_controller_buttons(int p_controller);
+extern int *godot_webxr_get_controller_axes(int p_controller);
+
+extern char *godot_webxr_get_visibility_state();
+extern int *godot_webxr_get_bounds_geometry();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GODOT_WEBXR_H */
diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js
new file mode 100644
index 0000000000..3041c16c79
--- /dev/null
+++ b/modules/webxr/native/library_godot_webxr.js
@@ -0,0 +1,651 @@
+/*************************************************************************/
+/* library_godot_webxr.js */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 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. */
+/*************************************************************************/
+const GodotWebXR = {
+ $GodotWebXR__deps: ['$Browser', '$GL', '$GodotRuntime'],
+ $GodotWebXR: {
+ gl: null,
+
+ texture_ids: [null, null],
+ textures: [null, null],
+
+ session: null,
+ space: null,
+ frame: null,
+ pose: null,
+
+ // Monkey-patch the requestAnimationFrame() used by Emscripten for the main
+ // loop, so that we can swap it out for XRSession.requestAnimationFrame()
+ // when an XR session is started.
+ orig_requestAnimationFrame: null,
+ requestAnimationFrame: (callback) => {
+ if (GodotWebXR.session && GodotWebXR.space) {
+ const onFrame = function (time, frame) {
+ GodotWebXR.frame = frame;
+ GodotWebXR.pose = frame.getViewerPose(GodotWebXR.space);
+ callback(time);
+ GodotWebXR.frame = null;
+ GodotWebXR.pose = null;
+ };
+ GodotWebXR.session.requestAnimationFrame(onFrame);
+ } else {
+ GodotWebXR.orig_requestAnimationFrame(callback);
+ }
+ },
+ monkeyPatchRequestAnimationFrame: (enable) => {
+ if (GodotWebXR.orig_requestAnimationFrame === null) {
+ GodotWebXR.orig_requestAnimationFrame = Browser.requestAnimationFrame;
+ }
+ Browser.requestAnimationFrame = enable
+ ? GodotWebXR.requestAnimationFrame : GodotWebXR.orig_requestAnimationFrame;
+ },
+ pauseResumeMainLoop: () => {
+ // Once both GodotWebXR.session and GodotWebXR.space are set or
+ // unset, our monkey-patched requestAnimationFrame() should be
+ // enabled or disabled. When using the WebXR API Emulator, this
+ // gets picked up automatically, however, in the Oculus Browser
+ // on the Quest, we need to pause and resume the main loop.
+ Browser.pauseAsyncCallbacks();
+ Browser.mainLoop.pause();
+ window.setTimeout(function () {
+ Browser.resumeAsyncCallbacks();
+ Browser.mainLoop.resume();
+ }, 0);
+ },
+
+ // Some custom WebGL code for blitting our eye textures to the
+ // framebuffer we get from WebXR.
+ shaderProgram: null,
+ programInfo: null,
+ buffer: null,
+ // Vertex shader source.
+ vsSource: `
+ const vec2 scale = vec2(0.5, 0.5);
+ attribute vec4 aVertexPosition;
+
+ varying highp vec2 vTextureCoord;
+
+ void main () {
+ gl_Position = aVertexPosition;
+ vTextureCoord = aVertexPosition.xy * scale + scale;
+ }
+ `,
+ // Fragment shader source.
+ fsSource: `
+ varying highp vec2 vTextureCoord;
+
+ uniform sampler2D uSampler;
+
+ void main() {
+ gl_FragColor = texture2D(uSampler, vTextureCoord);
+ }
+ `,
+
+ initShaderProgram: (gl, vsSource, fsSource) => {
+ const vertexShader = GodotWebXR.loadShader(gl, gl.VERTEX_SHADER, vsSource);
+ const fragmentShader = GodotWebXR.loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
+
+ const shaderProgram = gl.createProgram();
+ gl.attachShader(shaderProgram, vertexShader);
+ gl.attachShader(shaderProgram, fragmentShader);
+ gl.linkProgram(shaderProgram);
+
+ if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+ GodotRuntime.error(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`);
+ return null;
+ }
+
+ return shaderProgram;
+ },
+ loadShader: (gl, type, source) => {
+ const shader = gl.createShader(type);
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+ GodotRuntime.error(`An error occurred compiling the shader: ${gl.getShaderInfoLog(shader)}`);
+ gl.deleteShader(shader);
+ return null;
+ }
+
+ return shader;
+ },
+ initBuffer: (gl) => {
+ const positionBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
+ const positions = [
+ -1.0, -1.0,
+ 1.0, -1.0,
+ -1.0, 1.0,
+ 1.0, 1.0,
+ ];
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
+ return positionBuffer;
+ },
+ blitTexture: (gl, texture) => {
+ if (GodotWebXR.shaderProgram === null) {
+ GodotWebXR.shaderProgram = GodotWebXR.initShaderProgram(gl, GodotWebXR.vsSource, GodotWebXR.fsSource);
+ GodotWebXR.programInfo = {
+ program: GodotWebXR.shaderProgram,
+ attribLocations: {
+ vertexPosition: gl.getAttribLocation(GodotWebXR.shaderProgram, 'aVertexPosition'),
+ },
+ uniformLocations: {
+ uSampler: gl.getUniformLocation(GodotWebXR.shaderProgram, 'uSampler'),
+ },
+ };
+ GodotWebXR.buffer = GodotWebXR.initBuffer(gl);
+ }
+
+ const orig_program = gl.getParameter(gl.CURRENT_PROGRAM);
+ gl.useProgram(GodotWebXR.shaderProgram);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, GodotWebXR.buffer);
+ gl.vertexAttribPointer(GodotWebXR.programInfo.attribLocations.vertexPosition, 2, gl.FLOAT, false, 0, 0);
+ gl.enableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.uniform1i(GodotWebXR.programInfo.uniformLocations.uSampler, 0);
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+
+ // Restore state.
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.disableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
+ gl.useProgram(orig_program);
+ },
+
+ // Holds the controllers list between function calls.
+ controllers: [],
+
+ // Updates controllers array, where the left hand (or sole tracker) is
+ // the first element, and the right hand is the second element, and any
+ // others placed at the 3rd position and up.
+ sampleControllers: () => {
+ if (!GodotWebXR.session || !GodotWebXR.frame) {
+ return;
+ }
+
+ let other_index = 2;
+ const controllers = [];
+ GodotWebXR.session.inputSources.forEach((input_source) => {
+ if (input_source.targetRayMode === 'tracked-pointer') {
+ if (input_source.handedness === 'right') {
+ controllers[1] = input_source;
+ } else if (input_source.handedness === 'left' || !controllers[0]) {
+ controllers[0] = input_source;
+ }
+ } else {
+ controllers[other_index++] = input_source;
+ }
+ });
+ GodotWebXR.controllers = controllers;
+ },
+
+ getControllerId: (input_source) => GodotWebXR.controllers.indexOf(input_source),
+ },
+
+ godot_webxr_is_supported__proxy: 'sync',
+ godot_webxr_is_supported__sig: 'i',
+ godot_webxr_is_supported: function () {
+ return !!navigator.xr;
+ },
+
+ godot_webxr_is_session_supported__proxy: 'sync',
+ godot_webxr_is_session_supported__sig: 'vii',
+ godot_webxr_is_session_supported: function (p_session_mode, p_callback) {
+ const session_mode = GodotRuntime.parseString(p_session_mode);
+ const cb = GodotRuntime.get_func(p_callback);
+ if (navigator.xr) {
+ navigator.xr.isSessionSupported(session_mode).then(function (supported) {
+ const c_str = GodotRuntime.allocString(session_mode);
+ cb(c_str, supported ? 1 : 0);
+ GodotRuntime.free(c_str);
+ });
+ } else {
+ const c_str = GodotRuntime.allocString(session_mode);
+ cb(c_str, 0);
+ GodotRuntime.free(c_str);
+ }
+ },
+
+ godot_webxr_initialize__deps: ['emscripten_webgl_get_current_context'],
+ godot_webxr_initialize__proxy: 'sync',
+ godot_webxr_initialize__sig: 'viiiiiiiiii',
+ godot_webxr_initialize: function (p_session_mode, p_required_features, p_optional_features, p_requested_reference_spaces, p_on_session_started, p_on_session_ended, p_on_session_failed, p_on_controller_changed, p_on_input_event, p_on_simple_event) {
+ GodotWebXR.monkeyPatchRequestAnimationFrame(true);
+
+ const session_mode = GodotRuntime.parseString(p_session_mode);
+ const required_features = GodotRuntime.parseString(p_required_features).split(',').map((s) => s.trim()).filter((s) => s !== '');
+ const optional_features = GodotRuntime.parseString(p_optional_features).split(',').map((s) => s.trim()).filter((s) => s !== '');
+ const requested_reference_space_types = GodotRuntime.parseString(p_requested_reference_spaces).split(',').map((s) => s.trim());
+ const onstarted = GodotRuntime.get_func(p_on_session_started);
+ const onended = GodotRuntime.get_func(p_on_session_ended);
+ const onfailed = GodotRuntime.get_func(p_on_session_failed);
+ const oncontroller = GodotRuntime.get_func(p_on_controller_changed);
+ const oninputevent = GodotRuntime.get_func(p_on_input_event);
+ const onsimpleevent = GodotRuntime.get_func(p_on_simple_event);
+
+ const session_init = {};
+ if (required_features.length > 0) {
+ session_init['requiredFeatures'] = required_features;
+ }
+ if (optional_features.length > 0) {
+ session_init['optionalFeatures'] = optional_features;
+ }
+
+ navigator.xr.requestSession(session_mode, session_init).then(function (session) {
+ GodotWebXR.session = session;
+
+ session.addEventListener('end', function (evt) {
+ onended();
+ });
+
+ session.addEventListener('inputsourceschange', function (evt) {
+ let controller_changed = false;
+ [evt.added, evt.removed].forEach((lst) => {
+ lst.forEach((input_source) => {
+ if (input_source.targetRayMode === 'tracked-pointer') {
+ controller_changed = true;
+ }
+ });
+ });
+ if (controller_changed) {
+ oncontroller();
+ }
+ });
+
+ ['selectstart', 'select', 'selectend', 'squeezestart', 'squeeze', 'squeezeend'].forEach((input_event) => {
+ session.addEventListener(input_event, function (evt) {
+ const c_str = GodotRuntime.allocString(input_event);
+ oninputevent(c_str, GodotWebXR.getControllerId(evt.inputSource));
+ GodotRuntime.free(c_str);
+ });
+ });
+
+ session.addEventListener('visibilitychange', function (evt) {
+ const c_str = GodotRuntime.allocString('visibility_state_changed');
+ onsimpleevent(c_str);
+ GodotRuntime.free(c_str);
+ });
+
+ const gl_context_handle = _emscripten_webgl_get_current_context(); // eslint-disable-line no-undef
+ const gl = GL.getContext(gl_context_handle).GLctx;
+ GodotWebXR.gl = gl;
+
+ gl.makeXRCompatible().then(function () {
+ session.updateRenderState({
+ baseLayer: new XRWebGLLayer(session, gl),
+ });
+
+ function onReferenceSpaceSuccess(reference_space, reference_space_type) {
+ GodotWebXR.space = reference_space;
+
+ // Using reference_space.addEventListener() crashes when
+ // using the polyfill with the WebXR Emulator extension,
+ // so we set the event property instead.
+ reference_space.onreset = function (evt) {
+ const c_str = GodotRuntime.allocString('reference_space_reset');
+ onsimpleevent(c_str);
+ GodotRuntime.free(c_str);
+ };
+
+ // Now that both GodotWebXR.session and GodotWebXR.space are
+ // set, we need to pause and resume the main loop for the XR
+ // main loop to kick in.
+ GodotWebXR.pauseResumeMainLoop();
+
+ // Call in setTimeout() so that errors in the onstarted()
+ // callback don't bubble up here and cause Godot to try the
+ // next reference space.
+ window.setTimeout(function () {
+ const c_str = GodotRuntime.allocString(reference_space_type);
+ onstarted(c_str);
+ GodotRuntime.free(c_str);
+ }, 0);
+ }
+
+ function requestReferenceSpace() {
+ const reference_space_type = requested_reference_space_types.shift();
+ session.requestReferenceSpace(reference_space_type)
+ .then((refSpace) => {
+ onReferenceSpaceSuccess(refSpace, reference_space_type);
+ })
+ .catch(() => {
+ if (requested_reference_space_types.length === 0) {
+ const c_str = GodotRuntime.allocString('Unable to get any of the requested reference space types');
+ onfailed(c_str);
+ GodotRuntime.free(c_str);
+ } else {
+ requestReferenceSpace();
+ }
+ });
+ }
+
+ requestReferenceSpace();
+ }).catch(function (error) {
+ const c_str = GodotRuntime.allocString(`Unable to make WebGL context compatible with WebXR: ${error}`);
+ onfailed(c_str);
+ GodotRuntime.free(c_str);
+ });
+ }).catch(function (error) {
+ const c_str = GodotRuntime.allocString(`Unable to start session: ${error}`);
+ onfailed(c_str);
+ GodotRuntime.free(c_str);
+ });
+ },
+
+ godot_webxr_uninitialize__proxy: 'sync',
+ godot_webxr_uninitialize__sig: 'v',
+ godot_webxr_uninitialize: function () {
+ if (GodotWebXR.session) {
+ GodotWebXR.session.end()
+ // Prevent exception when session has already ended.
+ .catch((e) => { });
+ }
+
+ // Clean-up the textures we allocated for each view.
+ const gl = GodotWebXR.gl;
+ for (let i = 0; i < GodotWebXR.textures.length; i++) {
+ const texture = GodotWebXR.textures[i];
+ if (texture !== null) {
+ gl.deleteTexture(texture);
+ }
+ GodotWebXR.textures[i] = null;
+ GodotWebXR.texture_ids[i] = null;
+ }
+
+ GodotWebXR.session = null;
+ GodotWebXR.space = null;
+ GodotWebXR.frame = null;
+ GodotWebXR.pose = null;
+
+ // Disable the monkey-patched window.requestAnimationFrame() and
+ // pause/restart the main loop to activate it on all platforms.
+ GodotWebXR.monkeyPatchRequestAnimationFrame(false);
+ GodotWebXR.pauseResumeMainLoop();
+ },
+
+ godot_webxr_get_render_targetsize__proxy: 'sync',
+ godot_webxr_get_render_targetsize__sig: 'i',
+ godot_webxr_get_render_targetsize: function () {
+ if (!GodotWebXR.session || !GodotWebXR.pose) {
+ return 0;
+ }
+
+ const glLayer = GodotWebXR.session.renderState.baseLayer;
+ const view = GodotWebXR.pose.views[0];
+ const viewport = glLayer.getViewport(view);
+
+ const buf = GodotRuntime.malloc(2 * 4);
+ GodotRuntime.setHeapValue(buf + 0, viewport.width, 'i32');
+ GodotRuntime.setHeapValue(buf + 4, viewport.height, 'i32');
+ return buf;
+ },
+
+ godot_webxr_get_transform_for_eye__proxy: 'sync',
+ godot_webxr_get_transform_for_eye__sig: 'ii',
+ godot_webxr_get_transform_for_eye: function (p_eye) {
+ if (!GodotWebXR.session || !GodotWebXR.pose) {
+ return 0;
+ }
+
+ const views = GodotWebXR.pose.views;
+ let matrix;
+ if (p_eye === 0) {
+ matrix = GodotWebXR.pose.transform.matrix;
+ } else {
+ matrix = views[p_eye - 1].transform.matrix;
+ }
+ const buf = GodotRuntime.malloc(16 * 4);
+ for (let i = 0; i < 16; i++) {
+ GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float');
+ }
+ return buf;
+ },
+
+ godot_webxr_get_projection_for_eye__proxy: 'sync',
+ godot_webxr_get_projection_for_eye__sig: 'ii',
+ godot_webxr_get_projection_for_eye: function (p_eye) {
+ if (!GodotWebXR.session || !GodotWebXR.pose) {
+ return 0;
+ }
+
+ const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0;
+ const matrix = GodotWebXR.pose.views[view_index].projectionMatrix;
+ const buf = GodotRuntime.malloc(16 * 4);
+ for (let i = 0; i < 16; i++) {
+ GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float');
+ }
+ return buf;
+ },
+
+ godot_webxr_get_external_texture_for_eye__proxy: 'sync',
+ godot_webxr_get_external_texture_for_eye__sig: 'ii',
+ godot_webxr_get_external_texture_for_eye: function (p_eye) {
+ if (!GodotWebXR.session || !GodotWebXR.pose) {
+ return 0;
+ }
+
+ const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0;
+ if (GodotWebXR.texture_ids[view_index]) {
+ return GodotWebXR.texture_ids[view_index];
+ }
+
+ const glLayer = GodotWebXR.session.renderState.baseLayer;
+ const view = GodotWebXR.pose.views[view_index];
+ const viewport = glLayer.getViewport(view);
+ const gl = GodotWebXR.gl;
+
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewport.width, viewport.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+
+ const texture_id = GL.getNewId(GL.textures);
+ GL.textures[texture_id] = texture;
+ GodotWebXR.textures[view_index] = texture;
+ GodotWebXR.texture_ids[view_index] = texture_id;
+ return texture_id;
+ },
+
+ godot_webxr_commit_for_eye__proxy: 'sync',
+ godot_webxr_commit_for_eye__sig: 'vi',
+ godot_webxr_commit_for_eye: function (p_eye) {
+ if (!GodotWebXR.session || !GodotWebXR.pose) {
+ return;
+ }
+
+ const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0;
+ const glLayer = GodotWebXR.session.renderState.baseLayer;
+ const view = GodotWebXR.pose.views[view_index];
+ const viewport = glLayer.getViewport(view);
+ const gl = GodotWebXR.gl;
+
+ const orig_framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
+ const orig_viewport = gl.getParameter(gl.VIEWPORT);
+
+ // Bind to WebXR's framebuffer.
+ gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
+ gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
+
+ GodotWebXR.blitTexture(gl, GodotWebXR.textures[view_index]);
+
+ // Restore state.
+ gl.bindFramebuffer(gl.FRAMEBUFFER, orig_framebuffer);
+ gl.viewport(orig_viewport[0], orig_viewport[1], orig_viewport[2], orig_viewport[3]);
+ },
+
+ godot_webxr_sample_controller_data__proxy: 'sync',
+ godot_webxr_sample_controller_data__sig: 'v',
+ godot_webxr_sample_controller_data: function () {
+ GodotWebXR.sampleControllers();
+ },
+
+ godot_webxr_get_controller_count__proxy: 'sync',
+ godot_webxr_get_controller_count__sig: 'i',
+ godot_webxr_get_controller_count: function () {
+ if (!GodotWebXR.session || !GodotWebXR.frame) {
+ return 0;
+ }
+ return GodotWebXR.controllers.length;
+ },
+
+ godot_webxr_is_controller_connected__proxy: 'sync',
+ godot_webxr_is_controller_connected__sig: 'ii',
+ godot_webxr_is_controller_connected: function (p_controller) {
+ if (!GodotWebXR.session || !GodotWebXR.frame) {
+ return false;
+ }
+ return !!GodotWebXR.controllers[p_controller];
+ },
+
+ godot_webxr_get_controller_transform__proxy: 'sync',
+ godot_webxr_get_controller_transform__sig: 'ii',
+ godot_webxr_get_controller_transform: function (p_controller) {
+ if (!GodotWebXR.session || !GodotWebXR.frame) {
+ return 0;
+ }
+
+ const controller = GodotWebXR.controllers[p_controller];
+ if (!controller) {
+ return 0;
+ }
+
+ const frame = GodotWebXR.frame;
+ const space = GodotWebXR.space;
+
+ const pose = frame.getPose(controller.targetRaySpace, space);
+ if (!pose) {
+ // This can mean that the controller lost tracking.
+ return 0;
+ }
+ const matrix = pose.transform.matrix;
+
+ const buf = GodotRuntime.malloc(16 * 4);
+ for (let i = 0; i < 16; i++) {
+ GodotRuntime.setHeapValue(buf + (i * 4), matrix[i], 'float');
+ }
+ return buf;
+ },
+
+ godot_webxr_get_controller_buttons__proxy: 'sync',
+ godot_webxr_get_controller_buttons__sig: 'ii',
+ godot_webxr_get_controller_buttons: function (p_controller) {
+ if (GodotWebXR.controllers.length === 0) {
+ return 0;
+ }
+
+ const controller = GodotWebXR.controllers[p_controller];
+ if (!controller || !controller.gamepad) {
+ return 0;
+ }
+
+ const button_count = controller.gamepad.buttons.length;
+
+ const buf = GodotRuntime.malloc((button_count + 1) * 4);
+ GodotRuntime.setHeapValue(buf, button_count, 'i32');
+ for (let i = 0; i < button_count; i++) {
+ GodotRuntime.setHeapValue(buf + 4 + (i * 4), controller.gamepad.buttons[i].value, 'float');
+ }
+ return buf;
+ },
+
+ godot_webxr_get_controller_axes__proxy: 'sync',
+ godot_webxr_get_controller_axes__sig: 'ii',
+ godot_webxr_get_controller_axes: function (p_controller) {
+ if (GodotWebXR.controllers.length === 0) {
+ return 0;
+ }
+
+ const controller = GodotWebXR.controllers[p_controller];
+ if (!controller || !controller.gamepad) {
+ return 0;
+ }
+
+ const axes_count = controller.gamepad.axes.length;
+
+ const buf = GodotRuntime.malloc((axes_count + 1) * 4);
+ GodotRuntime.setHeapValue(buf, axes_count, 'i32');
+ for (let i = 0; i < axes_count; i++) {
+ let value = controller.gamepad.axes[i];
+ if (i === 1 || i === 3) {
+ // Invert the Y-axis on thumbsticks and trackpads, in order to
+ // match OpenXR and other XR platform SDKs.
+ value *= -1.0;
+ }
+ GodotRuntime.setHeapValue(buf + 4 + (i * 4), value, 'float');
+ }
+ return buf;
+ },
+
+ godot_webxr_get_visibility_state__proxy: 'sync',
+ godot_webxr_get_visibility_state__sig: 'i',
+ godot_webxr_get_visibility_state: function () {
+ if (!GodotWebXR.session || !GodotWebXR.session.visibilityState) {
+ return 0;
+ }
+
+ return GodotRuntime.allocString(GodotWebXR.session.visibilityState);
+ },
+
+ godot_webxr_get_bounds_geometry__proxy: 'sync',
+ godot_webxr_get_bounds_geometry__sig: 'i',
+ godot_webxr_get_bounds_geometry: function () {
+ if (!GodotWebXR.space || !GodotWebXR.space.boundsGeometry) {
+ return 0;
+ }
+
+ const point_count = GodotWebXR.space.boundsGeometry.length;
+ if (point_count === 0) {
+ return 0;
+ }
+
+ const buf = GodotRuntime.malloc(((point_count * 3) + 1) * 4);
+ GodotRuntime.setHeapValue(buf, point_count, 'i32');
+ for (let i = 0; i < point_count; i++) {
+ const point = GodotWebXR.space.boundsGeometry[i];
+ GodotRuntime.setHeapValue(buf + ((i * 3) + 1) * 4, point.x, 'float');
+ GodotRuntime.setHeapValue(buf + ((i * 3) + 2) * 4, point.y, 'float');
+ GodotRuntime.setHeapValue(buf + ((i * 3) + 3) * 4, point.z, 'float');
+ }
+
+ return buf;
+ },
+};
+
+autoAddDeps(GodotWebXR, '$GodotWebXR');
+mergeInto(LibraryManager.library, GodotWebXR);
diff --git a/modules/webxr/native/webxr.externs.js b/modules/webxr/native/webxr.externs.js
new file mode 100644
index 0000000000..03dc05bc83
--- /dev/null
+++ b/modules/webxr/native/webxr.externs.js
@@ -0,0 +1,499 @@
+/**
+ * @type {XR}
+ */
+Navigator.prototype.xr;
+
+/**
+ * @constructor
+ */
+function XRSessionInit() {};
+
+/**
+ * @type {Array<string>}
+ */
+XRSessionInit.prototype.requiredFeatures;
+
+/**
+ * @type {Array<string>}
+ */
+XRSessionInit.prototype.optionalFeatures;
+
+/**
+ * @constructor
+ */
+function XR() {}
+
+/**
+ * @type {?function (Event)}
+ */
+XR.prototype.ondevicechanged;
+
+/**
+ * @param {string} mode
+ *
+ * @return {!Promise<boolean>}
+ */
+XR.prototype.isSessionSupported = function(mode) {}
+
+/**
+ * @param {string} mode
+ * @param {XRSessionInit} options
+ *
+ * @return {!Promise<XRSession>}
+ */
+XR.prototype.requestSession = function(mode, options) {}
+
+/**
+ * @constructor
+ */
+function XRSession() {}
+
+/**
+ * @type {XRRenderState}
+ */
+XRSession.prototype.renderState;
+
+/**
+ * @type {Array<XRInputSource>}
+ */
+XRSession.prototype.inputSources;
+
+/**
+ * @type {string}
+ */
+XRSession.prototype.visibilityState;
+
+/**
+ * @type {?function (Event)}
+ */
+XRSession.prototype.onend;
+
+/**
+ * @type {?function (XRInputSourcesChangeEvent)}
+ */
+XRSession.prototype.oninputsourceschange;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onselectstart;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onselect;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onselectend;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onsqueezestart;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onsqueeze;
+
+/**
+ * @type {?function (XRInputSourceEvent)}
+ */
+XRSession.prototype.onsqueezeend;
+
+/**
+ * @type {?function (Event)}
+ */
+XRSession.prototype.onvisibilitychange;
+
+/**
+ * @param {XRRenderStateInit} state
+ * @return {void}
+ */
+XRSession.prototype.updateRenderState = function (state) {};
+
+/**
+ * @param {XRFrameRequestCallback} callback
+ * @return {number}
+ */
+XRSession.prototype.requestAnimationFrame = function (callback) {};
+
+/**
+ * @param {number} handle
+ * @return {void}
+ */
+XRSession.prototype.cancelAnimationFrame = function (handle) {};
+
+/**
+ * @return {Promise<void>}
+ */
+XRSession.prototype.end = function () {};
+
+/**
+ * @param {string} referenceSpaceType
+ * @return {Promise<XRReferenceSpace>}
+ */
+XRSession.prototype.requestReferenceSpace = function (referenceSpaceType) {};
+
+/**
+ * @typedef {function(number, XRFrame): undefined}
+ */
+var XRFrameRequestCallback;
+
+/**
+ * @constructor
+ */
+function XRRenderStateInit() {}
+
+/**
+ * @type {number}
+ */
+XRRenderStateInit.prototype.depthNear;
+
+/**
+ * @type {number}
+ */
+XRRenderStateInit.prototype.depthFar;
+
+/**
+ * @type {number}
+ */
+XRRenderStateInit.prototype.inlineVerticalFieldOfView;
+
+/**
+ * @type {?XRWebGLLayer}
+ */
+XRRenderStateInit.prototype.baseLayer;
+
+/**
+ * @constructor
+ */
+function XRRenderState() {};
+
+/**
+ * @type {number}
+ */
+XRRenderState.prototype.depthNear;
+
+/**
+ * @type {number}
+ */
+XRRenderState.prototype.depthFar;
+
+/**
+ * @type {?number}
+ */
+XRRenderState.prototype.inlineVerticalFieldOfView;
+
+/**
+ * @type {?XRWebGLLayer}
+ */
+XRRenderState.prototype.baseLayer;
+
+/**
+ * @constructor
+ */
+function XRFrame() {}
+
+/**
+ * @type {XRSession}
+ */
+XRFrame.prototype.session;
+
+/**
+ * @param {XRReferenceSpace} referenceSpace
+ * @return {?XRViewerPose}
+ */
+XRFrame.prototype.getViewerPose = function (referenceSpace) {};
+
+/**
+ *
+ * @param {XRSpace} space
+ * @param {XRSpace} baseSpace
+ * @return {XRPose}
+ */
+XRFrame.prototype.getPose = function (space, baseSpace) {};
+
+/**
+ * @constructor
+ */
+function XRReferenceSpace() {};
+
+/**
+ * @type {Array<DOMPointReadOnly>}
+ */
+XRReferenceSpace.prototype.boundsGeometry;
+
+/**
+ * @param {XRRigidTransform} originOffset
+ * @return {XRReferenceSpace}
+ */
+XRReferenceSpace.prototype.getOffsetReferenceSpace = function(originOffset) {};
+
+/**
+ * @type {?function (Event)}
+ */
+XRReferenceSpace.prototype.onreset;
+
+/**
+ * @constructor
+ */
+function XRRigidTransform() {};
+
+/**
+ * @type {DOMPointReadOnly}
+ */
+XRRigidTransform.prototype.position;
+
+/**
+ * @type {DOMPointReadOnly}
+ */
+XRRigidTransform.prototype.orientation;
+
+/**
+ * @type {Float32Array}
+ */
+XRRigidTransform.prototype.matrix;
+
+/**
+ * @type {XRRigidTransform}
+ */
+XRRigidTransform.prototype.inverse;
+
+/**
+ * @constructor
+ */
+function XRView() {}
+
+/**
+ * @type {string}
+ */
+XRView.prototype.eye;
+
+/**
+ * @type {Float32Array}
+ */
+XRView.prototype.projectionMatrix;
+
+/**
+ * @type {XRRigidTransform}
+ */
+XRView.prototype.transform;
+
+/**
+ * @constructor
+ */
+function XRViewerPose() {}
+
+/**
+ * @type {Array<XRView>}
+ */
+XRViewerPose.prototype.views;
+
+/**
+ * @constructor
+ */
+function XRViewport() {}
+
+/**
+ * @type {number}
+ */
+XRViewport.prototype.x;
+
+/**
+ * @type {number}
+ */
+XRViewport.prototype.y;
+
+/**
+ * @type {number}
+ */
+XRViewport.prototype.width;
+
+/**
+ * @type {number}
+ */
+XRViewport.prototype.height;
+
+/**
+ * @constructor
+ */
+function XRWebGLLayerInit() {};
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.antialias;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.depth;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.stencil;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.alpha;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.ignoreDepthValues;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayerInit.prototype.ignoreDepthValues;
+
+/**
+ * @type {number}
+ */
+XRWebGLLayerInit.prototype.framebufferScaleFactor;
+
+/**
+ * @constructor
+ *
+ * @param {XRSession} session
+ * @param {WebGLRenderContext|WebGL2RenderingContext} ctx
+ * @param {?XRWebGLLayerInit} options
+ */
+function XRWebGLLayer(session, ctx, options) {}
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayer.prototype.antialias;
+
+/**
+ * @type {boolean}
+ */
+XRWebGLLayer.prototype.ignoreDepthValues;
+
+/**
+ * @type {number}
+ */
+XRWebGLLayer.prototype.framebufferWidth;
+
+/**
+ * @type {number}
+ */
+XRWebGLLayer.prototype.framebufferHeight;
+
+/**
+ * @type {WebGLFramebuffer}
+ */
+XRWebGLLayer.prototype.framebuffer;
+
+/**
+ * @param {XRView} view
+ * @return {?XRViewport}
+ */
+XRWebGLLayer.prototype.getViewport = function(view) {};
+
+/**
+ * @param {XRSession} session
+ * @return {number}
+ */
+XRWebGLLayer.prototype.getNativeFramebufferScaleFactor = function (session) {};
+
+/**
+ * @constructor
+ */
+function WebGLRenderingContextBase() {};
+
+/**
+ * @return {Promise<void>}
+ */
+WebGLRenderingContextBase.prototype.makeXRCompatible = function () {};
+
+/**
+ * @constructor
+ */
+function XRInputSourcesChangeEvent() {};
+
+/**
+ * @type {Array<XRInputSource>}
+ */
+XRInputSourcesChangeEvent.prototype.added;
+
+/**
+ * @type {Array<XRInputSource>}
+ */
+XRInputSourcesChangeEvent.prototype.removed;
+
+/**
+ * @constructor
+ */
+function XRInputSourceEvent() {};
+
+/**
+ * @type {XRFrame}
+ */
+XRInputSourceEvent.prototype.frame;
+
+/**
+ * @type {XRInputSource}
+ */
+XRInputSourceEvent.prototype.inputSource;
+
+/**
+ * @constructor
+ */
+function XRInputSource() {};
+
+/**
+ * @type {Gamepad}
+ */
+XRInputSource.prototype.gamepad;
+
+/**
+ * @type {XRSpace}
+ */
+XRInputSource.prototype.gripSpace;
+
+/**
+ * @type {string}
+ */
+XRInputSource.prototype.handedness;
+
+/**
+ * @type {string}
+ */
+XRInputSource.prototype.profiles;
+
+/**
+ * @type {string}
+ */
+XRInputSource.prototype.targetRayMode;
+
+/**
+ * @type {XRSpace}
+ */
+XRInputSource.prototype.targetRaySpace;
+
+/**
+ * @constructor
+ */
+function XRSpace() {};
+
+/**
+ * @constructor
+ */
+function XRPose() {};
+
+/**
+ * @type {XRRigidTransform}
+ */
+XRPose.prototype.transform;
+
+/**
+ * @type {boolean}
+ */
+XRPose.prototype.emulatedPosition;
diff --git a/modules/webxr/register_types.cpp b/modules/webxr/register_types.cpp
new file mode 100644
index 0000000000..8baf7e05b8
--- /dev/null
+++ b/modules/webxr/register_types.cpp
@@ -0,0 +1,47 @@
+/*************************************************************************/
+/* register_types.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "register_types.h"
+
+#include "webxr_interface.h"
+#include "webxr_interface_js.h"
+
+void register_webxr_types() {
+ ClassDB::register_virtual_class<WebXRInterface>();
+
+#ifdef JAVASCRIPT_ENABLED
+ Ref<WebXRInterfaceJS> webxr;
+ webxr.instance();
+ XRServer::get_singleton()->add_interface(webxr);
+#endif
+}
+
+void unregister_webxr_types() {
+}
diff --git a/modules/webxr/register_types.h b/modules/webxr/register_types.h
new file mode 100644
index 0000000000..f0c5a4bd79
--- /dev/null
+++ b/modules/webxr/register_types.h
@@ -0,0 +1,37 @@
+/*************************************************************************/
+/* register_types.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 WEBXR_REGISTER_TYPES_H
+#define WEBXR_REGISTER_TYPES_H
+
+void register_webxr_types();
+void unregister_webxr_types();
+
+#endif // WEBXR_REGISTER_TYPES_H
diff --git a/modules/webxr/webxr_interface.cpp b/modules/webxr/webxr_interface.cpp
new file mode 100644
index 0000000000..3e8e75bf0e
--- /dev/null
+++ b/modules/webxr/webxr_interface.cpp
@@ -0,0 +1,71 @@
+/*************************************************************************/
+/* webxr_interface.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 "webxr_interface.h"
+#include <stdlib.h>
+
+void WebXRInterface::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("is_session_supported", "session_mode"), &WebXRInterface::is_session_supported);
+ ClassDB::bind_method(D_METHOD("set_session_mode", "session_mode"), &WebXRInterface::set_session_mode);
+ ClassDB::bind_method(D_METHOD("get_session_mode"), &WebXRInterface::get_session_mode);
+ ClassDB::bind_method(D_METHOD("set_required_features", "required_features"), &WebXRInterface::set_required_features);
+ ClassDB::bind_method(D_METHOD("get_required_features"), &WebXRInterface::get_required_features);
+ ClassDB::bind_method(D_METHOD("set_optional_features", "optional_features"), &WebXRInterface::set_optional_features);
+ ClassDB::bind_method(D_METHOD("get_optional_features"), &WebXRInterface::get_optional_features);
+ ClassDB::bind_method(D_METHOD("get_reference_space_type"), &WebXRInterface::get_reference_space_type);
+ ClassDB::bind_method(D_METHOD("set_requested_reference_space_types", "requested_reference_space_types"), &WebXRInterface::set_requested_reference_space_types);
+ ClassDB::bind_method(D_METHOD("get_requested_reference_space_types"), &WebXRInterface::get_requested_reference_space_types);
+ ClassDB::bind_method(D_METHOD("get_controller", "controller_id"), &WebXRInterface::get_controller);
+ ClassDB::bind_method(D_METHOD("get_visibility_state"), &WebXRInterface::get_visibility_state);
+ ClassDB::bind_method(D_METHOD("get_bounds_geometry"), &WebXRInterface::get_bounds_geometry);
+
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "session_mode", PROPERTY_HINT_NONE), "set_session_mode", "get_session_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "required_features", PROPERTY_HINT_NONE), "set_required_features", "get_required_features");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "optional_features", PROPERTY_HINT_NONE), "set_optional_features", "get_optional_features");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "requested_reference_space_types", PROPERTY_HINT_NONE), "set_requested_reference_space_types", "get_requested_reference_space_types");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "reference_space_type", PROPERTY_HINT_NONE), "", "get_reference_space_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "visibility_state", PROPERTY_HINT_NONE), "", "get_visibility_state");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "bounds_geometry", PROPERTY_HINT_NONE), "", "get_bounds_geometry");
+
+ ADD_SIGNAL(MethodInfo("session_supported", PropertyInfo(Variant::STRING, "session_mode"), PropertyInfo(Variant::BOOL, "supported")));
+ ADD_SIGNAL(MethodInfo("session_started"));
+ ADD_SIGNAL(MethodInfo("session_ended"));
+ ADD_SIGNAL(MethodInfo("session_failed", PropertyInfo(Variant::STRING, "message")));
+
+ ADD_SIGNAL(MethodInfo("selectstart", PropertyInfo(Variant::INT, "controller_id")));
+ ADD_SIGNAL(MethodInfo("select", PropertyInfo(Variant::INT, "controller_id")));
+ ADD_SIGNAL(MethodInfo("selectend", PropertyInfo(Variant::INT, "controller_id")));
+ ADD_SIGNAL(MethodInfo("squeezestart", PropertyInfo(Variant::INT, "controller_id")));
+ ADD_SIGNAL(MethodInfo("squeeze", PropertyInfo(Variant::INT, "controller_id")));
+ ADD_SIGNAL(MethodInfo("squeezeend", PropertyInfo(Variant::INT, "controller_id")));
+
+ ADD_SIGNAL(MethodInfo("visibility_state_changed"));
+ ADD_SIGNAL(MethodInfo("reference_space_reset"));
+}
diff --git a/modules/webxr/webxr_interface.h b/modules/webxr/webxr_interface.h
new file mode 100644
index 0000000000..c5b2dc8d73
--- /dev/null
+++ b/modules/webxr/webxr_interface.h
@@ -0,0 +1,65 @@
+/*************************************************************************/
+/* webxr_interface.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 WEBXR_INTERFACE_H
+#define WEBXR_INTERFACE_H
+
+#include "servers/xr/xr_interface.h"
+#include "servers/xr/xr_positional_tracker.h"
+
+/**
+ @author David Snopek <david.snopek@snopekgames.com>
+
+ The WebXR interface is a VR/AR interface that can be used on the web.
+*/
+
+class WebXRInterface : public XRInterface {
+ GDCLASS(WebXRInterface, XRInterface);
+
+protected:
+ static void _bind_methods();
+
+public:
+ virtual void is_session_supported(const String &p_session_mode) = 0;
+ virtual void set_session_mode(String p_session_mode) = 0;
+ virtual String get_session_mode() const = 0;
+ virtual void set_required_features(String p_required_features) = 0;
+ virtual String get_required_features() const = 0;
+ virtual void set_optional_features(String p_optional_features) = 0;
+ virtual String get_optional_features() const = 0;
+ virtual void set_requested_reference_space_types(String p_requested_reference_space_types) = 0;
+ virtual String get_requested_reference_space_types() const = 0;
+ virtual String get_reference_space_type() const = 0;
+ virtual XRPositionalTracker *get_controller(int p_controller_id) const = 0;
+ virtual String get_visibility_state() const = 0;
+ virtual PackedVector3Array get_bounds_geometry() const = 0;
+};
+
+#endif // WEBXR_INTERFACE_H
diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp
new file mode 100644
index 0000000000..6594553146
--- /dev/null
+++ b/modules/webxr/webxr_interface_js.cpp
@@ -0,0 +1,451 @@
+/*************************************************************************/
+/* webxr_interface_js.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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. */
+/*************************************************************************/
+
+#ifdef JAVASCRIPT_ENABLED
+
+#include "webxr_interface_js.h"
+#include "core/input/input.h"
+#include "core/os/os.h"
+#include "emscripten.h"
+#include "godot_webxr.h"
+#include <stdlib.h>
+
+void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ String session_mode = String(p_session_mode);
+ interface->emit_signal("session_supported", session_mode, p_supported ? true : false);
+}
+
+void _emwebxr_on_session_started(char *p_reference_space_type) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ String reference_space_type = String(p_reference_space_type);
+ ((WebXRInterfaceJS *)interface.ptr())->_set_reference_space_type(reference_space_type);
+ interface->emit_signal("session_started");
+}
+
+void _emwebxr_on_session_ended() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ interface->uninitialize();
+ interface->emit_signal("session_ended");
+}
+
+void _emwebxr_on_session_failed(char *p_message) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ String message = String(p_message);
+ interface->emit_signal("session_failed", message);
+}
+
+void _emwebxr_on_controller_changed() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ ((WebXRInterfaceJS *)interface.ptr())->_on_controller_changed();
+}
+
+extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_input_event(char *p_signal_name, int p_input_source) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ StringName signal_name = StringName(p_signal_name);
+ interface->emit_signal(signal_name, p_input_source + 1);
+}
+
+extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_simple_event(char *p_signal_name) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ Ref<XRInterface> interface = xr_server->find_interface("WebXR");
+ ERR_FAIL_COND(interface.is_null());
+
+ StringName signal_name = StringName(p_signal_name);
+ interface->emit_signal(signal_name);
+}
+
+void WebXRInterfaceJS::is_session_supported(const String &p_session_mode) {
+ godot_webxr_is_session_supported(p_session_mode.utf8().get_data(), &_emwebxr_on_session_supported);
+}
+
+void WebXRInterfaceJS::set_session_mode(String p_session_mode) {
+ session_mode = p_session_mode;
+}
+
+String WebXRInterfaceJS::get_session_mode() const {
+ return session_mode;
+}
+
+void WebXRInterfaceJS::set_required_features(String p_required_features) {
+ required_features = p_required_features;
+}
+
+String WebXRInterfaceJS::get_required_features() const {
+ return required_features;
+}
+
+void WebXRInterfaceJS::set_optional_features(String p_optional_features) {
+ optional_features = p_optional_features;
+}
+
+String WebXRInterfaceJS::get_optional_features() const {
+ return optional_features;
+}
+
+void WebXRInterfaceJS::set_requested_reference_space_types(String p_requested_reference_space_types) {
+ requested_reference_space_types = p_requested_reference_space_types;
+}
+
+String WebXRInterfaceJS::get_requested_reference_space_types() const {
+ return requested_reference_space_types;
+}
+
+void WebXRInterfaceJS::_set_reference_space_type(String p_reference_space_type) {
+ reference_space_type = p_reference_space_type;
+}
+
+String WebXRInterfaceJS::get_reference_space_type() const {
+ return reference_space_type;
+}
+
+XRPositionalTracker *WebXRInterfaceJS::get_controller(int p_controller_id) const {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL_V(xr_server, nullptr);
+
+ return xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id);
+}
+
+String WebXRInterfaceJS::get_visibility_state() const {
+ char *c_str = godot_webxr_get_visibility_state();
+ if (c_str) {
+ String visibility_state = String(c_str);
+ free(c_str);
+
+ return visibility_state;
+ }
+ return String();
+}
+
+PackedVector3Array WebXRInterfaceJS::get_bounds_geometry() const {
+ PackedVector3Array ret;
+
+ int *js_bounds = godot_webxr_get_bounds_geometry();
+ if (js_bounds) {
+ ret.resize(js_bounds[0]);
+ for (int i = 0; i < js_bounds[0]; i++) {
+ float *js_vector3 = ((float *)js_bounds) + (i * 3) + 1;
+ ret.set(i, Vector3(js_vector3[0], js_vector3[1], js_vector3[2]));
+ }
+ free(js_bounds);
+ }
+
+ return ret;
+}
+
+StringName WebXRInterfaceJS::get_name() const {
+ return "WebXR";
+};
+
+int WebXRInterfaceJS::get_capabilities() const {
+ return XRInterface::XR_STEREO;
+};
+
+bool WebXRInterfaceJS::is_stereo() {
+ // @todo WebXR can be mono! So, how do we know? Count the views in the frame?
+ return true;
+};
+
+bool WebXRInterfaceJS::is_initialized() const {
+ return (initialized);
+};
+
+bool WebXRInterfaceJS::initialize() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL_V(xr_server, false);
+
+ if (!initialized) {
+ if (!godot_webxr_is_supported()) {
+ return false;
+ }
+
+ if (requested_reference_space_types.size() == 0) {
+ return false;
+ }
+
+ // make this our primary interface
+ xr_server->set_primary_interface(this);
+
+ initialized = true;
+
+ godot_webxr_initialize(
+ session_mode.utf8().get_data(),
+ required_features.utf8().get_data(),
+ optional_features.utf8().get_data(),
+ requested_reference_space_types.utf8().get_data(),
+ &_emwebxr_on_session_started,
+ &_emwebxr_on_session_ended,
+ &_emwebxr_on_session_failed,
+ &_emwebxr_on_controller_changed,
+ &_emwebxr_on_input_event,
+ &_emwebxr_on_simple_event);
+ };
+
+ return true;
+};
+
+void WebXRInterfaceJS::uninitialize() {
+ if (initialized) {
+ XRServer *xr_server = XRServer::get_singleton();
+ if (xr_server != NULL) {
+ // no longer our primary interface
+ xr_server->clear_primary_interface_if(this);
+ }
+
+ godot_webxr_uninitialize();
+
+ reference_space_type = "";
+ initialized = false;
+ };
+};
+
+Transform WebXRInterfaceJS::_js_matrix_to_transform(float *p_js_matrix) {
+ Transform transform;
+
+ transform.basis.elements[0].x = p_js_matrix[0];
+ transform.basis.elements[1].x = p_js_matrix[1];
+ transform.basis.elements[2].x = p_js_matrix[2];
+ transform.basis.elements[0].y = p_js_matrix[4];
+ transform.basis.elements[1].y = p_js_matrix[5];
+ transform.basis.elements[2].y = p_js_matrix[6];
+ transform.basis.elements[0].z = p_js_matrix[8];
+ transform.basis.elements[1].z = p_js_matrix[9];
+ transform.basis.elements[2].z = p_js_matrix[10];
+ transform.origin.x = p_js_matrix[12];
+ transform.origin.y = p_js_matrix[13];
+ transform.origin.z = p_js_matrix[14];
+
+ return transform;
+}
+
+Size2 WebXRInterfaceJS::get_render_targetsize() {
+ Size2 target_size;
+
+ int *js_size = godot_webxr_get_render_targetsize();
+ if (!initialized || js_size == nullptr) {
+ // As a default, use half the window size.
+ target_size = DisplayServer::get_singleton()->window_get_size();
+ target_size.width /= 2.0;
+ return target_size;
+ }
+
+ target_size.width = js_size[0];
+ target_size.height = js_size[1];
+
+ free(js_size);
+
+ return target_size;
+};
+
+Transform WebXRInterfaceJS::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) {
+ Transform transform_for_eye;
+
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL_V(xr_server, transform_for_eye);
+
+ float *js_matrix = godot_webxr_get_transform_for_eye(p_eye);
+ if (!initialized || js_matrix == nullptr) {
+ transform_for_eye = p_cam_transform;
+ return transform_for_eye;
+ }
+
+ transform_for_eye = _js_matrix_to_transform(js_matrix);
+ free(js_matrix);
+
+ return p_cam_transform * xr_server->get_reference_frame() * transform_for_eye;
+};
+
+CameraMatrix WebXRInterfaceJS::get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) {
+ CameraMatrix eye;
+
+ float *js_matrix = godot_webxr_get_projection_for_eye(p_eye);
+ if (!initialized || js_matrix == nullptr) {
+ return eye;
+ }
+
+ int k = 0;
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
+ eye.matrix[i][j] = js_matrix[k++];
+ }
+ }
+
+ free(js_matrix);
+
+ // Copied from godot_oculus_mobile's ovr_mobile_session.cpp
+ eye.matrix[2][2] = -(p_z_far + p_z_near) / (p_z_far - p_z_near);
+ eye.matrix[3][2] = -(2.0f * p_z_far * p_z_near) / (p_z_far - p_z_near);
+
+ return eye;
+}
+
+unsigned int WebXRInterfaceJS::get_external_texture_for_eye(XRInterface::Eyes p_eye) {
+ if (!initialized) {
+ return 0;
+ }
+ return godot_webxr_get_external_texture_for_eye(p_eye);
+}
+
+void WebXRInterfaceJS::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) {
+ if (!initialized) {
+ return;
+ }
+ godot_webxr_commit_for_eye(p_eye);
+};
+
+void WebXRInterfaceJS::process() {
+ if (initialized) {
+ godot_webxr_sample_controller_data();
+
+ int controller_count = godot_webxr_get_controller_count();
+ if (controller_count == 0) {
+ return;
+ }
+
+ for (int i = 0; i < controller_count; i++) {
+ _update_tracker(i);
+ }
+ };
+};
+
+void WebXRInterfaceJS::_update_tracker(int p_controller_id) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ XRPositionalTracker *tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id + 1);
+ if (godot_webxr_is_controller_connected(p_controller_id)) {
+ if (tracker == nullptr) {
+ tracker = memnew(XRPositionalTracker);
+ tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER);
+ // Controller id's 0 and 1 are always the left and right hands.
+ if (p_controller_id < 2) {
+ tracker->set_tracker_name(p_controller_id == 0 ? "Left" : "Right");
+ tracker->set_tracker_hand(p_controller_id == 0 ? XRPositionalTracker::TRACKER_HAND_LEFT : XRPositionalTracker::TRACKER_HAND_RIGHT);
+ }
+ // Use the ids we're giving to our "virtual" gamepads.
+ tracker->set_joy_id(p_controller_id + 100);
+ xr_server->add_tracker(tracker);
+ }
+
+ Input *input = Input::get_singleton();
+
+ float *tracker_matrix = godot_webxr_get_controller_transform(p_controller_id);
+ if (tracker_matrix) {
+ Transform transform = _js_matrix_to_transform(tracker_matrix);
+ tracker->set_position(transform.origin);
+ tracker->set_orientation(transform.basis);
+ free(tracker_matrix);
+ }
+
+ int *buttons = godot_webxr_get_controller_buttons(p_controller_id);
+ if (buttons) {
+ for (int i = 0; i < buttons[0]; i++) {
+ input->joy_button(p_controller_id + 100, i, *((float *)buttons + (i + 1)));
+ }
+ free(buttons);
+ }
+
+ int *axes = godot_webxr_get_controller_axes(p_controller_id);
+ if (axes) {
+ for (int i = 0; i < axes[0]; i++) {
+ Input::JoyAxis joy_axis;
+ joy_axis.min = -1;
+ joy_axis.value = *((float *)axes + (i + 1));
+ input->joy_axis(p_controller_id + 100, i, joy_axis);
+ }
+ free(axes);
+ }
+ } else if (tracker) {
+ xr_server->remove_tracker(tracker);
+ }
+}
+
+void WebXRInterfaceJS::_on_controller_changed() {
+ // Register "virtual" gamepads with Godot for the ones we get from WebXR.
+ godot_webxr_sample_controller_data();
+ for (int i = 0; i < 2; i++) {
+ bool controller_connected = godot_webxr_is_controller_connected(i);
+ if (controllers_state[i] != controller_connected) {
+ Input::get_singleton()->joy_connection_changed(i + 100, controller_connected, i == 0 ? "Left" : "Right", "");
+ controllers_state[i] = controller_connected;
+ }
+ }
+}
+
+void WebXRInterfaceJS::notification(int p_what) {
+ // Nothing to do here.
+}
+
+WebXRInterfaceJS::WebXRInterfaceJS() {
+ initialized = false;
+ session_mode = "inline";
+ requested_reference_space_types = "local";
+};
+
+WebXRInterfaceJS::~WebXRInterfaceJS() {
+ // and make sure we cleanup if we haven't already
+ if (initialized) {
+ uninitialize();
+ };
+};
+
+#endif // JAVASCRIPT_ENABLED
diff --git a/modules/webxr/webxr_interface_js.h b/modules/webxr/webxr_interface_js.h
new file mode 100644
index 0000000000..93da9a6d12
--- /dev/null
+++ b/modules/webxr/webxr_interface_js.h
@@ -0,0 +1,103 @@
+/*************************************************************************/
+/* webxr_interface_js.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 WEBXR_INTERFACE_JS_H
+#define WEBXR_INTERFACE_JS_H
+
+#ifdef JAVASCRIPT_ENABLED
+
+#include "webxr_interface.h"
+
+/**
+ @author David Snopek <david.snopek@snopekgames.com>
+
+ The WebXR interface is a VR/AR interface that can be used on the web.
+*/
+
+class WebXRInterfaceJS : public WebXRInterface {
+ GDCLASS(WebXRInterfaceJS, WebXRInterface);
+
+private:
+ bool initialized;
+
+ // @todo Should these really use enums instead of strings?
+ String session_mode;
+ String required_features;
+ String optional_features;
+ String requested_reference_space_types;
+ String reference_space_type;
+
+ bool controllers_state[2];
+
+ Transform _js_matrix_to_transform(float *p_js_matrix);
+ void _update_tracker(int p_controller_id);
+
+public:
+ virtual void is_session_supported(const String &p_session_mode) override;
+ virtual void set_session_mode(String p_session_mode) override;
+ virtual String get_session_mode() const override;
+ virtual void set_required_features(String p_required_features) override;
+ virtual String get_required_features() const override;
+ virtual void set_optional_features(String p_optional_features) override;
+ virtual String get_optional_features() const override;
+ virtual void set_requested_reference_space_types(String p_requested_reference_space_types) override;
+ virtual String get_requested_reference_space_types() const override;
+ void _set_reference_space_type(String p_reference_space_type);
+ virtual String get_reference_space_type() const override;
+ virtual XRPositionalTracker *get_controller(int p_controller_id) const override;
+ virtual String get_visibility_state() const override;
+ virtual PackedVector3Array get_bounds_geometry() const override;
+
+ virtual StringName get_name() const override;
+ virtual int get_capabilities() const override;
+
+ virtual bool is_initialized() const override;
+ virtual bool initialize() override;
+ virtual void uninitialize() override;
+
+ virtual Size2 get_render_targetsize() override;
+ virtual bool is_stereo() override;
+ virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override;
+ virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override;
+ virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override;
+ virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override;
+
+ virtual void process() override;
+ virtual void notification(int p_what) override;
+
+ void _on_controller_changed();
+
+ WebXRInterfaceJS();
+ ~WebXRInterfaceJS();
+};
+
+#endif // JAVASCRIPT_ENABLED
+
+#endif // WEBXR_INTERFACE_JS_H
diff --git a/modules/xatlas_unwrap/SCsub b/modules/xatlas_unwrap/SCsub
index c659349d05..aa6bdaea33 100644
--- a/modules/xatlas_unwrap/SCsub
+++ b/modules/xatlas_unwrap/SCsub
@@ -6,6 +6,9 @@ Import("env_modules")
env_xatlas_unwrap = env_modules.Clone()
# Thirdparty source files
+
+thirdparty_obj = []
+
if env["builtin_xatlas"]:
thirdparty_dir = "#thirdparty/xatlas/"
thirdparty_sources = [
@@ -17,7 +20,16 @@ if env["builtin_xatlas"]:
env_thirdparty = env_xatlas_unwrap.Clone()
env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
+ env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)
+ env.modules_sources += thirdparty_obj
+
# Godot source files
-env_xatlas_unwrap.add_source_files(env.modules_sources, "*.cpp")
+
+module_obj = []
+
+env_xatlas_unwrap.add_source_files(module_obj, "*.cpp")
+env.modules_sources += module_obj
+
+# Needed to force rebuilding the module files when the thirdparty library is updated.
+env.Depends(module_obj, thirdparty_obj)
diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp
index 8c5525bed3..9f6e7efb27 100644
--- a/modules/xatlas_unwrap/register_types.cpp
+++ b/modules/xatlas_unwrap/register_types.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */
@@ -30,7 +30,7 @@
#include "register_types.h"
-#include "core/error_macros.h"
+#include "core/error/error_macros.h"
#include "core/crypto/crypto_core.h"
@@ -42,7 +42,6 @@
extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, 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, int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache);
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, int p_index_count, float **r_uvs, int **r_vertices, int *r_vertex_count, int **r_indices, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y, int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache) {
-
CryptoCore::MD5Context ctx;
ctx.start();
@@ -137,15 +136,16 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver
pack_options.maxChartSize = 4096;
pack_options.blockAlign = true;
+ pack_options.padding = 1;
pack_options.texelsPerUnit = 1.0 / p_texel_size;
xatlas::Atlas *atlas = xatlas::Create();
printf("Adding mesh..\n");
- xatlas::AddMeshError::Enum err = xatlas::AddMesh(atlas, input_mesh, 1);
- ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Enum::Success, false, xatlas::StringForEnum(err));
+ xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1);
+ ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err));
printf("Generate..\n");
- xatlas::Generate(atlas, chart_options, nullptr, pack_options);
+ xatlas::Generate(atlas, chart_options, pack_options);
*r_size_hint_x = atlas->width;
*r_size_hint_y = atlas->height;
@@ -229,7 +229,6 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver
}
void register_xatlas_unwrap_types() {
-
array_mesh_lightmap_unwrap_callback = xatlas_mesh_lightmap_unwrap_callback;
}
diff --git a/modules/xatlas_unwrap/register_types.h b/modules/xatlas_unwrap/register_types.h
index fe924bab96..2ad729f172 100644
--- a/modules/xatlas_unwrap/register_types.h
+++ b/modules/xatlas_unwrap/register_types.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2021 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 */